forked from OpenGamePanel/OGP-Agent-Linux
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathogp_agent.pl
4312 lines (3846 loc) · 115 KB
/
ogp_agent.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/perl
#
# OGP - Open Game Panel
# Copyright (C) 2008 - 2018 The OGP Development Team
#
# http://www.opengamepanel.org/
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
use warnings;
use strict;
use Cwd; # Fast way to get the current directory
use lib getcwd();
use Frontier::Daemon::OGP::Forking; # Forking XML-RPC server
use File::Copy; # Simple file copy functions
use File::Copy::Recursive
qw(fcopy rcopy dircopy fmove rmove dirmove pathempty pathrmdir)
; # Used to copy whole directories
use File::Basename; # Used to get the file name or the directory name from a given path
use Crypt::XXTEA; # Encryption between webpages and agent.
use Cfg::Config; # Config file
use Cfg::Preferences; # Preferences file
use Fcntl ':flock'; # Import LOCK_* constants for file locking
use LWP::UserAgent; # Used for fetching URLs
use MIME::Base64; # Used to ensure data travelling right through the network.
use Getopt::Long; # Used for command line params.
use Path::Class::File; # Used to handle files and directories.
use File::Path qw(mkpath);
use Archive::Extract; # Used to handle archived files.
use File::Find;
use Schedule::Cron; # Used for scheduling tasks
# Compression tools
use IO::Compress::Bzip2 qw(bzip2 $Bzip2Error); # Used to compress files to bz2.
use Compress::Zlib; # Used to compress file download buffers to zlib.
use Archive::Tar; # Used to create tar, tgz or tbz archives.
use Archive::Zip qw( :ERROR_CODES :CONSTANTS ); # Used to create zip archives.
# Current location of the agent.
use constant AGENT_RUN_DIR => getcwd();
# Load our config file values
use constant AGENT_KEY => $Cfg::Config{key};
use constant AGENT_IP => $Cfg::Config{listen_ip};
use constant AGENT_LOG_FILE => $Cfg::Config{logfile};
use constant AGENT_PORT => $Cfg::Config{listen_port};
use constant AGENT_VERSION => $Cfg::Config{version};
use constant SCREEN_LOG_LOCAL => $Cfg::Preferences{screen_log_local};
use constant DELETE_LOGS_AFTER => $Cfg::Preferences{delete_logs_after};
use constant AGENT_PID_FILE =>
Path::Class::File->new(AGENT_RUN_DIR, 'ogp_agent.pid');
use constant STEAM_LICENSE_OK => "Accept";
use constant STEAM_LICENSE => $Cfg::Config{steam_license};
use constant MANUAL_TMP_DIR => Path::Class::Dir->new(AGENT_RUN_DIR, 'tmp');
use constant SHARED_GAME_TMP_DIR => Path::Class::Dir->new(AGENT_RUN_DIR, 'shared');
use constant STEAMCMD_CLIENT_DIR => Path::Class::Dir->new(AGENT_RUN_DIR, 'steamcmd');
use constant STEAMCMD_CLIENT_BIN =>
Path::Class::File->new(STEAMCMD_CLIENT_DIR, 'steamcmd.sh');
use constant SCREEN_LOGS_DIR =>
Path::Class::Dir->new(AGENT_RUN_DIR, 'screenlogs');
use constant GAME_STARTUP_DIR =>
Path::Class::Dir->new(AGENT_RUN_DIR, 'startups');
use constant SCREENRC_FILE =>
Path::Class::File->new(AGENT_RUN_DIR, 'ogp_screenrc');
use constant SCREENRC_TMP_FILE =>
Path::Class::File->new(AGENT_RUN_DIR, 'ogp_screenrc.tmp');
use constant SCREEN_TYPE_HOME => "HOME";
use constant SCREEN_TYPE_UPDATE => "UPDATE";
use constant FD_DIR => Path::Class::Dir->new(AGENT_RUN_DIR, 'FastDownload');
use constant FD_ALIASES_DIR => Path::Class::Dir->new(FD_DIR, 'aliases');
use constant FD_PID_FILE => Path::Class::File->new(FD_DIR, 'fd.pid');
use constant SCHED_PID => Path::Class::File->new(AGENT_RUN_DIR, 'scheduler.pid');
use constant SCHED_TASKS => Path::Class::File->new(AGENT_RUN_DIR, 'scheduler.tasks');
use constant SCHED_LOG_FILE => Path::Class::File->new(AGENT_RUN_DIR, 'scheduler.log');
$Cfg::Config{sudo_password} =~ s/('+)/'\"$1\"'/g;
our $SUDOPASSWD = $Cfg::Config{sudo_password};
my $no_startups = 0;
my $clear_startups = 0;
our $log_std_out = 0;
GetOptions(
'no-startups' => \$no_startups,
'clear-startups' => \$clear_startups,
'log-stdout' => \$log_std_out
);
# Starting the agent as root user is not supported anymore.
if ($< == 0)
{
print "ERROR: You are trying to start the agent as root user.";
print "This is not currently supported. If you wish to start the";
print "you need to create a normal user account for it.";
exit 1;
}
### Logger function.
### @param line the line that is put to the log file.
sub logger
{
my $logcmd = $_[0];
my $also_print = 0;
if (@_ == 2)
{
($also_print) = $_[1];
}
$logcmd = localtime() . " $logcmd\n";
if ($log_std_out == 1)
{
print "$logcmd";
return;
}
if ($also_print == 1)
{
print "$logcmd";
}
open(LOGFILE, '>>', AGENT_LOG_FILE)
or die("Can't open " . AGENT_LOG_FILE . " - $!");
flock(LOGFILE, LOCK_EX) or die("Failed to lock log file.");
seek(LOGFILE, 0, 2) or die("Failed to seek to end of file.");
print LOGFILE "$logcmd" or die("Failed to write to log file.");
flock(LOGFILE, LOCK_UN) or die("Failed to unlock log file.");
close(LOGFILE) or die("Failed to close log file.");
}
# Rotate the log file
if (-e AGENT_LOG_FILE)
{
if (-e AGENT_LOG_FILE . ".bak")
{
unlink(AGENT_LOG_FILE . ".bak");
}
logger "Rotating log file";
move(AGENT_LOG_FILE, AGENT_LOG_FILE . ".bak");
logger "New log file created";
}
open INPUTFILE, "<", SCREENRC_FILE or die $!;
open OUTPUTFILE, ">", SCREENRC_TMP_FILE or die $!;
my $dest = SCREEN_LOGS_DIR . "/screenlog.%t";
while (<INPUTFILE>)
{
$_ =~ s/logfile.*/logfile $dest/g;
print OUTPUTFILE $_;
}
close INPUTFILE;
close OUTPUTFILE;
unlink SCREENRC_FILE;
move(SCREENRC_TMP_FILE,SCREENRC_FILE);
# Check the screen logs folder
if (!-d SCREEN_LOGS_DIR && !mkdir SCREEN_LOGS_DIR)
{
logger "Could not create " . SCREEN_LOGS_DIR . " directory $!.", 1;
exit -1;
}
# Check the global shared games folder
if (!-d SHARED_GAME_TMP_DIR && !mkdir SHARED_GAME_TMP_DIR)
{
logger "Could not create " . SHARED_GAME_TMP_DIR . " directory $!.", 1;
exit -1;
}
if (check_steam_cmd_client() == -1)
{
print "ERROR: You must download and uncompress the new steamcmd package.";
print "BE SURE TO INSTALL IT IN " . AGENT_RUN_DIR . "/steamcmd directory,";
print "so it can be managed by the agent to install servers.";
exit 1;
}
# create the directory for startup flags
if (!-e GAME_STARTUP_DIR)
{
logger "Creating the startups directory " . GAME_STARTUP_DIR . "";
if (!mkdir GAME_STARTUP_DIR)
{
my $message =
"Failed to create the "
. GAME_STARTUP_DIR
. " directory - check permissions. Errno: $!";
logger $message, 1;
exit 1;
}
}
elsif ($clear_startups)
{
opendir(STARTUPDIR, GAME_STARTUP_DIR);
while (my $startup_file = readdir(STARTUPDIR))
{
# Skip . and ..
next if $startup_file =~ /^\./;
$startup_file = Path::Class::File->new(GAME_STARTUP_DIR, $startup_file);
logger "Removing " . $startup_file . ".";
unlink($startup_file);
}
closedir(STARTUPDIR);
}
# If the directory already existed check if we need to start some games.
elsif ($no_startups != 1)
{
# Loop through all the startup flags, and call universal startup
opendir(STARTUPDIR, GAME_STARTUP_DIR);
logger "Reading startup flags from " . GAME_STARTUP_DIR . "";
while (my $dirlist = readdir(STARTUPDIR))
{
# Skip . and ..
next if $dirlist =~ /^\./;
logger "Found $dirlist";
open(STARTFILE, '<', Path::Class::Dir->new(GAME_STARTUP_DIR, $dirlist))
|| logger "Error opening start flag $!";
while (<STARTFILE>)
{
my (
$home_id, $home_path, $server_exe,
$run_dir, $startup_cmd, $server_port,
$server_ip, $cpu, $nice, $preStart, $envVars, $game_key
) = split(',', $_);
if (is_screen_running_without_decrypt(SCREEN_TYPE_HOME, $home_id) ==
1)
{
logger
"This server ($server_exe on $server_ip : $server_port) is already running (ID: $home_id).";
next;
}
logger "Starting server_exe $server_exe from home $home_path.";
universal_start_without_decrypt(
$home_id, $home_path, $server_exe,
$run_dir, $startup_cmd, $server_port,
$server_ip, $cpu, $nice, $preStart, $envVars, $game_key
);
}
close(STARTFILE);
}
closedir(STARTUPDIR);
}
# Create the pid file
open(PID, '>', AGENT_PID_FILE)
or die("Can't write to pid file - " . AGENT_PID_FILE . "\n");
print PID "$$\n";
close(PID);
logger "Open Game Panel - Agent started - "
. AGENT_VERSION
. " - port "
. AGENT_PORT
. " - PID $$", 1;
# Stop previous scheduler process if exists
scheduler_stop();
# Create new object with default dispatcher for scheduled tasks
my $cron = new Schedule::Cron( \&scheduler_dispatcher, {
nofork => 1,
loglevel => 0,
log => sub { print $_[1], "\n"; }
} );
$cron->add_entry( "* * * * * *", \&scheduler_read_tasks );
# Run scheduler
$cron->run( {detach=>1, pid_file=>SCHED_PID} );
if(-e Path::Class::File->new(FD_DIR, 'Settings.pm'))
{
require "FastDownload/Settings.pm"; # Settings for Fast Download Daemon.
if(defined($FastDownload::Settings{autostart_on_agent_startup}) && $FastDownload::Settings{autostart_on_agent_startup} eq "1")
{
start_fastdl();
}
}
my $d = Frontier::Daemon::OGP::Forking->new(
methods => {
is_screen_running => \&is_screen_running,
universal_start => \&universal_start,
renice_process => \&renice_process,
cpu_count => \&cpu_count,
rfile_exists => \&rfile_exists,
quick_chk => \&quick_chk,
steam_cmd => \&steam_cmd,
fetch_steam_version => \&fetch_steam_version,
installed_steam_version => \&installed_steam_version,
automatic_steam_update => \&automatic_steam_update,
get_log => \&get_log,
stop_server => \&stop_server,
send_rcon_command => \&send_rcon_command,
dirlist => \&dirlist,
dirlistfm => \&dirlistfm,
readfile => \&readfile,
writefile => \&writefile,
rebootnow => \&rebootnow,
what_os => \&what_os,
start_file_download => \&start_file_download,
lock_additional_files => \&lock_additional_files,
is_file_download_in_progress => \&is_file_download_in_progress,
uncompress_file => \&uncompress_file,
discover_ips => \&discover_ips,
mon_stats => \&mon_stats,
exec => \&exec,
clone_home => \&clone_home,
remove_home => \&remove_home,
start_rsync_install => \&start_rsync_install,
rsync_progress => \&rsync_progress,
restart_server => \&restart_server,
sudo_exec => \&sudo_exec,
master_server_update => \&master_server_update,
secure_path => \&secure_path,
get_chattr => \&get_chattr,
ftp_mgr => \&ftp_mgr,
compress_files => \&compress_files,
stop_fastdl => \&stop_fastdl,
restart_fastdl => \&restart_fastdl,
fastdl_status => \&fastdl_status,
fastdl_get_aliases => \&fastdl_get_aliases,
fastdl_add_alias => \&fastdl_add_alias,
fastdl_del_alias => \&fastdl_del_alias,
fastdl_get_info => \&fastdl_get_info,
fastdl_create_config => \&fastdl_create_config,
agent_restart => \&agent_restart,
scheduler_add_task => \&scheduler_add_task,
scheduler_del_task => \&scheduler_del_task,
scheduler_list_tasks => \&scheduler_list_tasks,
scheduler_edit_task => \&scheduler_edit_task,
get_file_part => \&get_file_part,
stop_update => \&stop_update,
shell_action => \&shell_action,
remote_query => \&remote_query,
send_steam_guard_code => \&send_steam_guard_code,
steam_workshop => \&steam_workshop,
get_workshop_mods_info => \&get_workshop_mods_info
},
debug => 4,
LocalPort => AGENT_PORT,
LocalAddr => AGENT_IP,
ReuseAddr => '1'
) or die "Couldn't start OGP Agent: $!";
sub backup_home_log
{
my ($home_id, $log_file) = @_;
my $home_backup_dir = SCREEN_LOGS_DIR . "/home_id_" . $home_id;
if( ! -e $home_backup_dir )
{
if( ! mkdir $home_backup_dir )
{
logger "Can not create a backup directory at $home_backup_dir.";
return 1;
}
}
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
my $backup_file_name = $mday . $mon . $year . '_' . $hour . 'h' . $min . 'm' . $sec . "s.log";
my $output_path = $home_backup_dir . "/" . $backup_file_name;
# Used for deleting log files older than DELETE_LOGS_AFTER
my @file_list;
my @find_dirs; # directories to search
my $now = time(); # get current time
my $days;
if((DELETE_LOGS_AFTER =~ /^[+-]?\d+$/) && (DELETE_LOGS_AFTER > 0)){
$days = DELETE_LOGS_AFTER; # how many days old
}else{
$days = 30; # how many days old
}
my $seconds_per_day = 60*60*24; # seconds in a day
my $AGE = $days*$seconds_per_day; # age in seconds
push (@find_dirs, $home_backup_dir);
# Create local copy of log file backup in the log_backups folder and current user home directory if SCREEN_LOG_LOCAL = 1
if(SCREEN_LOG_LOCAL == 1)
{
# Create local backups folder
my $local_log_folder = Path::Class::Dir->new("logs_backup");
if(!-e $local_log_folder){
mkdir($local_log_folder);
}
# Add full path to @find_dirs so that log files older than DELETE_LOGS_AFTER are deleted
my $fullpath_to_local_logs = Path::Class::Dir->new(getcwd(), "logs_backup");
push (@find_dirs, $fullpath_to_local_logs);
my $log_local = $local_log_folder . "/" . $backup_file_name;
# Delete the local log file if it already exists
if(-e $log_local){
unlink $log_local;
}
# If the log file contains UPDATE in the filename, do not allow users to see it since it will contain steam credentials
# Will return -1 for not existing
my $isUpdate = index($log_file,SCREEN_TYPE_UPDATE);
if($isUpdate == -1){
copy($log_file,$log_local);
}
}
# Delete all files in @find_dirs older than DELETE_LOGS_AFTER days
find ( sub {
my $file = $File::Find::name;
if ( -f $file ) {
push (@file_list, $file);
}
}, @find_dirs);
for my $file (@file_list) {
my @stats = stat($file);
if ($now-$stats[9] > $AGE) {
unlink $file;
}
}
move($log_file,$output_path);
return 0;
}
sub get_home_pids
{
my ($home_id) = @_;
my $screen_id = create_screen_id(SCREEN_TYPE_HOME, $home_id);
my ($pid, @pids);
($pid) = split(/\./, `screen -ls | grep -E -o "[0-9]+\.$screen_id"`, 2);
if(defined $pid)
{
chomp($pid);
while ($pid =~ /^[0-9]+$/)
{
push(@pids,$pid);
$pid = `pgrep -P $pid`;
chomp($pid);
}
}
return @pids;
}
sub create_screen_id
{
my ($screen_type, $home_id) = @_;
return sprintf("OGP_%s_%09d", $screen_type, $home_id);
}
sub create_screen_cmd
{
my ($screen_id, $exec_cmd) = @_;
$exec_cmd = replace_OGP_Env_Vars($screen_id, "", "", $exec_cmd);
return
sprintf('export WINEDEBUG="fixme-all" && export DISPLAY=:1 && screen -d -m -t "%1$s" -c ' . SCREENRC_FILE . ' -S %1$s %2$s',
$screen_id, $exec_cmd);
}
sub create_screen_cmd_loop
{
my ($screen_id, $exec_cmd, $envVars, $skipLoop) = @_;
my $server_start_bashfile = $screen_id . "_startup_scr.sh";
$exec_cmd = replace_OGP_Env_Vars($screen_id, "", "", $exec_cmd);
# Allow file to be overwritten
if(-e $server_start_bashfile){
secure_path_without_decrypt('chattr-i', $server_start_bashfile);
}
# Create bash file that screen will run which spawns the server
# If it crashes without user intervention, it will restart
open (SERV_START_SCRIPT, '>', $server_start_bashfile);
my $respawn_server_command = "#!/bin/bash" . "\n";
if(!$skipLoop){
$respawn_server_command .= "function startServer(){" . "\n";
}
if(defined $envVars && $envVars ne ""){
$respawn_server_command .= $envVars;
}
if(!$skipLoop){
$respawn_server_command .= "NUMSECONDS=`expr \$(date +%s)`" . "\n"
. "until " . $exec_cmd . "; do" . "\n"
. "let DIFF=(`date +%s` - \"\$NUMSECONDS\")" . "\n"
. "if [ \"\$DIFF\" -gt 15 ]; then" . "\n"
. "NUMSECONDS=`expr \$(date +%s)`" . "\n"
. "echo \"Server '" . $exec_cmd . "' crashed with exit code \$?. Respawning...\" >&2 " . "\n"
. "fi" . "\n"
. "sleep 3" . "\n"
. "done" . "\n"
. "let DIFF=(`date +%s` - \"\$NUMSECONDS\")" . "\n"
. "if [ ! -e \"SERVER_STOPPED\" ] && [ \"\$DIFF\" -gt 15 ]; then" . "\n"
. "startServer" . "\n"
. "fi" . "\n"
. "}" . "\n"
. "startServer" . "\n";
}else{
$respawn_server_command .= $exec_cmd . "\n";
}
print SERV_START_SCRIPT $respawn_server_command;
close (SERV_START_SCRIPT);
# Secure file
secure_path_without_decrypt('chattr+i', $server_start_bashfile);
my $screen_exec_script = "bash " . $server_start_bashfile;
return
sprintf('export WINEDEBUG="fixme-all" && export DISPLAY=:1 && screen -d -m -t "%1$s" -c ' . SCREENRC_FILE . ' -S %1$s %2$s',
$screen_id, $screen_exec_script);
}
sub handle_lock_command_line{
my ($command) = @_;
if(defined $command && $command ne ""){
if ($command =~ m/{OGP_LOCK_FILE}/) {
$command =~ s/{OGP_LOCK_FILE}\s*//g;
return secure_path_without_decrypt("chattr+i", $command);
}
}
return 0;
}
sub replace_OGP_Env_Vars{
# This function replaces constants from environment variables set in the XML
my ($screen_id, $homeid, $homepath, $exec_cmd, $game_key) = @_;
# Handle steam specific replacements
if(defined $screen_id && $screen_id ne ""){
my $screen_id_for_txt_update = substr ($screen_id, rindex($screen_id, '_') + 1);
my $steamInsFile = $screen_id_for_txt_update . "_install.txt";
my $steamCMDPath = STEAMCMD_CLIENT_DIR;
my $fullPath = Path::Class::File->new($steamCMDPath, $steamInsFile);
# If the install file exists, the game can be auto updated, else it will be ignored by the game for improper syntax
# To generate the install file, the "Install/Update via Steam" button must be clicked on at least once!
if(-e $fullPath){
$exec_cmd =~ s/{OGP_STEAM_CMD_DIR}/$steamCMDPath/g;
$exec_cmd =~ s/{STEAMCMD_INSTALL_FILE}/$steamInsFile/g;
}
}
# Handle home directory replacement
if(defined $homepath && $homepath ne ""){
$exec_cmd =~ s/{OGP_HOME_DIR}/$homepath/g;
}
# Handle global game shared directory replacement
if(defined $game_key && $game_key ne ""){
my $readable_game_key = lc(substr($game_key, 0, rindex($game_key,"_")));
my $shared_path = Path::Class::Dir->new(SHARED_GAME_TMP_DIR, $readable_game_key);
# Create the folder if it doesn't exist
if (!-d $shared_path && !mkdir $shared_path)
{
logger "Could not create " . $shared_path . " directory $!.", 1;
}
$exec_cmd =~ s/{OGP_GAME_SHARED_DIR}/$shared_path/g;
}
return $exec_cmd;
}
sub encode_list
{
my $encoded_content = '';
if(@_)
{
foreach my $line (@_)
{
$encoded_content .= encode_base64($line, "") . '\n';
}
}
return $encoded_content;
}
sub decrypt_param
{
my ($param) = @_;
$param = decode_base64($param);
$param = Crypt::XXTEA::decrypt($param, AGENT_KEY);
$param = decode_base64($param);
return $param;
}
sub decrypt_params
{
my @params;
foreach my $param (@_)
{
$param = &decrypt_param($param);
push(@params, $param);
}
return @params;
}
sub check_steam_cmd_client
{
if (STEAM_LICENSE ne STEAM_LICENSE_OK)
{
logger "Steam license not accepted, stopping Steam client check.";
return 0;
}
if (!-d STEAMCMD_CLIENT_DIR && !mkdir STEAMCMD_CLIENT_DIR)
{
logger "Could not create " . STEAMCMD_CLIENT_DIR . " directory $!.", 1;
exit -1;
}
if (!-w STEAMCMD_CLIENT_DIR)
{
logger "Steam client dir '"
. STEAMCMD_CLIENT_DIR
. "' not writable. Unable to get Steam client.";
return -1;
}
if (!-f STEAMCMD_CLIENT_BIN)
{
logger "The Steam client, steamcmd, does not exist yet, installing...";
my $steam_client_file = 'steamcmd_linux.tar.gz';
my $steam_client_path = Path::Class::File->new(STEAMCMD_CLIENT_DIR, $steam_client_file);
my $steam_client_url =
"http://media.steampowered.com/client/" . $steam_client_file;
logger "Downloading the Steam client from $steam_client_url to '"
. $steam_client_path . "'.";
my $ua = LWP::UserAgent->new;
$ua->agent('Mozilla/5.0');
my $response = $ua->get($steam_client_url, ':content_file' => "$steam_client_path");
unless ($response->is_success)
{
logger "Failed to download steam installer from "
. $steam_client_url
. ".", 1;
return -1;
}
if (-f $steam_client_path)
{
logger "Uncompressing $steam_client_path";
if ( uncompress_file_without_decrypt($steam_client_path, STEAMCMD_CLIENT_DIR) != 1 )
{
unlink($steam_client_path);
logger "Unable to uncompress $steam_client_path, the file has been removed.";
return -1;
}
unlink($steam_client_path);
}
}
if (!-x STEAMCMD_CLIENT_BIN)
{
if ( ! chmod 0755, STEAMCMD_CLIENT_BIN )
{
logger "Unable to apply execution permission to ".STEAMCMD_CLIENT_BIN.".";
}
}
return 1;
}
sub is_screen_running
{
return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
my ($screen_type, $home_id) = decrypt_params(@_);
return is_screen_running_without_decrypt($screen_type, $home_id);
}
sub is_screen_running_without_decrypt
{
my ($screen_type, $home_id) = @_;
my $screen_id = create_screen_id($screen_type, $home_id);
my $is_running = `screen -list | grep $screen_id`;
if ($is_running =~ /^\s*$/)
{
return 0;
}
else
{
return 1;
}
}
# Delete Server Stopped Status File:
sub deleteStoppedStatFile
{
my ($home_path) = @_;
my $server_stop_status_file = Path::Class::File->new($home_path, "SERVER_STOPPED");
if(-e $server_stop_status_file)
{
unlink $server_stop_status_file;
}
}
# Universal startup function
sub universal_start
{
chomp(@_);
return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
return universal_start_without_decrypt(decrypt_params(@_));
}
# Split to two parts because of internal calls.
sub universal_start_without_decrypt
{
my (
$home_id, $home_path, $server_exe, $run_dir,
$startup_cmd, $server_port, $server_ip, $cpu, $nice, $preStart, $envVars, $game_key
) = @_;
if (is_screen_running_without_decrypt(SCREEN_TYPE_HOME, $home_id) == 1)
{
logger "This server is already running (ID: $home_id).";
return -14;
}
if (!-e $home_path)
{
logger "Can't find server's install path [ $home_path ].";
return -10;
}
my $uid = `id -u`;
chomp $uid;
my $gid = `id -g`;
chomp $gid;
my $path = $home_path;
$path =~ s/('+)/'\"$1\"'/g;
sudo_exec_without_decrypt('chown -Rf '.$uid.':'.$gid.' \''.$path.'\'');
# Some game require that we are in the directory where the binary is.
my $game_binary_dir = Path::Class::Dir->new($home_path, $run_dir);
if ( -e $game_binary_dir && !chdir $game_binary_dir)
{
logger "Could not change to server binary directory $game_binary_dir.";
return -12;
}
secure_path_without_decrypt('chattr-i', $server_exe);
if (!-x $server_exe)
{
if (!chmod 0755, $server_exe)
{
logger "The $server_exe file is not executable.";
return -13;
}
}
if(defined $preStart && $preStart ne ""){
# Get it in the format that the startup file can use
$preStart = multiline_to_startup_comma_format($preStart);
}else{
$preStart = "";
}
if(defined $envVars && $envVars ne ""){
# Replace variables in the envvars if they exist
my @prestartenvvars = split /[\r\n]+/, $envVars;
my $envVarStr = "";
foreach my $line (@prestartenvvars) {
$line = replace_OGP_Env_Vars("", $home_id, $home_path, $line, $game_key);
if($line ne ""){
logger "Configuring environment variable: $line";
$envVarStr .= "$line\n";
}
}
if(defined $envVarStr && $envVarStr ne ""){
$envVars = $envVarStr;
}
# Get it in the format that the startup file can use
$envVars = multiline_to_startup_comma_format($envVars);
}else{
$envVars = "";
}
secure_path_without_decrypt('chattr+i', $server_exe);
# Create startup file for the server.
my $startup_file =
Path::Class::File->new(GAME_STARTUP_DIR, "$server_ip-$server_port");
if (open(STARTUP, '>', $startup_file))
{
print STARTUP
"$home_id,$home_path,$server_exe,$run_dir,$startup_cmd,$server_port,$server_ip,$cpu,$nice,$preStart,$envVars";
logger "Created startup flag for $server_ip-$server_port";
close(STARTUP);
}
else
{
logger "Cannot create file in " . $startup_file . " : $!";
}
if(defined $preStart && $preStart ne ""){
# Get it in the format that the startup file can use
$preStart = startup_comma_format_to_multiline($preStart);
}else{
$preStart = "";
}
if(defined $envVars && $envVars ne ""){
# Get it in the format that the startup file can use
$envVars = startup_comma_format_to_multiline($envVars);
}else{
$envVars = "";
}
# Create the startup string.
my $screen_id = create_screen_id(SCREEN_TYPE_HOME, $home_id);
my $file_extension = substr $server_exe, -4;
my $cli_bin;
my $command;
my $run_before_start;
# Replace any OGP variables found in the command line
$startup_cmd = replace_OGP_Env_Vars($screen_id, $home_id, $home_path, $startup_cmd, $game_key);
if($file_extension eq ".exe" or $file_extension eq ".bat")
{
$command = "wine $server_exe $startup_cmd";
if ($cpu ne 'NA')
{
$command = "taskset -c $cpu wine $server_exe $startup_cmd";
}
if(defined($Cfg::Preferences{ogp_autorestart_server}) && $Cfg::Preferences{ogp_autorestart_server} eq "1"){
deleteStoppedStatFile($home_path);
$cli_bin = create_screen_cmd_loop($screen_id, $command, $envVars);
}else{
$cli_bin = create_screen_cmd_loop($screen_id, $command, $envVars, 1);
}
}
elsif($file_extension eq ".jar")
{
$command = "$startup_cmd";
if ($cpu ne 'NA')
{
$command = "taskset -c $cpu $startup_cmd";
}
if(defined($Cfg::Preferences{ogp_autorestart_server}) && $Cfg::Preferences{ogp_autorestart_server} eq "1"){
deleteStoppedStatFile($home_path);
$cli_bin = create_screen_cmd_loop($screen_id, $command, $envVars);
}else{
$cli_bin = create_screen_cmd_loop($screen_id, $command, $envVars, 1);
}
}
else
{
$command = "./$server_exe $startup_cmd";
if ($cpu ne 'NA')
{
$command = "taskset -c $cpu ./$server_exe $startup_cmd";
}
if(defined($Cfg::Preferences{ogp_autorestart_server}) && $Cfg::Preferences{ogp_autorestart_server} eq "1"){
deleteStoppedStatFile($home_path);
$cli_bin = create_screen_cmd_loop($screen_id, $command, $envVars);
}else{
$cli_bin = create_screen_cmd_loop($screen_id, $command, $envVars, 1);
}
}
my $log_file = Path::Class::File->new(SCREEN_LOGS_DIR, "screenlog.$screen_id");
backup_home_log( $home_id, $log_file );
logger
"Startup command [ $cli_bin ] will be executed in dir $game_binary_dir.";
# Run before start script
$run_before_start = run_before_start_commands($home_id, $home_path, $preStart);
system($cli_bin);
sleep(1);
renice_process_without_decrypt($home_id, $nice);
chdir AGENT_RUN_DIR;
return 1;
}
# This is used to change the priority of process
# @return 1 if successfully set prosess priority
# @return -1 in case of an error.
sub renice_process
{
return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
return renice_process_without_decrypt(decrypt_params(@_));
}
sub renice_process_without_decrypt
{
my ($home_id, $nice) = @_;
if ($nice != 0)
{
my @pids = get_home_pids($home_id);
logger
"Renicing pids [ @pids ] from home_id $home_id with nice value $nice.";
foreach my $pid (@pids)
{
my $rpid = kill 0, $pid;
if ($rpid == 1)
{
my $ret = sudo_exec_without_decrypt('/usr/bin/renice '.$nice.' '.$pid);
($ret) = split(/;/, $ret, 2);
if($ret != 1)
{
logger "Unable to renice process, probably bad sudo password or not in sudoers list.";
return -1
}
}
}
}
return 1;
}
# This is used to force a process to run on a particular CPU
sub force_cpu
{
return force_cpu_without_decrypt(decrypt_params(@_));
}
sub force_cpu_without_decrypt
{
my ($home_id, $cpu) = @_;
if ($cpu ne 'NA')
{
my @pids = get_home_pids($home_id);
logger
"Setting server from home_id $home_id with pids @pids to run on CPU $cpu.";
foreach my $pid (@pids)
{
my $rpid = kill 0, $pid;
if ($rpid == 1)
{
my $ret = sudo_exec_without_decrypt('/usr/bin/taskset -pc '.$cpu.' '.$pid);
($ret) = split(/;/, $ret, 2);
if($ret != 1)
{
logger "Unable to set cpu, probably a bad sudo password or not in sudoers list.";
return -1
}
}
}
}
return 1;
}
# Returns the number of CPUs available.
sub cpu_count
{
return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
if (!-e "/proc/cpuinfo")
{
return "ERROR - Missing /proc/cpuinfo";
}
open(CPUINFO, '<', "/proc/cpuinfo")
or return "ERROR - Cannot open /proc/cpuinfo";
my $cpu_count = 0;
while (<CPUINFO>)