-
Notifications
You must be signed in to change notification settings - Fork 16
/
spads.pl
15989 lines (14669 loc) · 593 KB
/
spads.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 -w
#
# SPADS: Spring Perl Autohost for Dedicated Server
#
# Copyright (C) 2008-2024 Yann Riou <yaribzh@gmail.com>
#
# 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 3 of the License, or
# (at your option) 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, see <http://www.gnu.org/licenses/>.
#
use strict;
use Config;
use Cwd 'cwd';
use Digest::MD5 'md5_base64';
use Fcntl qw':DEFAULT :flock';
use File::Copy;
use File::Spec::Functions qw'catfile file_name_is_absolute';
use FindBin;
use IPC::Cmd 'can_run';
use JSON::PP;
use List::Util qw'first any all none notall shuffle reduce';
use MIME::Base64;
use POSIX qw'ceil uname';
use Storable qw'nfreeze dclone nstore retrieve';
use Symbol qw'delete_package';
use Text::ParseWords;
use Time::HiRes;
use lib $FindBin::Bin;
use SimpleEvent;
use SimpleLog;
use SpadsConf;
use SpadsUpdater;
use SpringAutoHostInterface;
my $SLI_LOADING_ERROR;
BEGIN { eval {require SpringLobbyInterface; 1} or do { $SLI_LOADING_ERROR=$@;chomp($SLI_LOADING_ERROR) } }
use constant {
MSWIN32 => $^O eq 'MSWin32',
DARWIN => $^O eq 'darwin',
EXIT_SUCCESS => 0,
EXIT_FAILURE => 1,
# Command/environment problems
EXIT_USAGE => 2, # invalid usage
EXIT_CONFIG => 3, # invalid configuration
EXIT_DEPENDENCY => 4, # missing dependency
# Data/state problems
EXIT_CONFLICT => 16, # instance directory conflict
EXIT_INPUTDATA => 17, # inconsistent input data
# Other local problems
EXIT_SYSTEM => 32, # system call failure
EXIT_SOFTWARE => 33, # software failure
# Network/remote system problems
EXIT_REMOTE => 48, # network error or deny from remote system
EXIT_CERTIFICATE => 49, # invalid/untrusted certificate
EXIT_LOGIN => 50, # login failure
LOBBY_STATE_DISCONNECTED => 0,
LOBBY_STATE_CONNECTING => 1,
LOBBY_STATE_CONNECTED => 2,
LOBBY_STATE_LOGGED_IN => 3,
LOBBY_STATE_SYNCHRONIZED => 4,
LOBBY_STATE_OPENING_BATTLE => 5,
LOBBY_STATE_BATTLE_OPENED => 6,
};
if(MSWIN32) {
eval { require Win32; 1; }
or fatalError("$@Missing dependency: Win32 Perl module",EXIT_DEPENDENCY);
eval { require Win32::API; 1; }
or fatalError("$@Missing dependency: Win32::API Perl module",EXIT_DEPENDENCY);
eval { Win32::API->VERSION(0.73); 1; }
or fatalError("$@SPADS requires Win32::API module version 0.73 or superior, please update your Perl installation (Perl 5.16.2 or superior is recommended)",EXIT_DEPENDENCY);
eval { require Win32::TieRegistry; Win32::TieRegistry->import(':KEY_'); 1; }
or fatalError("$@Missing dependency: Win32::TieRegistry Perl module",EXIT_DEPENDENCY);
Win32::API->Import('msvcrt', 'int __cdecl _putenv (char* envstring)')
or fatalError('Failed to import _putenv function from msvcrt.dll ('.getLastWin32Error().')',EXIT_DEPENDENCY);
}else{
eval { require FFI::Platypus; 1; }
or fatalError("$@Missing dependency: FFI::Platypus Perl module",EXIT_DEPENDENCY);
}
SimpleEvent::addProxyPackage('SpadsPluginApi');
SimpleEvent::addProxyPackage('Inline');
# Constants ###################################################################
our $SPADS_VERSION='0.13.38';
our $spadsVer=$SPADS_VERSION; # TODO: remove this line when AutoRegister plugin versions < 0.3 are no longer used
our $CWD=cwd();
my $PATH_SEP=MSWIN32?';':':';
my @SPADS_PACKAGES=qw'spads.pl help.dat helpSettings.dat PerlUnitSync.pm springLobbyCertificates.dat SpringAutoHostInterface.pm SpringLobbyProtocol.pm SpringLobbyInterface.pm SimpleEvent.pm SimpleLog.pm SpadsConf.pm SpadsUpdater.pm SpadsPluginApi.pm argparse.py replay_upload.py';
if(MSWIN32) {
push(@SPADS_PACKAGES,'7za.exe');
}elsif(! DARWIN) {
push(@SPADS_PACKAGES,'7za');
}
my %IRC_COLORS;
my %NO_COLOR;
for my $i (0..15) {
$IRC_COLORS{$i}=''.sprintf('%02u',$i);
$NO_COLOR{$i}='';
}
my @IRC_STYLE=(\%IRC_COLORS,'');
my @NO_IRC_STYLE=(\%NO_COLOR,'');
my @READ_ONLY_SETTINGS=qw'description commandsfile battlepreset hostingpreset welcomemsg welcomemsgingame maplink ghostmaplink preset battlename advertmsg endgamecommand endgamecommandenv endgamecommandmsg';
my @OPTION_TYPES=qw'error bool list number string section';
my %MACOS_SYSTEM_INFO;
if(DARWIN) {
my $sysctlBin;
if(-x '/sbin/sysctl') {
$sysctlBin='/sbin/sysctl';
}elsif(-x '/usr/sbin/sysctl') {
$sysctlBin='/usr/sbin/sysctl';
}else{
$sysctlBin=can_run('sysctl');
}
if(defined $sysctlBin) {
my @sysctlOut=`$sysctlBin -a 2>/dev/null`;
foreach my $line (@sysctlOut) {
if($line =~ /^\s*([^:]*[^\s:])\s*:\s*(.*[^\s])\s*$/) {
$MACOS_SYSTEM_INFO{$1}=$2;
}
}
}
my $swVersBin;
if(-x '/bin/sw_vers') {
$swVersBin='/bin/sw_vers';
}elsif(-x '/usr/bin/sw_vers') {
$swVersBin='/usr/bin/sw_vers';
}else{
$swVersBin=can_run('sw_vers');
}
if(defined $swVersBin) {
my @swVersOut=`$swVersBin 2>/dev/null`;
foreach my $line (@swVersOut) {
if($line =~ /^\s*([^:]*[^\s:])\s*:\s*(.*[^\s])\s*$/) {
$MACOS_SYSTEM_INFO{$1}=$2;
}
}
}
}
my %SPADS_CORE_CMD_HANDLERS = (
addbot => \&hAddBot,
addbox => \&hAddBox,
advert => \&hAdvert,
auth => \&hAuth,
balance => \&hBalance,
ban => \&hBan,
banip => \&hBanIp,
banips => \&hBanIps,
bkick => \&hBKick,
bpreset => \&hBPreset,
boss => \&hBoss,
bset => \&hBSet,
callvote => \&hCallVote,
cancelquit => \&hCancelQuit,
cheat => \&hCheat,
chpasswd => \&hChpasswd,
chrank => \&hChrank,
chskill => \&hChskill,
ckick => \&hCKick,
clearbox => \&hClearBox,
closebattle => \&hCloseBattle,
endvote => \&hEndVote,
fixcolors => \&hFixColors,
force => \&hForce,
forcepreset => \&hForcePreset,
forcestart => \&hForceStart,
gkick => \&hGKick,
help => \&hHelp,
helpall => \&hHelpAll,
hoststats => \&hHostStats,
hpreset => \&hHPreset,
hset => \&hHSet,
joinas => \&hJoinAs,
kick => \&hKick,
kickban => \&hKickBan,
learnmaps => \&hLearnMaps,
list => \&hList,
loadboxes => \&hLoadBoxes,
lock => \&hLock,
maplink => \&hMapLink,
nextmap => \&hNextMap,
nextpreset => \&hNextPreset,
notify => \&hNotify,
openbattle => \&hOpenBattle,
plugin => \&hPlugin,
preset => \&hPreset,
promote => \&hPromote,
pset => \&hPSet,
quit => \&hQuit,
rebalance => \&hRebalance,
reloadarchives => \&hReloadArchives,
reloadconf => \&hReloadConf,
removebot => \&hRemoveBot,
rehost => \&hRehost,
resign => \&hResign,
restart => \&hRestart,
ring => \&hRing,
saveboxes => \&hSaveBoxes,
say => \&hSay,
searchuser => \&hSearchUser,
send => \&hSend,
sendlobby => \&hSendLobby,
set => \&hSet,
smurfs => \&hSmurfs,
specafk => \&hSpecAfk,
split => \&hSplit,
start => \&hStart,
stats => \&hStats,
status => \&hStatus,
stop => \&hStop,
unban => \&hUnban,
unbanip => \&hUnbanIp,
unbanips => \&hUnbanIps,
unlock => \&hUnlock,
unlockspec => \&hUnlockSpec,
update => \&hUpdate,
version => \&hVersion,
vote => \&hVote,
whois => \&hWhois,
'#skill' => \&hSkill );
my %SPADS_CORE_CMD_ALIASES=(
b => ['vote','b'],
coop => ['pSet','shareId'],
cv => ['callVote'],
ev => ['endVote'],
fb => ['force','*'],
h => ['help'],
map => ['set','map'],
n => ['vote','n'],
rc => ['reloadConf'],
rck => ['reloadConf','keepSettings'],
s => ['status'],
sb => ['status','battle'],
spec => ['force','%1%','spec'],
su => ['searchUser'],
us => ['unlockSpec'],
w => ['whois'],
y => ['vote','y'],
);
my %SPADS_CORE_API_HANDLERS = (
getPreferences => \&hApiGetPreferences,
getSettings => \&hApiGetSettings,
getVoteSettings => \&hApiGetVoteSettings,
status => \&hApiStatus,
);
my %SPADS_CORE_API_RIGHTS = (
getPreferences => 'list',
getSettings => 'list',
getVoteSettings => 'list',
);
my %ALERTS=('UPD-001' => 'Unable to check for SPADS update',
'UPD-002' => 'Major SPADS update available',
'UPD-003' => 'Unable to apply SPADS update',
'SPR-001' => 'Spring server crashed');
my %RANK_SKILL=(0 => 10,
1 => 13,
2 => 16,
3 => 20,
4 => 25,
5 => 30,
6 => 35,
7 => 38);
my %RANK_TRUESKILL=(0 => 20,
1 => 22,
2 => 23,
3 => 24,
4 => 25,
5 => 26,
6 => 28,
7 => 30);
our %JSONRPC_ERRORS = ( RATE_LIMIT_EXCEEDED => -1,
INSUFFICIENT_PRIVILEGES => -2,
UNKNOWN_ERROR => -3,
PARSE_ERROR => -32700,
INVALID_REQUEST => -32600,
METHOD_NOT_FOUND => -32601,
INVALID_PARAMS => -32602,
INTERNAL_ERROR => -32603,
SERVER_ERROR => -32000 );
my %JSONRPC_ERRORMSGS = ( -1 => 'Rate limit exceeded',
-2 => 'Insufficient privileges',
-3 => 'Unknown error',
-32700 => 'Parse error',
-32600 => 'Invalid request',
-32601 => 'Method not found',
-32602 => 'Invalid params',
-32603 => 'Internal error' );
map {$JSONRPC_ERRORMSGS{$_}='Server error'} (-32099..-32000);
my @DEFAULT_COLOR_ORDER=(qw'red blue green yellow cyan magenta orange purple teal gold azure pink lime gray');
# Command line parameters handling ############################################
invalidUsage() if($#ARGV < 0 || ! (-f $ARGV[0]));
my ($confFile,$genDoc,$tlsAction,$tlsHost,$tlsCert);
our %confMacros;
{
my @cmdLineArgs=@ARGV;
$confFile=shift(@cmdLineArgs);
my $p_macroData;
($p_macroData,$genDoc,$tlsAction,$tlsHost,$tlsCert)=parseCmdLineArgs(@cmdLineArgs);
invalidUsage() unless(defined $p_macroData);
%confMacros=%{$p_macroData};
}
# Default logging system ######################################################
my $sLog=SimpleLog->new(prefix => "[SPADS] ");
$SIG{__DIE__} = sub {
return unless(defined $^S && ! $^S);
my $msg=shift;
chomp($msg);
slog("Fatal error: $msg",0);
my $nestLevel=1;
while(my @callerData=caller($nestLevel++)) {
if($nestLevel>9) {
slog("Fatal error: ...",0);
last;
}else{
slog("Fatal error: $callerData[3] called at $callerData[1] line $callerData[2]",0);
}
}
};
$SIG{__WARN__} = sub {
my $msg=shift;
chomp($msg);
slog("PERL WARNING: $msg",1);
my $nestLevel=1;
while(my @callerData=caller($nestLevel++)) {
if($nestLevel>9) {
slog("PERL WARNING: ...",1);
last;
}else{
slog("PERL WARNING: $callerData[3] called at $callerData[1] line $callerData[2]",1);
}
}
};
# Configuration loading #######################################################
our $spads=SpadsConf->new($confFile,$sLog,\%confMacros);
fatalError('Unable to load SPADS configuration at startup',EXIT_CONFIG) unless($spads);
$sLog=$spads->{log};
# State variables #############################################################
#
# Already declared:
# . Command line parameters handling:
# my ($confFile,$genDoc,$tlsAction,$tlsHost,$tlsCert);
# our %confMacros;
#
# . Default logging system:
# my $sLog;
#
# . Configuration loading:
# our $spads;
#
my $masterChannel=$spads->{conf}{masterChannel};
$masterChannel=$1 if($masterChannel =~ /^([^\s]+)\s/);
my $spadsDir=File::Spec->canonpath($FindBin::Bin);
our %conf=%{$spads->{conf}};
my $abortSpadsStartForAutoUpdate=0;
my %quitAfterGame=(
action => undef, # 0: shutdown, 1: restart
condition => undef, # 0: no game is running, 1: no game is running and only spectators in battle lobby, 2: no game is running and battle lobby is empty
exitCode => EXIT_SUCCESS,
);
my $closeBattleAfterGame=0;
our %timestamps=(connectAttempt => 0,
ping => 0,
promote => 0,
autoRestore => 0,
battleChange => 0,
balance => 0,
autoBalance => 0,
fixColors => 0,
autoHostStart => time,
lastGameStart => 0,
lastGameStartPlaying => 0,
lastGameEnd => 0,
rotationEmpty => time,
dataDump => time,
autoUpdate => 0,
autoRestartCheck => 0,
autoForcePossible => 0,
archivesLoad => 0,
archivesCheck => 0,
mapLearned => 0,
autoStop => -1,
floodPurge => time,
advert => time,
gameOver => 0,
prefCachePurge => time,
usLockRequestForGameStart => 0);
my $syncedSpringVersion='';
my $fullSpringVersion='';
our $lobbyState=LOBBY_STATE_DISCONNECTED;
my %pendingRedirect;
my $lobbyBrokenConnection=0;
my $loadArchivesInProgress=0;
my %availableMapsNameToNb;
my @availableMaps;
my %availableModsNameToNb;
my @availableMods;
my ($currentNbNonPlayer,$currentLockedStatus)=(0,0);
my $currentMap=$conf{map};
my $targetMod="";
our $p_runningBattle={};
my %inGameAddedUsers;
my %inGameAddedPlayers;
my %runningBattleMapping;
my %runningBattleReversedMapping;
my $cheating=0;
my $p_gameOverResults={};
my %defeatTimes;
my $p_answerFunction;
our %currentVote=();
our $springPid=0;
my $springWin32Process;
my %endGameData;
my $nbEndGameCommandRunning=0;
my %gdr;
my %gdrIPs;
my @gdrQueue;
my $gdrLobbyBot='SpringLobbyMonitor';
my $sldbLobbyBot='SLDB';
my $gdrEnabled=0;
my %teamStats;
my %lastSentMessages;
my @messageQueue=();
my @lowPriorityMessageQueue=();
my %lastBattleMsg;
my %lastBattleStatus;
my %lastFloodKicks;
my %lastCmds;
my %ignoredUsers;
my $balanceState=0; # 0: not balanced, 1: balanced
my $colorsState=0; # 0: not fixed, 1: fixed
my @predefinedColors;
my %advColors;
my %balanceTarget;
my %colorsTarget;
my $manualLockedStatus=0;
my %currentPlayers;
my %currentSpecs;
my %forceSpecTimestamps;
my %pendingLocalBotManual;
my %pendingLocalBotAuto;
my %autoAddedLocalBots;
my %pendingFloodKicks;
my %pendingNotifications;
my %pendingSpecJoin;
my %lastRungUsers;
my $triedGhostWorkaround=0;
my $inGameTime=0;
my $accountInGameTime;
my ($os,$mem,$sysUptime,$cpuModel)=getSysInfo();
my %pendingAlerts;
my %alertedUsers;
my %springPrematureEndData=();
our %bosses=();
my $balRandSeed=intRand();
my %authenticatedUsers;
my $lanMode=0;
our @pluginsOrder;
my %pluginsReverseDeps;
our %plugins;
my %battleSkills;
our %battleSkillsCache;
my %pendingGetSkills;
my $currentGameType='Duel';
our $springServerType=$conf{springServerType};
my $springServerBin=$conf{springServer};
my %autoManagedEngineData=(mode => 'off');
my $failedEngineInstallVersion;
my $engineVersionAutoManagementInProgress;
my ($lockFh,$pidFile,$lockAcquired,$auLockFh,$periodicAutoUpdateLockAcquired,$usLockFhForGameStart);
my %prefCache;
my %prefCacheTs;
our %spadsCmdHandlers=%SPADS_CORE_CMD_HANDLERS;
our %spadsApiHandlers=%SPADS_CORE_API_HANDLERS;
our %spadsApiRights=%SPADS_CORE_API_RIGHTS;
my %nbRelayedApiCalls;
my %ignoredRelayedApiUsers;
my %pendingRelayedJsonRpcChunks;
my %sentPlayersScriptTags;
my $simpleEventLoopStopping;
our $unitsync;
my %unitsyncOptFuncs;
my %unitsyncHostHashes;
my $lobbyReconnectDelay;
my $useTls;
my %hostingParams;
my $lobbySimpleLog=SimpleLog->new(logFiles => [$conf{logDir}."/spads.log",''],
logLevels => [$conf{lobbyInterfaceLogLevel},3],
useANSICodes => [0,-t STDOUT ? 1 : 0],
useTimestamps => [1,-t STDOUT ? 0 : 1],
prefix => "[SpringLobbyInterface] ");
my $autohostSimpleLog=SimpleLog->new(logFiles => [$conf{logDir}."/spads.log"],
logLevels => [$conf{autoHostInterfaceLogLevel}],
useANSICodes => [0],
useTimestamps => [1],
prefix => "[SpringAutoHostInterface] ");
my $updaterSimpleLog=SimpleLog->new(logFiles => [$conf{logDir}."/spads.log",""],
logLevels => [$conf{updaterLogLevel},3],
useANSICodes => [0,-t STDOUT ? 1 : 0],
useTimestamps => [1,-t STDOUT ? 0 : 1],
prefix => "[SpadsUpdater] ");
my $simpleEventSimpleLog=SimpleLog->new(logFiles => [$conf{logDir}.'/spads.log',''],
logLevels => [$conf{simpleEventLogLevel},3],
useANSICodes => [0,-t STDOUT ? 1 : 0],
useTimestamps => [1,-t STDOUT ? 0 : 1],
prefix => "[SimpleEvent] ");
our $lobby;
$lobby = SpringLobbyInterface->new(serverHost => $conf{lobbyHost},
serverPort => $conf{lobbyPort},
simpleLog => $lobbySimpleLog,
warnForUnhandledMessages => 0,
inconsistencyHandler => sub { $lobbyBrokenConnection=1; } )
unless($SLI_LOADING_ERROR);
our $autohost = SpringAutoHostInterface->new(autoHostPort => $conf{autoHostPort},
simpleLog => $autohostSimpleLog,
warnForUnhandledMessages => 0);
my $updater = SpadsUpdater->new(sLog => $updaterSimpleLog,
repository => "http://planetspads.free.fr/spads/repository",
release => $conf{autoUpdateRelease},
packages => \@SPADS_PACKAGES,
springDir => $conf{autoManagedSpringDir});
# Binaries update (Windows only) ##############################################
if(MSWIN32) {
if(opendir(BINDIR,$spadsDir)) {
my @toBeDeletedFiles = grep {/\.toBeDeleted$/} readdir(BINDIR);
closedir(BINDIR);
my @toBeDelAbsNames=map("$spadsDir/$_",@toBeDeletedFiles);
unlink @toBeDelAbsNames;
}
my %updatedPackages;
if(-f "$spadsDir/updateInfo.txt") {
if(open(UPDATE_INFO,"<$spadsDir/updateInfo.txt")) {
while(local $_ = <UPDATE_INFO>) {
$updatedPackages{$1}=$2 if(/^([^:]+):(.+)$/);
}
close(UPDATE_INFO);
}else{
fatalError("Unable to read \"$spadsDir/updateInfo.txt\" file",EXIT_SYSTEM);
}
}
foreach my $updatedPackage (keys %updatedPackages) {
my $updatedPackagePath=catfile($spadsDir,$updatedPackage);
my $versionedUpdatedPackagePath=catfile($spadsDir,$updatedPackages{$updatedPackage});
next unless($updatedPackage =~ /\.(exe|dll)$/ && -f $versionedUpdatedPackagePath);
if(-f $updatedPackagePath) {
my @origStat=stat($versionedUpdatedPackagePath);
my @destStat=stat($updatedPackagePath);
next if($origStat[9] <= $destStat[9]);
unlink($updatedPackagePath);
renameToBeDeleted($updatedPackagePath) if(-f $updatedPackagePath);
}
if(! copy($versionedUpdatedPackagePath,$updatedPackagePath)) {
fatalError("Unable to copy \"$versionedUpdatedPackagePath\" to \"$updatedPackagePath\", system consistency must be checked manually !",EXIT_SYSTEM);
}
slog("Copied \"$versionedUpdatedPackagePath\" to \"$updatedPackagePath\" (Windows binary update mode)",5);
}
}
# TLS certificates management #################################################
if(defined $tlsAction && ($tlsAction eq 'revoke' || $tlsAction eq 'list' || defined $tlsCert)) {
$tlsHost//=$conf{lobbyHost} unless($tlsAction eq 'list');
my $exitCode=EXIT_SUCCESS;
if($tlsAction eq 'trust') {
my $res=$spads->addTrustedCertificateHash({lobbyHost => $tlsHost, certHash => $tlsCert});
if($res) {
slog("Added trusted certificate hash (SHA-256) $tlsCert for host $tlsHost",3);
}else{
$exitCode=EXIT_INPUTDATA;
slog('Failed to add trusted certificate!',1);
}
}elsif($tlsAction eq 'revoke') {
my $res=$spads->removeTrustedCertificateHash({lobbyHost => $tlsHost, certHash => $tlsCert});
if($res) {
slog("Revoked certificate hash (SHA-256) $tlsCert for host $tlsHost",3);
}else{
$exitCode=EXIT_INPUTDATA;
slog('Failed to revoke certificate!',1) unless($res);
}
}else{
my $r_trustedCerts=$spads->getTrustedCertificateHashes();
my @trustedCerts;
foreach my $lobbyHost (keys %{$r_trustedCerts}) {
next if(defined $tlsHost && $lobbyHost ne $tlsHost);
foreach my $lobbyCert (keys %{$r_trustedCerts->{$lobbyHost}}) {
push(@trustedCerts,{host => $lobbyHost, hash => $lobbyCert});
}
}
if(@trustedCerts) {
print 'Trusted lobby certificate hash'.($#trustedCerts>0?'es':'').' (SHA-256)'.(defined $tlsHost ? " for host $tlsHost" : '').":\n";
foreach my $r_trustedCert (@trustedCerts) {
if(defined $tlsHost) {
print " - $r_trustedCert->{hash}\n";
}else{
print " - host:$r_trustedCert->{host}, hash:$r_trustedCert->{hash}\n";
}
}
}else{
print 'No trusted lobby certificate'.(defined $tlsHost ? " for host $tlsHost" : '')."!\n";
}
}
exit $exitCode;
}
if($conf{lobbyTls} ne 'off') {
$useTls = eval {require IO::Socket::SSL; 1};
fatalError('Module IO::Socket::SSL required for TLS support',EXIT_DEPENDENCY) if($conf{lobbyTls} eq 'on' && ! $useTls);
}
# Console title update (Windows only) #########################################
if(MSWIN32) {
eval {
require Win32::Console;
my $title=$conf{lobbyLogin};
$title.="\@$conf{lobbyHost}" if($conf{lobbyHost} ne 'lobby.springrts.com' || $conf{lobbyPort} != 8200);
$title.=":$conf{lobbyPort}" if($conf{lobbyPort} != 8200);
$title.=" (SPADS $SPADS_VERSION)";
Win32::Console->new()->Title($title);
};
}
# Subfunctions ################################################################
sub invalidUsage {
print "usage: perl $0 <configurationFile> [--doc] [<macroName>=<macroValue> [...]]\n";
print <<EOH;
perl $0 <configurationFile> --tls-cert-trust
perl $0 <configurationFile> --tls-cert-trust=<certificateHash>
perl $0 <configurationFile> --tls-cert-trust=<hostName>:<certificateHash>
perl $0 <configurationFile> --tls-cert-revoke=<certificateHash>
perl $0 <configurationFile> --tls-cert-revoke=<hostName>:<certificateHash>
perl $0 <configurationFile> --tls-cert-list
perl $0 <configurationFile> --tls-cert-list=<hostName>
EOH
exit EXIT_USAGE;
}
sub parseCmdLineArgs {
my $parsedGenDoc=0;
my ($parsedTlsAction,$parsedTlsHost,$parsedTlsCert);
my %macros;
foreach my $arg (@_) {
if($arg =~ /^--tls-cert-(trust|revoke|list)(?:=(.+))?$/i) {
return undef if(defined $parsedTlsAction);
$parsedTlsAction=lc($1);
my $tlsParam=lc($2) if(defined $2);
if(defined $tlsParam) {
if($parsedTlsAction eq 'list') {
return undef unless($tlsParam =~ /^\w[\w\-\.]*$/);
$parsedTlsHost=$tlsParam;
}elsif($tlsParam =~ /^(\w[\w\-\.]*):([\da-f]+)$/) {
($parsedTlsHost,$parsedTlsCert)=($1,$2);
}elsif($tlsParam =~ /^[\da-f]+$/) {
$parsedTlsCert=$tlsParam;
}else{
return undef;
}
}else{
return undef if($parsedTlsAction eq 'revoke');
}
}elsif($arg =~ /^([\w\:]+)=(.*)$/) {
$macros{$1}=$2;
}elsif($arg eq "--doc") {
$parsedGenDoc=1;
}else{
return undef;
}
}
return (\%macros,$parsedGenDoc,$parsedTlsAction,$parsedTlsHost,$parsedTlsCert);
}
sub parseMacroTokens {
my %macros;
foreach my $macroToken (@_) {
if($macroToken =~ /^([\w\:]+)=(.*)$/) {
$macros{$1}=$2;
}else{
return undef;
}
}
return \%macros;
}
sub slog { $sLog->log(@_) }
sub fatalError {
my ($m,$ec)=@_;
$ec//=EXIT_SOFTWARE;
defined $sLog ? $sLog->log($m,0) : print STDERR $m."\n";
unlink($pidFile) if($lockAcquired);
exit $ec;
}
sub intRand {
rand() =~ /\.(\d+)/;
return $1 % 99999999;
}
sub renameToBeDeleted {
my $fileName=shift;
my $i=1;
while(-f "$fileName.$i.toBeDeleted" && $i < 100) {
$i++;
}
return move($fileName,"$fileName.$i.toBeDeleted");
}
sub int32 { return unpack('l',pack('l',shift)) }
sub uint32 { return unpack('L',pack('L',shift)) }
sub hasEvalError {
if($@) {
chomp($@);
return 1;
}else{
return 0;
}
}
sub getPerlModuleVersion {
my @moduleParts=split(/::/,shift);
my $r_symtab=\%::;
while (my $nextModulePart=shift(@moduleParts)) {
return undef unless(exists $r_symtab->{"$nextModulePart\::"});
$r_symtab=$r_symtab->{"$nextModulePart\::"};
}
return undef unless(exists $r_symtab->{VERSION});
return ${$r_symtab->{VERSION}};
}
sub onSpringProcessExit {
my (undef,$exitCode,$signalNb,$hasCoreDump)=@_;
$signalNb//=0;
$hasCoreDump//=0;
if($usLockFhForGameStart) {
close($usLockFhForGameStart);
undef $usLockFhForGameStart;
}
if(%{$p_runningBattle}) {
%springPrematureEndData=(ec => $exitCode, ts => time, signal => $signalNb, core => $hasCoreDump);
}else{
my $gameRunningTime=secToTime(time-$timestamps{lastGameStart});
if(($exitCode && $exitCode != 255) || $signalNb || $hasCoreDump) {
$autohost->serverQuitHandler() if($autohost->{state});
my $logMsg="Spring crashed (running time: $gameRunningTime";
if($signalNb) {
$logMsg.=", interrupted by signal $signalNb";
$logMsg.=", exit code: $exitCode" if($exitCode);
}else{
$logMsg.=", exit code: $exitCode";
}
$logMsg.=', core dumped' if($hasCoreDump);
$logMsg.=')';
slog($logMsg,1);
broadcastMsg("Spring crashed ! (running time: $gameRunningTime)");
addAlert('SPR-001');
}else{
slog('Spring server detected sync errors during game',2) if($exitCode == 255);
broadcastMsg("Server stopped (running time: $gameRunningTime)");
endGameProcessing();
delete $pendingAlerts{'SPR-001'};
}
$inGameTime+=time-$timestamps{lastGameStart};
setAsOutOfGame();
}
}
sub onUpdaterCallEnd {
my $updateRc=shift;
if($updateRc < 0) {
if($updateRc > -7 || $updateRc == -12) {
delete @pendingAlerts{('UPD-002','UPD-003')};
addAlert('UPD-001');
}elsif($updateRc == -7) {
delete @pendingAlerts{('UPD-001','UPD-003')};
addAlert('UPD-002');
}else{
delete @pendingAlerts{('UPD-001','UPD-002')};
addAlert('UPD-003');
}
}else{
delete @pendingAlerts{('UPD-001','UPD-002','UPD-003')};
}
if(isRestartForUpdateApplicable() && (! $updater->isUpdateInProgress())) {
autoRestartForUpdateIfNeeded();
}
}
sub getLastWin32Error {
my $errorNb=Win32::GetLastError();
return 'unknown error' unless($errorNb);
my $errorMsg=Win32::FormatMessage($errorNb)//($^E=$errorNb);
$errorMsg=~s/\cM?\cJ$//;
return $errorMsg;
}
sub escapeWin32Parameter {
my $arg = shift;
$arg =~ s/(\\*)"/$1$1\\"/g;
if($arg =~ /[ \t\(]/) {
$arg =~ s/(\\*)$/$1$1/;
$arg = "\"$arg\"";
}
return $arg;
}
sub portableExec {
my ($program,@params)=@_;
my @args=($program,@params);
@args=map {escapeWin32Parameter($_)} @args if(MSWIN32);
return exec {$program} @args;
}
sub execError {
my ($msg,$level)=@_;
slog($msg,$level);
exit EXIT_FAILURE;
}
sub autoRetry {
my ($p_f,$retryNb,$delayMs)=@_;
$retryNb//=50;
$delayMs//=100;
my $delayUs=1000*$delayMs;
my $res=&{$p_f}();
while(! $res) {
return 0 unless($retryNb--);
Time::HiRes::usleep($delayUs);
$res=&{$p_f}();
}
return $res;
}
sub areSamePaths {
my ($p1,$p2)=map {File::Spec->canonpath($_)} @_;
($p1,$p2)=map {lc($_)} ($p1,$p2) if(MSWIN32);
return $p1 eq $p2;
}
sub splitPaths {
my $pathsString=shift;
return () unless(defined $pathsString);
return split(/$PATH_SEP/,$pathsString);
}
sub setEnvVarFirstPaths {
my ($varName,@firstPaths)=@_;
my $needRestart=0;
fatalError("Unable to handle path containing \"$PATH_SEP\" character!") if(any {index($_,$PATH_SEP) != -1} @firstPaths);
$ENV{"SPADS_$varName"}=$ENV{$varName}//'_UNDEF_' unless(exists $ENV{"SPADS_$varName"});
my @currentPaths=split(/$PATH_SEP/,$ENV{$varName}//'');
$needRestart=1 if($#currentPaths < $#firstPaths);
if(! $needRestart) {
for my $i (0..$#firstPaths) {
if(! areSamePaths($currentPaths[$i],$firstPaths[$i])) {
$needRestart=1;
last;
}
}
}
if($needRestart) {
my @origPaths=$ENV{"SPADS_$varName"} eq '_UNDEF_' ? () : split(/$PATH_SEP/,$ENV{"SPADS_$varName"});
my @newPaths;
foreach my $path (@origPaths) {
push(@newPaths,$path) unless(any {areSamePaths($path,$_)} @firstPaths);
}
$ENV{$varName}=join($PATH_SEP,@firstPaths,@newPaths);
}
return $needRestart;
}
sub exportWin32EnvVar {
my $envVar=shift;
my $envVarDef="$envVar=".($ENV{$envVar}//'');
fatalError("Unable to export environment variable definition \"$envVarDef\"",EXIT_SYSTEM) unless(int32(_putenv($envVarDef)) == 0);
}
sub setSpringEnv {
my @dataDirs=@_;
setEnvVarFirstPaths('SPRING_DATADIR',@dataDirs);
exportWin32EnvVar('SPRING_DATADIR') if(MSWIN32);
$ENV{SPRING_WRITEDIR}=$dataDirs[0] unless(areSamePaths($dataDirs[0],$ENV{SPRING_WRITEDIR}//''));
exportWin32EnvVar('SPRING_WRITEDIR') if(MSWIN32);
eval {require PerlUnitSync};
fatalError("Unable to load PerlUnitSync module ($@)") if (hasEvalError());
$unitsync = eval {PerlUnitSync->new($conf{unitsyncDir} eq '' ? $dataDirs[1] : $conf{unitsyncDir})};
fatalError($@) if (hasEvalError());
fatalError("Failed to load unitsync library from \"$conf{unitsyncDir}\" - unknown error") unless(defined $unitsync);
map {$unitsyncOptFuncs{$_}=1 if($unitsync->hasFunc($_))} (qw'GetMapInfoCount GetMacAddrHash GetSysInfoHash');
$unitsyncHostHashes{macAddr}=$unitsync->GetMacAddrHash() if($unitsyncOptFuncs{GetMacAddrHash});
$unitsyncHostHashes{sysInfo}=$unitsync->GetSysInfoHash() if($unitsyncOptFuncs{GetSysInfoHash});
}
sub setSpringServerBin {
my $baseDir=shift;
$springServerBin=catfile($baseDir,"spring-$springServerType".(MSWIN32?'.exe':''));
}
sub generateGameId {
my @gameIdChars=split('','1234567890abcdef');
my $gameId='SPADS-';
for my $i (1..26) {
$gameId.=$gameIdChars[int(rand($#gameIdChars+1))];
}
return $gameId;
}
sub compareVersionElem {
my ($v1,$v2)=@_;
my ($v1Nb,$v1Str,$v2Nb,$v2Str);
if($v1 =~ /^(\d+)(.*)$/) {
($v1Nb,$v1Str)=($1,$2);
}else{
($v1Nb,$v1Str)=(0,$v1);
}
if($v2 =~ /^(\d+)(.*)$/) {
($v2Nb,$v2Str)=($1,$2);
}else{
($v2Nb,$v2Str)=(0,$v2);
}
return 1 if($v1Nb > $v2Nb);
return -1 if($v1Nb < $v2Nb);
return 1 if($v1Str gt $v2Str);
return -1 if($v1Str lt $v2Str);
return 0;
}
sub compareVersions {
my ($ver1,$ver2)=@_;
my @v1=split(/\./,$ver1);
my @v2=split(/\./,$ver2);
my $maxSize=$#v1 > $#v2 ? $#v1 : $#v2;
for my $i (0..$maxSize) {
my ($val1,$val2)=(0,0);
$val1=$v1[$i] if(defined $v1[$i]);
$val2=$v2[$i] if(defined $v2[$i]);
my $comp=compareVersionElem($val1,$val2);
return $comp if($comp);