-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathslMonitor.pl
executable file
·1625 lines (1492 loc) · 74.7 KB
/
slMonitor.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
#
# This file implements the Spring lobby monitoring functionality for SLDB
# (slMonitor), it is part of SLDB.
#
# slMonitor is a Spring lobby bot, it serves 2 main purposes:
# - monitor and store all lobby data (users, battles...) into SLDB in realtime
# - receive, check, and store game data reports (GDR) sent by SPADS into SLDB
#
# Copyright (C) 2013-2022 Yann Riou <yaribzh@gmail.com>
#
# SLDB 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.
#
# SLDB 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 SLDB. If not, see <http://www.gnu.org/licenses/>.
#
use strict;
use File::Basename qw/dirname fileparse/;
use File::Spec::Functions qw/catdir catfile file_name_is_absolute rel2abs/;
use File::Path;
use IO::Select;
use MIME::Base64;
use Storable qw(thaw);
my ($scriptBaseName,$scriptDir)=fileparse(rel2abs($0),'.pl');
unshift(@INC,$scriptDir);
require SimpleConf;
require SimpleLog;
require Sldb;
require SpringLobbyInterface;
my $slMonVer='0.5';
$SIG{TERM} = \&sigTermHandler;
$SIG{USR1} = \&sigUsr1Handler;
my $confFile=catfile($scriptDir,'etc',"$scriptBaseName.conf");
$confFile=$ARGV[0] if($#ARGV == 0);
if($#ARGV > 0 || ! -f $confFile) {
print "usage: $0 [<confFile>]\n";
exit 1;
}
my %conf=(lobbyHost => 'lobby.springrts.com',
lobbyPort => 8200,
lobbyLogin => 'SpringLobbyMonitor',
lobbyPassword => undef,
lobbyAdminIds => undef,
logLevel => 4,
sldbLogLevel => 4,
lobbyLogLevel => 4,
logFile => catfile('var','log',"$scriptBaseName.log"),
logPvDir => catdir('var','log','slMonPv'),
dbName => 'sldb',
dbLogin => $scriptBaseName,
dbPwd => undef,
minGameLength => 180,
maxChatMessageLength => 512,
tsTolerance => 30,
dynIpThreshold => 30,
dynIpRange => 512);
SimpleConf::readConf($confFile,\%conf);
my $logFile=$conf{logFile};
$logFile=catfile($scriptDir,$logFile) unless(file_name_is_absolute($logFile));
mkpath(dirname($logFile));
my $logPvDir=$conf{logPvDir};
$logPvDir=catdir($scriptDir,$logPvDir) unless(file_name_is_absolute($logPvDir));
mkpath($logPvDir);
my $dbDs=$conf{dbName};
$dbDs="DBI:mysql:database=$dbDs;host=localhost" unless($dbDs =~ /^DBI:/i);
my @lobbyAdminIds=split(/,/,$conf{lobbyAdminIds});
my $sLog=SimpleLog->new(logFiles => [$logFile,''],
logLevels => [$conf{logLevel},3],
useANSICodes => [0,1],
useTimestamps => [1,1],
prefix => "[slMonitor] ");
my $sLogSldb=SimpleLog->new(logFiles => [$logFile,''],
logLevels => [$conf{sldbLogLevel},3],
useANSICodes => [0,1],
useTimestamps => [1,1],
prefix => "[SLDB] ");
my $sLogLobby=SimpleLog->new(logFiles => [$logFile],
logLevels => [$conf{lobbyLogLevel}],
useANSICodes => [0],
useTimestamps => [1],
prefix => "[SpringLobbyInterface] ");
my $lobby = SpringLobbyInterface->new(serverHost => $conf{lobbyHost},
serverPort => $conf{lobbyPort},
simpleLog => $sLogLobby,
warnForUnhandledMessages => 0);
my %commands=( quit => \&hQuit,
restart => \&hRestart,
setloglevel => \&hSetLogLevel,
status => \&hStatus);
sub slog {
$sLog->log(@_);
}
sub error {
my $m=shift;
slog($m,0);
exit 1;
}
sub nonFatalError {
my $m=shift;
slog($m,1);
}
sub logMsg {
my ($file,$msg)=@_;
if(! open(CHAT,">>$logPvDir/$file.log")) {
slog("Unable to log chat message into file \"$logPvDir/$file.log\"",1);
return;
}
my $dateTime=localtime();
print CHAT "[$dateTime] $msg\n";
close(CHAT);
}
sub forkedError {
my ($msg,$level)=@_;
slog($msg,$level);
exit 1;
}
my $stopping=0; # (0:running, 1:quitting, 2:restarting)
my $lobbyState=0; # (0:not_connected, 1:connecting, 2: connected, 3:logged_in, 4:start_data_received)
my %timestamps=(connectAttempt => 0,
ping => 0);
my %hosts;
my %battles;
my %unmonitoredGames;
my %monitoredBattles;
my %monitoredGames;
my %GDRs;
my $lSock;
my $sldb=Sldb->new({dbDs => $dbDs,
dbLogin => $conf{dbLogin},
dbPwd => $conf{dbPwd},
sLog => $sLogSldb,
sqlErrorHandler => \&error});
$sldb->connect();
$sldb->do("set session time_zone = '+0:00'","set UTC timezone to avoid DST problems");
sub sigTermHandler {
slog('SIGTERM signal received, exiting...',2);
$stopping=1;
}
sub sigUsr1Handler {
slog('SIGUSR1 signal received, restarting...',2);
$stopping=2;
}
sub cbLobbyConnect {
$lobbyState=2;
if($_[4]) {
slog("Lobby server is running in LAN mode, disconnecting...",2);
$lobbyState=0;
$lobby->disconnect();
return;
}
$lobby->addPreCallbacks({REMOVEUSER => \&cbPreRemoveUser,
CLIENTSTATUS => \&cbPreClientStatus});
$lobby->addCallbacks({LOGININFOEND => \&cbLoginInfoEnd,
ADDUSER => \&cbAddUser,
BATTLEOPENED => \&cbBattleOpened,
BATTLECLOSED => \&cbBattleClosed,
REMOVEUSER => \&cbRemoveUser,
UPDATEBATTLEINFO => \&cbUpdateBattleInfo,
CLIENTSTATUS => \&cbClientStatus,
JOINEDBATTLE => \&cbJoinedBattle,
LEFTBATTLE => \&cbLeftBattle,
SAIDPRIVATE => \&cbSaidPrivate,
SERVERMSG => \&cbServerMsg,
BROADCAST => \&cbBroadcast});
$lobby->sendCommand(['LOGIN',$conf{lobbyLogin},$lobby->marshallPasswd($conf{lobbyPassword}),0,'*',"SpringLobbyMonitor v$slMonVer",0,'l t sp cl'],
{ACCEPTED => \&cbLoginAccepted,
DENIED => \&cbLoginDenied,
AGREEMENTEND => \&cbAgreementEnd},
\&cbLoginTimeout);
}
sub cbLobbyDisconnect {
slog("Disconnected from lobby server (connection reset by peer)",2);
$lobbyState=0;
$lobby->disconnect();
endMonitoring();
}
sub cbConnectTimeout {
slog("Timeout while connecting to lobby server ($conf{lobbyHost}:$conf{lobbyPort})",2);
$lobbyState=0;
}
sub cbLoginAccepted {
$lobbyState=3;
slog("Logged on lobby server",4);
}
sub cbLoginDenied {
my (undef,$reason)=@_;
slog("Login denied on lobby server ($reason)",1);
$lobbyState=0;
$lobby->disconnect();
}
sub cbAgreementEnd {
slog("Spring Lobby agreement has not been accepted for this account yet, please login with a Spring lobby client and accept the agreement",1);
$stopping=1;
$lobbyState=0;
$lobby->disconnect();
}
sub cbLoginTimeout {
slog("Unable to log on lobby server (timeout)",2);
$lobbyState=0;
$lobby->disconnect();
}
sub cbLoginInfoEnd {
$lobbyState=4;
if(exists $lobby->{users}->{$conf{lobbyLogin}} && ! $lobby->{users}->{$conf{lobbyLogin}}->{status}->{bot}) {
slog('The lobby account currently used by slMonitor is not tagged as bot. It is recommended to ask a lobby administrator for bot flag on accounts used by slMonitor',2);
}
$lobby->sendCommand(["JOIN",'SLDB']);
}
sub cbAddUser {
my (undef,$user,$country,$id,$lobbyClient)=@_;
return if($user eq 'ChanServ');
if(! defined $country) {
slog("Received an invalid ADDUSER command from server (country field not provided for user $user)",2);
$country='??';
}
if(! defined $lobbyClient) {
slog("Received an invalid ADDUSER command from server (lobbyClient field not provided for user $user)",2);
$lobbyClient='';
}
if(! defined $id || ! $id || $id !~ /^\d+$/) {
slog("Received an invalid ADDUSER command from server (accountId field not provided or invalid for user $user)",1);
return;
}
my $sth=$sldb->prepExec("select count(*) from accounts where id=$id","check if id \"$id\" is already known in accounts table");
my @accountsCount=$sth->fetchrow_array();
if($accountsCount[0] == 0) {
$sldb->do("insert into accounts values ($id,0,0,0,now())","insert new account data in accounts table for account \"$id\" and name \"$user\"");
}
seenUser($user,$id);
$lobby->sendCommand(['GETUSERID',$user]);
$lobby->sendCommand(['GETIP',$user]);
($user,$country,$lobbyClient)=$sldb->quote($user,$country,$lobbyClient);
$sldb->do("insert into names values ($id,$user,now()) on duplicate key update lastConnection=now()","insert or update names table for account \"$id\" and name \"$user\"");
$sldb->do("insert into countries values ($id,$country,now()) on duplicate key update lastConnection=now()","insert or update countries table for account \"$id\" and country \"$country\"");
$sldb->do("insert into rtPlayers values ($id,$user,0,0,$country,$lobbyClient,0,0,0,0,0)","insert data in rtPlayers on addUser ($user)",\&nonFatalError);
}
sub cbPreRemoveUser {
my (undef,$user)=@_;
if(exists $lobby->{users}->{$user}) {
my $accountId=$lobby->{users}->{$user}->{accountId};
$sldb->do("delete from rtPlayers where accountId=$accountId","update rtPlayers on removeUser ($user)",\&nonFatalError);
$sldb->do("delete from rtBattlePlayers where accountId=$accountId","update rtBattlePlayers on removeUser ($user)",\&nonFatalError);
}else{
slog("Ignoring invalid REMOVEUSER command (unknown user \"$user\")",2);
}
}
sub cbRemoveUser {
my (undef,$user)=@_;
if(exists $hosts{$user}) {
my $bId=$hosts{$user};
slog("REMOVEUSER: Removing data in memory for host \"$user\" <-> battle \"$bId\"",5);
if(exists $monitoredGames{$bId}) {
slog("REMOVEUSER: Terminating monitoring of game prematurely [$monitoredGames{$bId}->{accountId},$monitoredGames{$bId}->{startTs}]",4);
$sldb->do("update games set endTimestamp=now(),endCause=1 where hostAccountId=$monitoredGames{$bId}->{accountId} and startTimestamp=FROM_UNIXTIME($monitoredGames{$bId}->{startTs})","update games table on REMOVEUSER for game ($monitoredGames{$bId}->{accountId},$monitoredGames{$bId}->{startTs})");
delete $monitoredGames{$bId};
}
delete $unmonitoredGames{$bId};
delete $monitoredBattles{$bId};
delete $battles{$bId};
delete $hosts{$user};
$sldb->do("delete from rtBattles where battleId=$bId","update rtBattles on removeUser host ($user)",\&nonFatalError);
$sldb->do("delete from rtBattlePlayers where battleId=$bId","update rtBattlePlayers on removeUser host ($user)",\&nonFatalError);
}
}
sub cbBattleOpened {
my ($bId,$user)=($_[1],$_[4]);
slog("BATTLEOPENED: Adding data in memory for host \"$user\" <-> battle \"$bId\"",5);
$hosts{$user}=$bId;
$battles{$bId}=$user;
if($lobbyState > 3 && $lobby->{battles}->{$bId}->{type} == 0) {
if($lobby->{users}->{$user}->{status}->{inGame}) {
slog("BATTLEOPENED: New battle opened directly in-game, added to unmonitored battles (\"$user\" <-> battle \"$bId\")",3);
$unmonitoredGames{$bId}=1;
}else{
slog("BATTLEOPENED: New battle added to monitored battles",5);
$monitoredBattles{$bId}=1;
}
}
if(! exists $lobby->{users}->{$user}) {
slog("Ignoring invalid BATTLEOPENED command (unknown user \"$user\")",2);
return;
}
if(! exists $lobby->{battles}->{$bId}) {
slog("Ignoring invalid BATTLEOPENED command (unknown battle \"$bId\")",2);
return;
}
my $hostAccountId=$lobby->{users}->{$user}->{accountId};
my $p_b=$lobby->{battles}->{$bId};
my ($quotedFounder,$quotedMod,$quotedMap,$quotedDescription,$quotedEngineName,$quotedEngineVersion)=$sldb->quote($user,$p_b->{mod},$p_b->{map},$p_b->{title},$p_b->{engineName},$p_b->{engineVersion});
$sldb->do("insert into rtBattles values ($bId,$hostAccountId,$quotedFounder,INET_ATON('$p_b->{ip}'),$p_b->{port},$p_b->{type},$p_b->{natType},$p_b->{locked},$p_b->{passworded},$p_b->{rank},$quotedMod,$quotedMap,$p_b->{mapHash},$quotedDescription,$p_b->{maxPlayers},$p_b->{nbSpec},$quotedEngineName,$quotedEngineVersion)","insert new battle in rtBattles on BattleOpened ($bId,$user)",\&nonFatalError);
$sldb->do("insert into rtBattlePlayers values ($hostAccountId,$bId)","insert host in rtBattlePlayers on BattleOpened ($bId,$user)",\&nonFatalError);
}
sub cbBattleClosed {
my (undef,$bId)=@_;
if(! exists $battles{$bId}) {
slog("Ignoring invalid BATTLECLOSED command (unknown battle \"$bId\")",2);
return;
}
my $user=$battles{$bId};
slog("BATTLECLOSED: Removing data in memory for host \"$user\" <-> battle \"$bId\"",5);
if(exists $monitoredGames{$bId}) {
slog("BATTLECLOSED: Terminating monitoring of game prematurely [$monitoredGames{$bId}->{accountId},$monitoredGames{$bId}->{startTs}]",4);
$sldb->do("update games set endTimestamp=now(),endCause=1 where hostAccountId=$monitoredGames{$bId}->{accountId} and startTimestamp=FROM_UNIXTIME($monitoredGames{$bId}->{startTs})","update games table on BATTLECLOSED for game ($monitoredGames{$bId}->{accountId},$monitoredGames{$bId}->{startTs})");
delete $monitoredGames{$bId};
}
delete $unmonitoredGames{$bId};
delete $monitoredBattles{$bId};
delete $battles{$bId};
delete $hosts{$user};
$sldb->do("delete from rtBattles where battleId=$bId","delete battle from rtBattles on BattleClosed",\&nonFatalError);
$sldb->do("delete from rtBattlePlayers where battleId=$bId","delete battle from rtBattlePlayers on BattleClosed",\&nonFatalError);
}
sub cbUpdateBattleInfo {
my (undef,$bId)=@_;
if(exists $lobby->{battles}->{$bId}) {
my $p_b=$lobby->{battles}->{$bId};
my $quotedMap=$sldb->quote($p_b->{map});
$sldb->do("update rtBattles set nbSpec=$p_b->{nbSpec},locked=$p_b->{locked},mapName=$quotedMap,mapHash=$p_b->{mapHash} where battleId=$bId","updating rtBattles on UpdateBattleInfo ($bId)",\&nonFatalError);
}else{
slog("Ignoring invalid UPDATEBATTLEINFO command (unknown battle \"$bId\")",2);
}
}
sub cbPreClientStatus {
my (undef,$user,$newStatus)=@_;
my $p_newStatus=$lobby->unmarshallClientStatus($newStatus);
if(! exists $lobby->{users}->{$user}) {
slog("Ignoring invalid CLIENTSTATUS command (unknown user \"$user\")",2);
return;
}
my $p_currentStatus=$lobby->{users}->{$user}->{status};
my @sqlUpdates;
foreach my $statusKey (keys %{$p_newStatus}) {
push(@sqlUpdates,"$statusKey=$p_newStatus->{$statusKey}") if($p_newStatus->{$statusKey} != $p_currentStatus->{$statusKey});
}
if(@sqlUpdates) {
push(@sqlUpdates,"gameTimestamp=NOW()") if($p_newStatus->{inGame} != $p_currentStatus->{inGame});
push(@sqlUpdates,"awayTimestamp=NOW()") if($p_newStatus->{away} != $p_currentStatus->{away});
my $sqlUpdatesString=join(',',@sqlUpdates);
my $accountId=$lobby->{users}->{$user}->{accountId};
$sldb->do("update rtPlayers set $sqlUpdatesString where accountId=$accountId","update rtPlayers table on ClientStatus ($user)",\&nonFatalError);
}
}
sub cbClientStatus {
my (undef,$user)=@_;
if(! exists $lobby->{users}->{$user}) {
slog("Ignoring invalid CLIENTSTATUS command (unknown user \"$user\")",2);
return;
}
return if($user eq 'ChanServ');
my $p_user=$lobby->{users}->{$user};
$sldb->do("insert into accounts values ($p_user->{accountId},$p_user->{status}->{rank},$p_user->{status}->{access},$p_user->{status}->{bot},now()) on duplicate key update rank=$p_user->{status}->{rank},admin=$p_user->{status}->{access},bot=$p_user->{status}->{bot},lastUpdate=now()","insert or update accounts table for account \"$p_user->{accountId}\" name \"$user\"");
if(exists $hosts{$user}) {
my $bId=$hosts{$user};
if($lobby->{battles}->{$bId}->{type} == 0) {
if($lobbyState < 4) {
if($lobby->{users}->{$user}->{status}->{inGame}) {
slog("CLIENTSTATUS: Lobby connection init, host in game => adding game to unmonitored games (\"$user\" <-> battle \"$bId\")",5);
$unmonitoredGames{$bId}=1;
}else{
slog("CLIENTSTATUS: Lobby connection init, host not in game => adding battle to monitored battles (\"$user\" <-> battle \"$bId\")",5);
$monitoredBattles{$bId}=1;
}
}else{
if($lobby->{users}->{$user}->{status}->{inGame}) {
if(exists $monitoredBattles{$bId}) {
delete $monitoredBattles{$bId};
my @userList=@{$lobby->{battles}->{$bId}->{userList}};
my $nbUsers=$#userList+1;
my $nbSpecs=$lobby->{battles}->{$bId}->{nbSpec};
if($nbSpecs > $nbUsers) {
slog("Got a spec count superior to total number of players for battle hosted by \"$user\"",2);
$nbSpecs=$nbUsers;
}
my $nbPlayers=$nbUsers-$nbSpecs;
if($nbPlayers > 0) {
my $timestamp=time;
$monitoredGames{$bId}={accountId => $lobby->{users}->{$user}->{accountId},
startTs => $timestamp};
slog("CLIENTSTATUS: A monitored battle went in game, storing game data in database (\"$user\" <-> battle \"$bId\") [$lobby->{users}->{$user}->{accountId},$timestamp]",5);
my $battleTitle=$lobby->{battles}->{$bId}->{title};
$battleTitle=$1 if($battleTitle =~ /^Incompatible \(spring [^\)]*\) *(.*)$/);
my ($quotedUser,$quotedMod,$quotedMap,$quotedEngineName,$quotedEngineVersion);
($battleTitle,$quotedUser,$quotedMod,$quotedMap,$quotedEngineName,$quotedEngineVersion)=$sldb->quote($battleTitle,$user,$lobby->{battles}->{$bId}->{mod},$lobby->{battles}->{$bId}->{map},$lobby->{battles}{$bId}{engineName},$lobby->{battles}{$bId}{engineVersion});
$sldb->do("insert into games values ($monitoredGames{$bId}->{accountId},FROM_UNIXTIME($timestamp),0,0,$quotedUser,$quotedMod,$quotedMap,$nbSpecs,$nbPlayers,$battleTitle,$lobby->{battles}->{$bId}->{passworded},$quotedEngineName,$quotedEngineVersion,NULL)",
"insert into games table for game ($monitoredGames{$bId}->{accountId},$timestamp)");
foreach my $player (@userList) {
my $quotedPlayer=$sldb->quote($player);
$sldb->do("insert into players values ($monitoredGames{$bId}->{accountId},FROM_UNIXTIME($timestamp),$lobby->{users}->{$player}->{accountId},$quotedPlayer)","insert into players table for player ($monitoredGames{$bId}->{accountId},FROM_UNIXTIME($timestamp),$lobby->{users}->{$player}->{accountId})");
}
}else{
slog("CLIENTSTATUS: A monitored battle went in game with no player, adding game to unmonitored games (\"$user\" <-> battle \"$bId\")",5);
$unmonitoredGames{$bId}=1;
}
}
}else{
if(exists $unmonitoredGames{$bId}) {
slog("CLIENTSTATUS: An unmonitored game finished, adding battle to monitored battles (\"$user\" <-> battle \"$bId\")",5);
delete $unmonitoredGames{$bId};
$monitoredBattles{$bId}=1;
}elsif(exists $monitoredGames{$bId}) {
if(time - $monitoredGames{$bId}->{startTs} < $conf{minGameLength}) {
slog("CLIENTSTATUS: Discarding game [$monitoredGames{$bId}->{accountId},$monitoredGames{$bId}->{startTs}] (game too short), adding battle to monitored battles (\"$user\" <-> battle \"$bId\")",5);
$sldb->do("delete from games where hostAccountId=$monitoredGames{$bId}->{accountId} and startTimestamp=FROM_UNIXTIME($monitoredGames{$bId}->{startTs})","delete from games table on CLIENTSTATUS for game ($monitoredGames{$bId}->{accountId},$monitoredGames{$bId}->{startTs})");
$sldb->do("delete from players where hostAccountId=$monitoredGames{$bId}->{accountId} and startTimestamp=FROM_UNIXTIME($monitoredGames{$bId}->{startTs})","delete from players table on CLIENTSTATUS for game ($monitoredGames{$bId}->{accountId},$monitoredGames{$bId}->{startTs})");
}else{
slog("CLIENTSTATUS: A monitored game finished [$monitoredGames{$bId}->{accountId},$monitoredGames{$bId}->{startTs}], adding battle to monitored battles (\"$user\" <-> battle \"$bId\")",5);
$sldb->do("update games set endTimestamp=now() where hostAccountId=$monitoredGames{$bId}->{accountId} and startTimestamp=FROM_UNIXTIME($monitoredGames{$bId}->{startTs})","update games table on CLIENTSTATUS for game ($monitoredGames{$bId}->{accountId},$monitoredGames{$bId}->{startTs})");
}
delete $monitoredGames{$bId};
$monitoredBattles{$bId}=1;
}
}
}
}
}
}
sub cbJoinedBattle {
my (undef,$bId,$user)=@_;
if(! exists $lobby->{users}->{$user}) {
slog("Ignoring invalid JOINEDBATTLE command (unknown user \"$user\")",2);
return;
}
if(! exists $lobby->{battles}->{$bId}) {
slog("Ignoring invalid JOINEDBATTLE command (unknown battle \"$bId\")",2);
return;
}
my $accountId=$lobby->{users}->{$user}->{accountId};
$sldb->do("insert into rtBattlePlayers values ($accountId,$bId)","insert data into rtBattlePlayers on JoinedBattle ($bId,$user)",\&nonFatalError);
}
sub cbLeftBattle {
my (undef,undef,$user)=@_;
if(! exists $lobby->{users}->{$user}) {
slog("Ignoring invalid LEFTBATTLE command (unknown user \"$user\")",2);
return;
}
my $accountId=$lobby->{users}->{$user}->{accountId};
$sldb->do("delete from rtBattlePlayers where accountId=$accountId","delete data from rtBattlePlayers on LeftBattle ($user)",\&nonFatalError);
}
sub cbSaidPrivate {
my (undef,$user,$msg)=@_;
logMsg("pv_$user","<$user> $msg");
if($msg =~ /^!([\w\#]+)\s*(.*)$/) {
my ($command,$params)=($1,$2);
if(exists $GDRs{$user}) {
if($command ne '#endGDR') {
$GDRs{$user}->{data}.=$msg;
}else{
handleCommand($user,$command,$params);
}
}else{
handleCommand($user,$command,$params);
}
}elsif(exists $GDRs{$user}) {
$GDRs{$user}->{data}.=$msg;
}
}
sub cbServerMsg {
my (undef,$msg)=@_;
slog("SERVER MESSAGE: $msg",5);
if($msg =~ /^The ID for <([^>]+)> is (.+)$/) {
my ($user,$idsString)=($1,$2);
my @ids=split(/ /,$idsString);
if($ids[0] !~ /^\d+$/) {
slog("Ignoring invalid hardwareId \"$ids[0]\" received for user \"$user\"",2);
$ids[0]=undef;
}
if(defined $ids[1] && $ids[1] !~ /^[0-9a-f]{1,16}$/) {
slog("Ignoring invalid systemId \"$ids[1]\" received for user \"$user\"",2);
$ids[1]=undef;
}
if(exists $lobby->{users}->{$user}) {
my $userId=$lobby->{users}{$user}{accountId};
seenHardwareId($userId,$ids[0]) if(defined $ids[0]);
seenSystemId($userId,$ids[1]) if(defined $ids[1]);
}else{
slog("Ignoring ids received for offline user \"$user\"",4);
}
}elsif($msg =~ /^<([^>]+)> is currently bound to (\d+\.\d+\.\d+\.\d+)/) {
seenLobbyIp($1,$2);
}
}
sub cbBroadcast {
my (undef,$msg)=@_;
print "Lobby broadcast message: $msg\n";
slog("Lobby broadcast message: $msg",3);
}
sub splitMsg {
my ($longMsg,$maxSize)=@_;
my @messages=($longMsg =~ /.{1,$maxSize}/gs);
return \@messages;
}
sub sayPrivate {
my ($user,$msg)=@_;
my $p_messages=splitMsg($msg,$conf{maxChatMessageLength}-1);
foreach my $mes (@{$p_messages}) {
$lobby->sendCommand(['SAYPRIVATE',$user,$mes]);
logMsg("pv_$user","<$conf{lobbyLogin}> $mes");
}
}
sub getFirstRangeAddr {
my $ip=shift;
$ip-=$ip%256;
return $ip;
}
sub getLastRangeAddr {
my $ip=shift;
$ip=$ip-($ip%256)+255;
return $ip;
}
sub seenUser {
my ($user,$id)=@_;
my $sth=$sldb->prepExec("select count(*) from userAccounts where accountId=$id","check if id \"$id\" is already known in userAccounts!");
my @uaCount=$sth->fetchrow_array();
return if($uaCount[0] > 0);
my ($name,$clan)=('','');
if($user=~/^\[([^\]]+)\](.+)$/) {
($clan,$name)=($1,$2);
}else{
$name=$user;
}
$clan=$sldb->quote($clan);
my $quotedName=$sldb->quote($sldb->findAvailableUserName($name));
$sldb->do("insert into userAccounts values ($id,$id,0,0)","insert data in table userAccounts");
$sldb->do("insert into userDetails values ($id,$quotedName,$clan,NULL,NULL,0)","insert data in table userDetails");
}
sub initializeUserTablesIfNeeded {
my $sth=$sldb->prepExec("select count(*) from userAccounts","check userAccounts state in database!");
my @uaCount=$sth->fetchrow_array();
return if($uaCount[0] > 0);
slog("Initializing \"userAccounts\" and \"userDetails\" tables from \"names\" table",3);
$sth=$sldb->prepExec("select accountId,name from names group by accountId","read \"names\" table for user tables initialization!");
my ($id,$name);
while(($id,$name)=$sth->fetchrow_array()) {
seenUser($name,$id);
}
slog("User tables initialization done.",3);
}
sub seenHardwareId {
my ($accountId,$hardwareId)=@_;
$sldb->do("insert into hardwareIds values ($accountId,$hardwareId,now()) on duplicate key update lastConnection=now()","insert or update hardwareIds table for account \"$accountId\" and hardwareId \"$hardwareId\"");
return unless($hardwareId);
return unless($lobby->{users}->{$lobby->{accounts}->{$accountId}}->{status}->{rank} == 0);
my $smurfId=$sldb->getUserId($accountId);
return unless($smurfId == $accountId);
my $sth=$sldb->prepExec("select distinct ua.userId from userAccounts ua,hardwareIds hw where ua.userId != $smurfId and ua.accountId=hw.accountId and hw.hardwareId=$hardwareId limit 2","retrieve users with accounts matching hardwareId \"$hardwareId\" from userAccounts and hardwareIds");
my $p_results=$sth->fetchall_arrayref();
return unless(@{$p_results});
if($#{$p_results} > 0) {
slog("HardwareId of newbie account \"$lobby->{accounts}->{$accountId}\" matches multiple users, cancelling auto-merge",4);
return;
}
my $userId=$p_results->[0]->[0];
my $mergeStatus=checkUserMerge($userId,$smurfId,1);
return unless($mergeStatus);
slog("Detected smurf for user \#$userId: \#$smurfId ($lobby->{accounts}->{$accountId}), merging users...",3);
$sldb->adminEvent('JOIN_ACC',$mergeStatus,0,0,{mainUserId => $userId, childUserId => $smurfId});
$sth=$sldb->prepExec("select accountId from userAccounts where userId=$smurfId","retrieve smurfs list of user $smurfId that will be joined with user $userId");
my $p_oldUserSmurfs=$sth->fetchall_arrayref();
foreach my $p_accountId (@{$p_oldUserSmurfs}) {
$sldb->queueGlobalRerate($p_accountId->[0]);
}
$sldb->do("update userAccounts set userId=$userId where userId=$smurfId","update data in table userAccounts for new smurf found \"$smurfId\" of \"$userId\"");
$sldb->computeAllUserIps($userId,$conf{dynIpThreshold},$conf{dynIpRange});
}
sub seenSystemId {
my ($accountId,$systemId)=@_;
$sldb->do("insert into systemIds values ($accountId,conv('$systemId',16,10),now()) on duplicate key update lastConnection=now()","insert or update systemIds table for account \"$accountId\" and systemId \"$systemId\"");
}
sub seenLobbyIp {
my ($user,$ip)=@_;
return unless(exists $lobby->{users}->{$user});
my $id=$lobby->{users}->{$user}->{accountId};
my $ipNb;
if($ip =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/) {
$ipNb=$sldb->ipToInt($ip);
if(! $ipNb) {
slog("Unable to convert ip to number in seenLobbyIp ($ip)!",2);
return 0;
}
}elsif($ip =~ /^\d+$/) {
$ipNb=$ip;
}else{
slog("Invalid ip in seenLobbyIp ($ip)!",2);
return 0;
}
my $sth=$sldb->prepExec("select bot,noSmurf from accounts,userAccounts where id=$id and accountId=$id","check bot and noSmurf flags for account \"$id\" in tables accounts and userAccounts!");
my @foundData=$sth->fetchrow_array();
if($foundData[0] || $foundData[1]) {
slog("Skipping smurf detection from lobby IP for account \"$id\" (bot=$foundData[0], noSmurf=$foundData[1])",5);
return 1;
}
$sth=$sldb->prepExec("select userId from userAccounts where accountId=$id","query userAccounts for user id of account \"$id\"!");
@foundData=$sth->fetchrow_array();
error("Unable to find user id of account \"$id\" in userAccounts table!") unless(@foundData);
my $userId=$foundData[0];
$sth=$sldb->prepExec("select rank from accounts where id=$userId","retrieve rank of account \"$userId\"");
@foundData=$sth->fetchrow_array();
error("Unable to find rank of user \"$userId\" in accounts table!") unless(@foundData);
my $userRank=$foundData[0];
# Smurf detection (search of static IPs matching one IP)
$sth=$sldb->prepExec("select userId,max(rank) maxRank from accounts,userAccounts,ips where id=userAccounts.accountId and id=ips.accountId and bot=0 and noSmurf=0 and userId != $userId and ip=$ipNb group by userId order by maxRank desc","search smurfs for ip $ipNb of user \"$userId\" in ips table");
my $p_newSmurfData=$sth->fetchall_arrayref();
foreach my $p_possibleSmurfUser (@{$p_newSmurfData}) {
my ($smurfId,$smurfRank)=($p_possibleSmurfUser->[0],$p_possibleSmurfUser->[1]);
my $mergeStatus=checkUserMerge($userId,$smurfId,1);
next unless($mergeStatus);
my ($oldUserId,$newUserId);
if($smurfRank < $userRank || ($smurfRank == $userRank && $userId < $smurfId)) {
($oldUserId,$newUserId)=($smurfId,$userId);
}else{
($oldUserId,$newUserId)=($userId,$smurfId);
($userId,$userRank)=($smurfId,$smurfRank);
}
slog("Merging $oldUserId into $newUserId based on lobby IP!",3);
$sldb->adminEvent('JOIN_ACC',$mergeStatus,0,0,{mainUserId => $newUserId, childUserId => $oldUserId});
$sth=$sldb->prepExec("select accountId from userAccounts where userId=$oldUserId","retrieve smurfs list of user $oldUserId that will be joined with user $newUserId");
my $p_oldUserSmurfs=$sth->fetchall_arrayref();
foreach my $p_accountId (@{$p_oldUserSmurfs}) {
$sldb->queueGlobalRerate($p_accountId->[0]);
}
$sldb->do("update userAccounts set userId=$newUserId where userId=$oldUserId","update data in table userAccounts for new smurf found \"$oldUserId\" of \"$newUserId\"");
$sldb->computeAllUserIps($newUserId,$conf{dynIpThreshold},$conf{dynIpRange});
}
}
sub seenIp {
my ($id,$ip,$date)=@_;
if(defined $date) {
$date="FROM_UNIXTIME($date)";
}else{
$date='now()';
}
my $ipNb;
if($ip =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/) {
$ipNb=$sldb->ipToInt($ip);
if(! $ipNb) {
slog("Unable to convert ip to number ($ip)!",2);
return 0;
}
}elsif($ip =~ /^\d+$/) {
$ipNb=$ip;
}
return 0 if($sldb->isReservedIpNb($ipNb));
my $sth=$sldb->prepExec("select ua.userId,ua.nbIps,ud.nbIps from userAccounts ua,userDetails ud where ua.accountId=$id and ua.userId=ud.userId","query id \"$id\" in userAccounts and userDetails");
my @foundData=$sth->fetchrow_array();
if(! @foundData) {
slog("Unable to retrieve data for id \"$id\" in userAccounts and userDetails, ignoring ip \"$ip\"!",2);
return 0;
}
my ($userId,$nbIps,$nbUserIps)=@foundData;
my @ipCount;
if($date eq 'now()') {
$sth=$sldb->prepExec("select count(*) from userIps where userId=$userId and ip=$ipNb","check if ip \"$ip\" for userId \"$userId\" is already known in userIps table");
@ipCount=$sth->fetchrow_array();
if($ipCount[0] > 0) {
$sldb->do("update userIps set lastSeen=$date where userId=$userId and ip=$ipNb","update ip last seen date in table userIps");
}else{
if($nbUserIps < $conf{dynIpThreshold}) {
$sldb->do("insert into userIps values ($userId,$ipNb,$date)","insert new ip \"$ip\" for userId \"$userId\" in table userIps");
$sldb->do("update userDetails set nbIps=nbIps+1 where userId=$userId","increment nbIps for userId \"$userId\" in table userDetails");
}
if($nbUserIps == $conf{dynIpThreshold}-1) {
slog("User \#$userId has been detected as using dynamic IP, starting dynamic IP ranges detection...",3);
$sldb->computeAllUserIps($userId,$conf{dynIpThreshold},$conf{dynIpRange});
}elsif($nbUserIps > $conf{dynIpThreshold}-1) {
$sth=$sldb->prepExec("select count(*) from userIpRanges where userId=$userId and ip1 <= $ipNb and $ipNb <= ip2","check if ip \"$ip\" for userId \"$userId\" is already known in userIpRanges table");
@ipCount=$sth->fetchrow_array();
if($ipCount[0] > 0) {
$sldb->do("update userIpRanges set lastSeen=$date where userId=$userId and ip1 <= $ipNb and $ipNb <= ip2","update ip last seen date in table userIpRanges");
}else{
$sth=$sldb->prepExec("select ip from userIps where userId=$userId and ABS(cast(ip as signed) - $ipNb) <= $conf{dynIpRange}","query userIps table for neighbour ips of \"$ip\" for userId \"$userId\"");
my @neighbourIps;
while(@foundData=$sth->fetchrow_array()) {
push(@neighbourIps,$foundData[0]);
}
my @sortedIps=sort {$a <=> $b} (@neighbourIps,$ipNb);
my ($rangeStart,$rangeEnd)=($sortedIps[0],$sortedIps[$#sortedIps]);
if($rangeStart<$rangeEnd) {
$rangeStart=getFirstRangeAddr($rangeStart);
$rangeEnd=getLastRangeAddr($rangeEnd);
}
$sth=$sldb->prepExec("select ip1,ip2 from userIpRanges where userId=$userId and (($rangeStart >= ip1 and $rangeStart <= ip2+$conf{dynIpRange}) or ($rangeEnd >= ip1-$conf{dynIpRange} and $rangeEnd <= ip2) or ($rangeStart < ip1 and $rangeEnd > ip2))","query userIpRanges table for neighbour ranges of userId \"$userId\"");
my @neighbourRanges;
while(@foundData=$sth->fetchrow_array()) {
push(@neighbourRanges,$foundData[0]);
$rangeStart=$foundData[0] if($foundData[0]<$rangeStart);
$rangeEnd=$foundData[1] if($foundData[1]>$rangeEnd);
}
if(@neighbourIps) {
my $neighbourIpsString=join(',',@neighbourIps);
$sldb->do("delete from userIps where userId=$userId and ip in ($neighbourIpsString)","remove aggregated ip addresses for userId \"$userId\" in table userIps during dynamic ip ranges detection");
}
if(@neighbourRanges) {
my $neighbourRangesString=join(',',@neighbourRanges);
$sldb->do("delete from userIpRanges where userId=$userId and ip1 in ($neighbourRangesString)","remove aggregated ip ranges for userId \"$userId\" in table userIpRanges during dynamic ip ranges detection");
}
if($rangeStart<$rangeEnd) {
$rangeStart=getFirstRangeAddr($rangeStart);
$rangeEnd=getLastRangeAddr($rangeEnd);
$sldb->do("insert into userIpRanges values ($userId,$rangeStart,$rangeEnd,$date)","insert aggregated range for userId \"$userId\" in table userIpRanges during dynamic ip ranges detection");
}else{
$sldb->do("insert into userIps values ($userId,$ipNb,$date)","insert new ip \"$ip\" for userId \"$userId\" in table userIps");
}
}
}
}
}
$sth=$sldb->prepExec("select count(*) from ips where accountId=$id and ip=$ipNb","check if ip \"$ip\" for id \"$id\" is already known in ips table!");
@ipCount=$sth->fetchrow_array();
if($ipCount[0] > 0) {
$sldb->do("update ips set lastSeen=$date where accountId=$id and ip=$ipNb","update ip last seen date in table ips");
return 1;
}
if($nbIps < $conf{dynIpThreshold}-1) {
$sldb->do("insert into ips values ($id,$ipNb,$date)","insert new ip \"$ip\" for id \"$id\" in table ips");
$sldb->do("update userAccounts set nbIps=nbIps+1 where accountId=$id","increment nbIps for account \"$id\" in table userAccounts");
checkSmurf($id,$ipNb);
}else{
if($nbIps == $conf{dynIpThreshold}-1) {
slog("Account \#$id has been detected as using dynamic IP, starting dynamic IP ranges detection...",3);
$sth=$sldb->prepExec("select ip,UNIX_TIMESTAMP(lastSeen) from ips where accountId=$id","retrieve known ips for id \"$id\" in ips table for dynamic ip ranges detection!");
my (@knownIp,%knownIps);
while(@knownIp=$sth->fetchrow_array()) {
$knownIps{$knownIp[0]}=$knownIp[1];
}
my (@isolatedIps,@ranges);
my ($rangeStart,$rangeEnd,$rangeTs)=(0,0,0);
foreach my $testedIp (sort {$a <=> $b} keys %knownIps) {
if($rangeEnd) {
if(getFirstRangeAddr($testedIp)-$rangeEnd <= $conf{dynIpRange}) {
$rangeEnd=getLastRangeAddr($testedIp);
$rangeTs=$knownIps{$testedIp} if($knownIps{$testedIp} > $rangeTs);
}else{
push(@ranges,[$rangeStart,$rangeEnd,$rangeTs]);
($rangeStart,$rangeEnd,$rangeTs)=($testedIp,0,$knownIps{$testedIp});
}
}elsif($rangeStart) {
if(getFirstRangeAddr($testedIp)-$rangeStart <= $conf{dynIpRange}) {
$rangeStart=getFirstRangeAddr($rangeStart);
$rangeEnd=getLastRangeAddr($testedIp);
$rangeTs=$knownIps{$testedIp} if($knownIps{$testedIp} > $rangeTs);
}else{
push(@isolatedIps,$rangeStart);
($rangeStart,$rangeTs)=($testedIp,$knownIps{$testedIp});
}
}else{
($rangeStart,$rangeTs)=($testedIp,$knownIps{$testedIp});
}
}
if($rangeEnd) {
push(@ranges,[$rangeStart,$rangeEnd,$rangeTs]);
}elsif($rangeStart) {
push(@isolatedIps,$rangeStart);
}else{
error("Inconsistent state while processing dynamic ip ranges detection");
}
$sldb->do("delete from ips where accountId=$id","flush ip addresses for account \"$id\" in table ips for dynamic ip ranges detection");
foreach my $isolatedIp (@isolatedIps) {
$sldb->do("insert into ips values ($id,$isolatedIp,FROM_UNIXTIME($knownIps{$isolatedIp}))","reinsert ip addresses for account \"$id\" in table ips for dynamic ip ranges detection");
}
foreach my $p_range (@ranges) {
$sldb->do("insert into ipRanges values ($id,$p_range->[0],$p_range->[1],FROM_UNIXTIME($p_range->[2]))","insert ip ranges for account \"$id\" in table ipRanges for dynamic ip ranges detection");
}
my $nbRangesFound=$#ranges+1;
if($nbRangesFound) {
slog($nbRangesFound." dynamic IP range(s) found.",4);
}else{
slog("No dynamic IP range found.",4);
}
$sldb->do("update userAccounts set nbIps=$conf{dynIpThreshold} where accountId=$id","set nbIps to $conf{dynIpThreshold} for account \"$id\" in table userAccounts");
}
$sth=$sldb->prepExec("select count(*) from ipRanges where accountId=$id and $ipNb >= ip1 and $ipNb <= ip2","check if ip \"$ip\" for id \"$id\" is already known in ipRanges table!");
@ipCount=$sth->fetchrow_array();
if($ipCount[0] > 0) {
$sldb->do("update ipRanges set lastSeen=$date where accountId=$id and $ipNb >= ip1 and $ipNb <= ip2","update ip last seen date in table ips");
return 1;
}
$sth=$sldb->prepExec("select ip from ips where accountId=$id and ABS(cast(ip as signed) - $ipNb) <= $conf{dynIpRange}","query ips table for neighbour ips of \"$ip\" for id \"$id\"!");
my @neighbourIps;
while(@foundData=$sth->fetchrow_array()) {
push(@neighbourIps,$foundData[0]);
}
my @sortedIps=sort {$a <=> $b} (@neighbourIps,$ipNb);
my ($rangeStart,$rangeEnd)=($sortedIps[0],$sortedIps[$#sortedIps]);
if($rangeStart<$rangeEnd) {
$rangeStart=getFirstRangeAddr($rangeStart);
$rangeEnd=getLastRangeAddr($rangeEnd);
}
$sth=$sldb->prepExec("select ip1,ip2 from ipRanges where accountId=$id and (($rangeStart >= ip1 and $rangeStart <= ip2+$conf{dynIpRange}) or ($rangeEnd >= ip1-$conf{dynIpRange} and $rangeEnd <= ip2) or ($rangeStart < ip1 and $rangeEnd > ip2))","query ipRanges table for neighbour ranges of id \"$id\"!");
my @neighbourRanges;
while(@foundData=$sth->fetchrow_array()) {
push(@neighbourRanges,$foundData[0]);
$rangeStart=$foundData[0] if($foundData[0]<$rangeStart);
$rangeEnd=$foundData[1] if($foundData[1]>$rangeEnd);
}
if(@neighbourIps) {
my $neighbourIpsString=join(',',@neighbourIps);
$sldb->do("delete from ips where accountId=$id and ip in ($neighbourIpsString)","remove aggregated ip addresses for account \"$id\" in table ips during dynamic ip ranges detection");
}
if(@neighbourRanges) {
my $neighbourRangesString=join(',',@neighbourRanges);
$sldb->do("delete from ipRanges where accountId=$id and ip1 in ($neighbourRangesString)","remove aggregated ip ranges for account \"$id\" in table ipRanges during dynamic ip ranges detection");
}
if($rangeStart<$rangeEnd) {
$rangeStart=getFirstRangeAddr($rangeStart);
$rangeEnd=getLastRangeAddr($rangeEnd);
$sldb->do("insert into ipRanges values ($id,$rangeStart,$rangeEnd,$date)","insert aggregated range for account \"$id\" in table ipRanges during dynamic ip ranges detection");
checkSmurf($id,$rangeStart,$rangeEnd);
}else{
$sldb->do("insert into ips values ($id,$ipNb,$date)","insert new ip \"$ip\" for id \"$id\" in table ips");
checkSmurf($id,$ipNb);
}
}
}
sub checkSmurf {
my ($id,$ipNbParam,$ipNbParam2)=@_;
my $paramsString=join(',',@_);
my $functionStartTime=time;
my $sth=$sldb->prepExec("select bot,noSmurf from accounts,userAccounts where id=$id and accountId=$id","check bot and noSmurf flags for account \"$id\" in tables accounts and userAccounts!");
my @foundData=$sth->fetchrow_array();
if($foundData[0] || $foundData[1]) {
slog("Skipping smurf detection for account \"$id\" (bot=$foundData[0], noSmurf=$foundData[1])",4);
return 1;
}
$sth=$sldb->prepExec("select userId from userAccounts where accountId=$id","query userAccounts for user id of account \"$id\"!");
@foundData=$sth->fetchrow_array();
error("Unable to find user id of account \"$id\" in userAccounts table!") unless(@foundData);
my $userId=$foundData[0];
$sth=$sldb->prepExec("select rank from accounts where id=$userId","retrieve rank of account \"$userId\"");
@foundData=$sth->fetchrow_array();
error("Unable to find rank of user \"$userId\" in accounts table!") unless(@foundData);
my $userRank=$foundData[0];
my @ipDataToCheck;
if(defined $ipNbParam) {
if(defined $ipNbParam2) {
@ipDataToCheck=([$ipNbParam,$ipNbParam2]);
}else{
@ipDataToCheck=([$ipNbParam]);
}
}else{
$sth=$sldb->prepExec("select distinct(ip) from ips where accountId in (select accountId from userAccounts where userId=$userId)","retrieve all known ips for user $userId");
while(@foundData=$sth->fetchrow_array()) {
push(@ipDataToCheck,[$foundData[0]]);
}
$sth=$sldb->prepExec("select ip1,ip2 from ipRanges where accountId in (select accountId from userAccounts where userId=$userId) group by concat(ip1,ip2)","retrieve all known ip ranges for user $userId");
while(@foundData=$sth->fetchrow_array()) {
push(@ipDataToCheck,[$foundData[0],$foundData[1]]);
}
}
foreach my $p_ipData (@ipDataToCheck) {
my ($ipNb,$ipNb2)=@{$p_ipData};
if(! defined $ipNb2) {
# Smurf detection (search of static IPs matching one IP)
$sth=$sldb->prepExec("select userId,max(rank) maxRank from accounts,userAccounts,ips where id=userAccounts.accountId and id=ips.accountId and bot=0 and noSmurf=0 and userId != $userId and ip=$ipNb group by userId order by maxRank desc","search smurfs for ip $ipNb of user \"$userId\" in ips table");
my $p_newSmurfData=$sth->fetchall_arrayref();
foreach my $p_possibleSmurfUser (@{$p_newSmurfData}) {
my ($smurfId,$smurfRank)=($p_possibleSmurfUser->[0],$p_possibleSmurfUser->[1]);
my $mergeStatus=checkUserMerge($userId,$smurfId,1);
next unless($mergeStatus);
my ($oldUserId,$newUserId);
if($smurfRank < $userRank || ($smurfRank == $userRank && $userId < $smurfId)) {
($oldUserId,$newUserId)=($smurfId,$userId);
}else{
($oldUserId,$newUserId)=($userId,$smurfId);
($userId,$userRank)=($smurfId,$smurfRank);
}
$sldb->adminEvent('JOIN_ACC',$mergeStatus,0,0,{mainUserId => $newUserId, childUserId => $oldUserId});
$sth=$sldb->prepExec("select accountId from userAccounts where userId=$oldUserId","retrieve smurfs list of user $oldUserId that will be joined with user $newUserId");
my $p_oldUserSmurfs=$sth->fetchall_arrayref();
foreach my $p_accountId (@{$p_oldUserSmurfs}) {
$sldb->queueGlobalRerate($p_accountId->[0]);
}
$sldb->do("update userAccounts set userId=$newUserId where userId=$oldUserId","update data in table userAccounts for new smurf found \"$oldUserId\" of \"$newUserId\"");
$sldb->computeAllUserIps($newUserId,$conf{dynIpThreshold},$conf{dynIpRange});
}
# Probable smurf detection (search of dynamic IP ranges matching one IP)
$sth=$sldb->prepExec("select id,userId from accounts,userAccounts,ipRanges where id=userAccounts.accountId and id=ipRanges.accountId and bot=0 and noSmurf=0 and userId != $userId and ip1 <= $ipNb and ip2 >= $ipNb group by concat(id,userId)","search probable smurfs for ip $ipNb of account $id in ipRanges table");
my $p_newProbableSmurfsData=$sth->fetchall_arrayref();
my %newProbableSmurfs;
foreach my $p_probableSmurfUser (@{$p_newProbableSmurfsData}) {
my ($probSmurfAccId,$probSmurfUserId)=($p_probableSmurfUser->[0],$p_probableSmurfUser->[1]);
next unless(checkUserMerge($userId,$probSmurfUserId) == 1);
if(exists $newProbableSmurfs{$probSmurfUserId}) {
$newProbableSmurfs{$probSmurfUserId}->{$probSmurfAccId}=1;
}else{
$newProbableSmurfs{$probSmurfUserId}={$probSmurfAccId => 1};
}
}
foreach my $probSmurfUserId (keys %newProbableSmurfs) {
my $bestId=$probSmurfUserId;
if(! exists $newProbableSmurfs{$probSmurfUserId}->{$probSmurfUserId}) {
my @probSmurfUserIds=sort {$a <=> $b} (keys %{$newProbableSmurfs{$probSmurfUserId}});
$bestId=$probSmurfUserIds[0];
}
my ($id1,$id2)= $bestId < $id ? ($bestId,$id) : ($id,$bestId);
$sldb->adminEvent('ADD_PROB_SMURF',0,0,0,{accountId1 => $id1, accountId2 => $id2});
$sldb->do("insert into smurfs values ($id1,$id2,2,0)","add probable smurf \"$id1\" <-> \"$id2\" into smurfs table");
}
}else{
# Probable smurf detection (search of static IPs matching a dynamic IP range)