-
Notifications
You must be signed in to change notification settings - Fork 15
/
gameplayer.cpp
873 lines (700 loc) · 30.1 KB
/
gameplayer.cpp
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
/*
ent-ghost
Copyright [2011-2013] [Jack Lu]
This file is part of the ent-ghost source code.
ent-ghost 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.
ent-ghost source code 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 ent-ghost source code. If not, see <http://www.gnu.org/licenses/>.
ent-ghost is modified from GHost++ (http://ghostplusplus.googlecode.com/)
GHost++ is Copyright [2008] [Trevor Hogan]
*/
#include "ghost.h"
#include "util.h"
#include "language.h"
#include "socket.h"
#include "commandpacket.h"
#include "bnet.h"
#include "map.h"
#include "gameplayer.h"
#include "gameprotocol.h"
#include "gcbiprotocol.h"
#include "gpsprotocol.h"
#include "ghostdb.h"
#include "game_base.h"
//
// CPotentialPlayer
//
CPotentialPlayer :: CPotentialPlayer( CGameProtocol *nProtocol, CBaseGame *nGame, CTCPSocket *nSocket ) : m_Protocol( nProtocol ), m_Game( nGame ), m_Socket( nSocket ), m_DeleteMe( false ), m_Error( false ), m_IncomingJoinPlayer( NULL ), m_IncomingGarenaUser( NULL ), m_ConnectionState( 0 ), m_ConnectionTime( GetTicks( ) ), m_Banned( false ), m_CallableBanCheck( NULL )
{
if( nSocket )
m_CachedIP = nSocket->GetIPString( );
else
m_CachedIP = string( );
}
CPotentialPlayer :: ~CPotentialPlayer( )
{
if( m_Socket )
delete m_Socket;
while( !m_Packets.empty( ) )
{
delete m_Packets.front( );
m_Packets.pop( );
}
delete m_IncomingJoinPlayer;
delete m_IncomingGarenaUser;
boost::mutex::scoped_lock lock( m_Game->m_GHost->m_CallablesMutex );
if( m_CallableBanCheck )
m_Game->m_GHost->m_Callables.push_back( m_CallableBanCheck );
lock.unlock( );
}
BYTEARRAY CPotentialPlayer :: GetGarenaIP( )
{
if( m_IncomingGarenaUser == NULL ) {
return UTIL_CreateByteArray( (uint32_t) 0, true );
} else {
return UTIL_CreateByteArray( m_IncomingGarenaUser->GetIP( ), true );
}
}
BYTEARRAY CPotentialPlayer :: GetExternalIP( )
{
unsigned char Zeros[] = { 0, 0, 0, 0 };
if( m_Socket ) {
if( m_IncomingGarenaUser != NULL )
return GetGarenaIP( );
else
return m_Socket->GetIP( );
}
return UTIL_CreateByteArray( Zeros, 4 );
}
string CPotentialPlayer :: GetExternalIPString( )
{
if( m_Socket ) {
if( m_IncomingGarenaUser != NULL ) {
BYTEARRAY GarenaIP = GetGarenaIP( );
return UTIL_ToString(GarenaIP[0]) + "." + UTIL_ToString(GarenaIP[1]) + "." + UTIL_ToString(GarenaIP[2]) + "." + UTIL_ToString(GarenaIP[3]);
} else {
string IPString = m_Socket->GetIPString( );
if( !IPString.empty( ) && IPString != "0.0.0.0" )
return m_Socket->GetIPString( );
else
return m_CachedIP;
}
}
return m_CachedIP;
}
bool CPotentialPlayer :: Update( void *fd )
{
if( m_DeleteMe )
return true;
if( !m_Socket )
return false;
m_Socket->DoRecv( (fd_set *)fd );
ExtractPackets( );
ProcessPackets( );
// make sure we don't keep this socket open forever (disconnect after five seconds)
if( m_ConnectionState == 0 && GetTicks( ) - m_ConnectionTime > 5000 && !m_Banned )
{
CONSOLE_Print( "[DENY] Kicking player: REQJOIN not received within five seconds" );
m_DeleteMe = true;
m_Game->m_GHost->DenyIP( GetExternalIPString( ), 60000, "REQJOIN not received within five seconds" );
}
else if( m_ConnectionState == 0 && GetTicks( ) - m_ConnectionTime > 30000 )
{
m_DeleteMe = true;
m_Game->m_GHost->DenyIP( GetExternalIPString( ), 30000, "banned player message" );
}
// request join if we're ready or if ban check is taking too long
if( m_ConnectionState == 0 && m_CallableBanCheck && ( m_CallableBanCheck->GetReady( ) || GetTicks( ) - m_ConnectionTime > 2000 ) )
{
CDBBan *Ban = m_CallableBanCheck->GetResult( );
if( Ban )
{
m_Banned = true;
SendBannedInfo( Ban, "banned" );
}
else
m_Game->EventPlayerJoined( this, m_IncomingJoinPlayer, NULL );
if( m_CallableBanCheck->GetReady( ) )
{
m_Game->m_GHost->m_DB->RecoverCallable( m_CallableBanCheck );
delete m_CallableBanCheck; //deletes Ban too
}
else
{
boost::mutex::scoped_lock lock( m_Game->m_GHost->m_CallablesMutex );
m_Game->m_GHost->m_Callables.push_back( m_CallableBanCheck );
lock.unlock( );
}
m_CallableBanCheck = NULL;
}
// don't call DoSend here because some other players may not have updated yet and may generate a packet for this player
// also m_Socket may have been set to NULL during ProcessPackets but we're banking on the fact that m_DeleteMe has been set to true as well so it'll short circuit before dereferencing
return m_DeleteMe || m_Error || m_Socket->HasError( ) || !m_Socket->GetConnected( );
}
void CPotentialPlayer :: ExtractPackets( )
{
if( !m_Socket )
return;
// extract as many packets as possible from the socket's receive buffer and put them in the m_Packets queue
string *RecvBuffer = m_Socket->GetBytes( );
BYTEARRAY Bytes = UTIL_CreateByteArray( (unsigned char *)RecvBuffer->c_str( ), RecvBuffer->size( ) );
// a packet is at least 4 bytes so loop as long as the buffer contains 4 bytes
while( Bytes.size( ) >= 4 )
{
if( Bytes[0] == W3GS_HEADER_CONSTANT || Bytes[0] == GPS_HEADER_CONSTANT || Bytes[0] == GCBI_HEADER_CONSTANT )
{
// bytes 2 and 3 contain the length of the packet
uint16_t Length = UTIL_ByteArrayToUInt16( Bytes, false, 2 );
if( Length >= 4 )
{
if( Bytes.size( ) >= Length )
{
m_Packets.push( new CCommandPacket( Bytes[0], Bytes[1], BYTEARRAY( Bytes.begin( ), Bytes.begin( ) + Length ) ) );
*RecvBuffer = RecvBuffer->substr( Length );
Bytes = BYTEARRAY( Bytes.begin( ) + Length, Bytes.end( ) );
}
else
return;
}
else
{
m_Error = true;
m_ErrorString = "received invalid packet from player (bad length)";
return;
}
}
else
{
m_Error = true;
m_ErrorString = "received invalid packet from player (bad header constant)";
return;
}
}
}
void CPotentialPlayer :: ProcessPackets( )
{
if( !m_Socket )
return;
// process all the received packets in the m_Packets queue
while( !m_Packets.empty( ) )
{
CCommandPacket *Packet = m_Packets.front( );
m_Packets.pop( );
if( Packet->GetPacketType( ) == W3GS_HEADER_CONSTANT )
{
// the only packet we care about as a potential player is W3GS_REQJOIN, ignore everything else
switch( Packet->GetID( ) )
{
case CGameProtocol :: W3GS_REQJOIN:
delete m_IncomingJoinPlayer;
m_IncomingJoinPlayer = m_Protocol->RECEIVE_W3GS_REQJOIN( Packet->GetData( ) );
if( m_IncomingJoinPlayer && !m_Banned )
{
// check for bans on this player
m_CallableBanCheck = m_Game->m_GHost->m_DB->ThreadedBanCheck( m_Game->GetJoinedRealm( m_IncomingJoinPlayer->GetHostCounter( ) ), m_IncomingJoinPlayer->GetName( ), GetExternalIPString( ), m_Game->m_GHost->HostNameLookup( GetExternalIPString( ) ), m_Game->GetOwnerName( ) );
}
// don't continue looping because there may be more packets waiting and this parent class doesn't handle them
// EventPlayerJoined creates the new player, NULLs the socket, and sets the delete flag on this object so it'll be deleted shortly
// any unprocessed packets will be copied to the new CGamePlayer in the constructor or discarded if we get deleted because the game is full
delete Packet;
return;
}
}
else if( Packet->GetPacketType( ) == GCBI_HEADER_CONSTANT )
{
if( Packet->GetID( ) == CGCBIProtocol :: GCBI_INIT && m_Game->m_GHost->IsLocal( GetExternalIPString( ) ) )
{
delete m_IncomingGarenaUser;
m_IncomingGarenaUser = m_Game->m_GHost->m_GCBIProtocol->RECEIVE_GCBI_INIT( Packet->GetData( ) );
CONSOLE_Print( "[GCBI] Garena user detected; userid=" + UTIL_ToString( m_IncomingGarenaUser->GetUserID( ) ) + ", roomid=" + UTIL_ToString( m_IncomingGarenaUser->GetRoomID( ) ) + ", experience=" + UTIL_ToString( m_IncomingGarenaUser->GetUserExp( ) ) + ", country=" + m_IncomingGarenaUser->GetCountryCode( ) );
}
}
delete Packet;
}
}
void CPotentialPlayer :: Send( BYTEARRAY data )
{
if( m_Socket )
m_Socket->PutBytes( data );
}
void CPotentialPlayer :: SendBannedInfo( CDBBan *Ban, string type )
{
// send slot info to the banned player
CMap *Map = m_Game->GetMap( );
if( Map )
{
vector<CGameSlot> Slots = Map->GetSlots( );
m_Socket->PutBytes( m_Protocol->SEND_W3GS_SLOTINFOJOIN( 2, m_Socket->GetPort( ), GetExternalIP( ), Slots, 0, Map->GetMapGameType( ) == GAMETYPE_CUSTOM ? 3 : 0, Map->GetMapNumPlayers( ) ) );
BYTEARRAY IP;
IP.push_back( 0 );
IP.push_back( 0 );
IP.push_back( 0 );
IP.push_back( 0 );
if( type == "banned" )
m_Socket->PutBytes( m_Protocol->SEND_W3GS_PLAYERINFO( 1, "BANNED", IP, IP ) );
else if( type == "score" )
m_Socket->PutBytes( m_Protocol->SEND_W3GS_PLAYERINFO( 1, "LOW SCORE", IP, IP ) );
// send a map check packet to the new player
m_Socket->PutBytes( m_Protocol->SEND_W3GS_MAPCHECK( Map->GetMapPath( ), Map->GetMapSize( ), Map->GetMapInfo( ), Map->GetMapCRC( ), Map->GetMapSHA1( ) ) );
if(type == "banned")
{
m_Socket->PutBytes( m_Protocol->SEND_W3GS_CHAT_FROM_HOST( 1, UTIL_CreateByteArray( 2 ), 16, BYTEARRAY( ), "Sorry, but you are currently banned." ) );
m_Socket->PutBytes( m_Protocol->SEND_W3GS_CHAT_FROM_HOST( 1, UTIL_CreateByteArray( 2 ), 16, BYTEARRAY( ), " Username: " + Ban->GetName( ) ) );
m_Socket->PutBytes( m_Protocol->SEND_W3GS_CHAT_FROM_HOST( 1, UTIL_CreateByteArray( 2 ), 16, BYTEARRAY( ), " Admin: " + Ban->GetAdmin( ) ) );
m_Socket->PutBytes( m_Protocol->SEND_W3GS_CHAT_FROM_HOST( 1, UTIL_CreateByteArray( 2 ), 16, BYTEARRAY( ), " Reason: " + Ban->GetReason( ) ) );
m_Socket->PutBytes( m_Protocol->SEND_W3GS_CHAT_FROM_HOST( 1, UTIL_CreateByteArray( 2 ), 16, BYTEARRAY( ), " Gamename: " + Ban->GetGameName( ) ) );
}
else if(type == "score") {
m_Socket->PutBytes( m_Protocol->SEND_W3GS_CHAT_FROM_HOST( 1, UTIL_CreateByteArray( 2 ), 16, BYTEARRAY( ), "Error: you do not have the required score or number of wins to join this game." ) );
}
}
}
//
// CGamePlayer
//
CGamePlayer :: CGamePlayer( CGameProtocol *nProtocol, CBaseGame *nGame, CTCPSocket *nSocket, unsigned char nPID, string nJoinedRealm, string nName, BYTEARRAY nInternalIP, bool nReserved ) : CPotentialPlayer( nProtocol, nGame, nSocket ), m_PID( nPID ), m_Name( nName ), m_InternalIP( nInternalIP ), m_JoinedRealm( nJoinedRealm ), m_TotalPacketsSent( 0 ), m_TotalPacketsReceived( 0 ), m_LeftCode( PLAYERLEAVE_LOBBY ), m_SyncCounter( 0 ), m_JoinTime( GetTime( ) ), m_LastMapPartSent( 0 ), m_LastMapPartAcked( 0 ), m_StartedDownloadingTicks( 0 ), m_FinishedLoadingTicks( 0 ), m_StartedLaggingTicks( 0 ), m_TotalLaggingTicks( 0 ), m_StatsSentTime( 0 ), m_StatsDotASentTime( 0 ), m_LastGProxyWaitNoticeSentTime( 0 ), m_Score( -100000.0 ), m_Spoofed( false ), m_Reserved( nReserved ), m_WhoisShouldBeSent( false ), m_WhoisSent( false ), m_DownloadAllowed( false ), m_DownloadStarted( false ), m_DownloadFinished( false ), m_FinishedLoading( false ), m_Lagging( false ), m_DropVote( false ), m_KickVote( false ), m_StartVote( false ), m_Muted( false ), m_LeftMessageSent( false ), m_GProxy( false ), m_GProxyDisconnectNoticeSent( false ), m_GProxyReconnectKey( rand( ) ), m_LastGProxyAckTime( 0 ), m_Autoban( false ), m_ForfeitVote( false ), m_FriendlyName( nName ), m_DrawVote( false ), m_NoLag( false )
{
m_ConnectionState = 1;
}
CGamePlayer :: CGamePlayer( CPotentialPlayer *potential, unsigned char nPID, string nJoinedRealm, string nName, BYTEARRAY nInternalIP, bool nReserved ) : CPotentialPlayer( potential->m_Protocol, potential->m_Game, potential->GetSocket( ) ), m_PID( nPID ), m_Name( nName ), m_InternalIP( nInternalIP ), m_JoinedRealm( nJoinedRealm ), m_TotalPacketsSent( 0 ), m_TotalPacketsReceived( 1 ), m_LeftCode( PLAYERLEAVE_LOBBY ), m_Cookies( 0 ), m_SyncCounter( 0 ), m_JoinTime( GetTime( ) ), m_LastMapPartSent( 0 ), m_LastMapPartAcked( 0 ), m_StartedDownloadingTicks( 0 ), m_FinishedLoadingTicks( 0 ), m_StartedLaggingTicks( 0 ), m_TotalLaggingTicks( 0 ), m_StatsSentTime( 0 ), m_StatsDotASentTime( 0 ), m_LastGProxyWaitNoticeSentTime( 0 ), m_Score( -100000.0 ), m_Spoofed( false ), m_Reserved( nReserved ), m_WhoisShouldBeSent( false ), m_WhoisSent( false ), m_DownloadAllowed( false ), m_DownloadStarted( false ), m_DownloadFinished( false ), m_FinishedLoading( false ), m_Lagging( false ), m_DropVote( false ), m_KickVote( false ), m_StartVote( false ), m_Muted( false ), m_LeftMessageSent( false ), m_GProxy( false ), m_GProxyDisconnectNoticeSent( false ), m_GProxyReconnectKey( rand( ) ), m_LastGProxyAckTime( 0 ), m_Autoban( false ), m_ForfeitVote( false ), m_FriendlyName( nName ), m_DrawVote( false ), m_NoLag( false )
{
// todotodo: properly copy queued packets to the new player, this just discards them
// this isn't a big problem because official Warcraft III clients don't send any packets after the join request until they receive a response
// m_Packets = potential->GetPackets( );
// hackhack: we initialize m_TotalPacketsReceived to 1 because the CPotentialPlayer must have received a W3GS_REQJOIN before this class was created
// to fix this we could move the packet counters to CPotentialPlayer and copy them here
// note: we must make sure we never send a packet to a CPotentialPlayer otherwise the send counter will be incorrect too! what a mess this is...
// that said, the packet counters are only used for managing GProxy++ reconnections
m_ConnectionState = 1;
m_IncomingGarenaUser = potential->GetGarenaUser( );
}
CGamePlayer :: ~CGamePlayer( )
{
}
string CGamePlayer :: GetNameTerminated( )
{
// if the player's name contains an unterminated colour code add the colour terminator to the end of their name
// this is useful because it allows you to print the player's name in a longer message which doesn't colour all the subsequent text
string LowerName = m_Name;
transform( LowerName.begin( ), LowerName.end( ), LowerName.begin( ), (int(*)(int))tolower );
string :: size_type Start = LowerName.find( "|c" );
string :: size_type End = LowerName.find( "|r" );
if( Start != string :: npos && ( End == string :: npos || End < Start ) )
return m_Name + "|r";
else
return m_Name;
}
uint32_t CGamePlayer :: GetPing( bool LCPing )
{
// just average all the pings in the vector, nothing fancy
if( m_Pings.empty( ) )
return 0;
uint32_t AvgPing = 0;
for( unsigned int i = 0; i < m_Pings.size( ); ++i )
AvgPing += m_Pings[i];
AvgPing /= m_Pings.size( );
if( LCPing )
return AvgPing / 2;
else
return AvgPing;
}
bool CGamePlayer :: GetIsIgnoring( string username )
{
transform( username.begin( ), username.end( ), username.begin( ), (int(*)(int))tolower );
for( vector<string> :: iterator i = m_IgnoreList.begin( ); i != m_IgnoreList.end( ); ++i )
{
if( (*i) == username )
return true;
}
return false;
}
void CGamePlayer :: Ignore( string username )
{
if( GetIsIgnoring( username ) ) return;
transform( username.begin( ), username.end( ), username.begin( ), (int(*)(int))tolower );
m_IgnoreList.push_back( username );
}
void CGamePlayer :: UnIgnore( string username )
{
transform( username.begin( ), username.end( ), username.begin( ), (int(*)(int))tolower );
for( vector<string> :: iterator i = m_IgnoreList.begin( ); i != m_IgnoreList.end( ); )
{
if( (*i) == username )
{
m_IgnoreList.erase( i );
continue;
}
++i;
}
}
bool CGamePlayer :: Update( void *fd )
{
// wait 4 seconds after joining before sending the /whois or /w
// if we send the /whois too early battle.net may not have caught up with where the player is and return erroneous results
if( m_WhoisShouldBeSent && !m_Spoofed && !m_WhoisSent && !m_JoinedRealm.empty( ) && GetTime( ) - m_JoinTime >= 4 )
{
// todotodo: we could get kicked from battle.net for sending a command with invalid characters, do some basic checking
for( vector<CBNET *> :: iterator i = m_Game->m_GHost->m_BNETs.begin( ); i != m_Game->m_GHost->m_BNETs.end( ); ++i )
{
if( (*i)->GetServer( ) == m_JoinedRealm )
{
if( m_Game->GetGameState( ) == GAME_PUBLIC )
{
if( (*i)->GetPasswordHashType( ) == "pvpgn" )
(*i)->QueueChatCommand( "/whereis " + m_Name );
else
(*i)->QueueChatCommand( "/whois " + m_Name );
}
else if( m_Game->GetGameState( ) == GAME_PRIVATE )
(*i)->QueueChatCommand( m_Game->m_GHost->m_Language->SpoofCheckByReplying( ), m_Name, true );
}
}
m_WhoisSent = true;
}
// check for socket timeouts
// if we don't receive anything from a player for 30 seconds we can assume they've dropped
// this works because in the lobby we send pings every 5 seconds and expect a response to each one
// and in the game the Warcraft 3 client sends keepalives frequently (at least once per second it looks like)
if( m_Socket && GetTime( ) - m_Socket->GetLastRecv( ) >= 30 )
m_Game->EventPlayerDisconnectTimedOut( this );
// make sure we're not waiting too long for the first MAPSIZE packet
if( m_ConnectionState == 1 && GetTicks( ) - m_ConnectionTime > 5000 && !m_Game->GetGameLoaded() && !m_Game->GetGameLoading() )
{
CONSOLE_Print( "[DENY] Kicking player: MAPSIZE not received within five seconds" );
m_DeleteMe = true;
SetLeftReason( "MAPSIZE not received within five seconds" );
SetLeftCode( PLAYERLEAVE_LOBBY );
m_Game->OpenSlot( m_Game->GetSIDFromPID( GetPID( ) ), false );
m_Game->m_GHost->DenyIP( GetExternalIPString( ), 60000, "MAPSIZE not received within five seconds" );
}
// disconnect if the player is downloading too slowly
if( m_DownloadStarted && !m_DownloadFinished && !m_Game->GetGameLoaded() && !m_Game->GetGameLoading() && GetLastMapPartSent( ) > 0 )
{
uint32_t downloadingTime = GetTicks( ) - m_StartedDownloadingTicks;
if( downloadingTime > 8000 && GetLastMapPartAcked( ) / downloadingTime < 10 ) // GetLastMapPartAcked( ) / downloadingTime is B/ms, approximately KB/sec
{
CONSOLE_Print( "[DENY] Kicking player: download speed too low" );
m_DeleteMe = true;
SetLeftReason( "download speed too low" );
SetLeftCode( PLAYERLEAVE_LOBBY );
m_Game->OpenSlot( m_Game->GetSIDFromPID( GetPID( ) ), false );
}
}
// unmute player
if( GetMuted( ) && ( GetTicks( ) - m_MutedTicks > 60000 || ( m_MutedAuto && GetTicks( ) - m_MutedTicks > 15000 ) ) )
{
SetMuted( false );
m_Game->SendAllChat( "[" + m_Name + "] has been automatically unmuted. (Don't spam or you'll be muted again!)" );
m_MuteMessages.clear( );
}
// GProxy++ acks
if( m_GProxy && GetTime( ) - m_LastGProxyAckTime >= 10 )
{
if( m_Socket )
m_Socket->PutBytes( m_Game->m_GHost->m_GPSProtocol->SEND_GPSS_ACK( m_TotalPacketsReceived ) );
m_LastGProxyAckTime = GetTime( );
}
// base class update
CPotentialPlayer :: Update( fd );
bool Deleting;
if( m_GProxy && m_Game->GetGameLoaded( ) )
Deleting = m_DeleteMe || m_Error;
else
Deleting = m_DeleteMe || m_Error || m_Socket->HasError( ) || !m_Socket->GetConnected( );
// try to find out why we're requesting deletion
// in cases other than the ones covered here m_LeftReason should have been set when m_DeleteMe was set
if( m_Error )
{
m_Game->m_GHost->DenyIP( GetExternalIPString( ), 180000, "player error" );
m_Game->EventPlayerDisconnectPlayerError( this );
m_Socket->Reset( );
return Deleting;
}
if( m_Socket )
{
if( m_Socket->HasError( ) )
{
m_Game->EventPlayerDisconnectSocketError( this );
m_Game->m_GHost->DenyIP( GetExternalIPString( ), 20000, "socket error" );
m_Socket->Reset( );
}
else if( !m_Socket->GetConnected( ) )
{
m_Game->EventPlayerDisconnectConnectionClosed( this );
m_Socket->Reset( );
}
}
return Deleting;
}
void CGamePlayer :: ExtractPackets( )
{
if( !m_Socket )
return;
// extract as many packets as possible from the socket's receive buffer and put them in the m_Packets queue
string *RecvBuffer = m_Socket->GetBytes( );
BYTEARRAY Bytes = UTIL_CreateByteArray( (unsigned char *)RecvBuffer->c_str( ), RecvBuffer->size( ) );
// a packet is at least 4 bytes so loop as long as the buffer contains 4 bytes
while( Bytes.size( ) >= 4 )
{
if( Bytes[0] == W3GS_HEADER_CONSTANT || Bytes[0] == GPS_HEADER_CONSTANT || Bytes[0] == GCBI_HEADER_CONSTANT )
{
// bytes 2 and 3 contain the length of the packet
uint16_t Length = UTIL_ByteArrayToUInt16( Bytes, false, 2 );
if( Length >= 4 )
{
if( Bytes.size( ) >= Length )
{
m_Packets.push( new CCommandPacket( Bytes[0], Bytes[1], BYTEARRAY( Bytes.begin( ), Bytes.begin( ) + Length ) ) );
if( Bytes[0] == W3GS_HEADER_CONSTANT )
++m_TotalPacketsReceived;
*RecvBuffer = RecvBuffer->substr( Length );
Bytes = BYTEARRAY( Bytes.begin( ) + Length, Bytes.end( ) );
}
else
return;
}
else
{
m_Error = true;
m_ErrorString = "received invalid packet from player (bad length)";
return;
}
}
else
{
m_Error = true;
m_ErrorString = "received invalid packet from player (bad header constant)";
return;
}
}
}
void CGamePlayer :: ProcessPackets( )
{
if( !m_Socket )
return;
CIncomingAction *Action = NULL;
CIncomingChatPlayer *ChatPlayer = NULL;
CIncomingMapSize *MapSize = NULL;
bool HasMap = false;
uint32_t CheckSum = 0;
uint32_t Pong = 0;
// process all the received packets in the m_Packets queue
while( !m_Packets.empty( ) )
{
CCommandPacket *Packet = m_Packets.front( );
m_Packets.pop( );
if( Packet->GetPacketType( ) == W3GS_HEADER_CONSTANT )
{
switch( Packet->GetID( ) )
{
case CGameProtocol :: W3GS_LEAVEGAME:
m_Game->EventPlayerLeft( this, m_Protocol->RECEIVE_W3GS_LEAVEGAME( Packet->GetData( ) ) );
break;
case CGameProtocol :: W3GS_GAMELOADED_SELF:
if( m_Protocol->RECEIVE_W3GS_GAMELOADED_SELF( Packet->GetData( ) ) )
{
if( !m_FinishedLoading && m_Game->GetGameLoading( ) )
{
m_FinishedLoading = true;
m_FinishedLoadingTicks = GetTicks( );
m_Game->EventPlayerLoaded( this );
}
else
{
// we received two W3GS_GAMELOADED_SELF packets from this player!
}
}
break;
case CGameProtocol :: W3GS_OUTGOING_ACTION:
Action = m_Protocol->RECEIVE_W3GS_OUTGOING_ACTION( Packet->GetData( ), m_PID );
if( Action )
m_Game->EventPlayerAction( this, Action );
// don't delete Action here because the game is going to store it in a queue and delete it later
break;
case CGameProtocol :: W3GS_OUTGOING_KEEPALIVE:
CheckSum = m_Protocol->RECEIVE_W3GS_OUTGOING_KEEPALIVE( Packet->GetData( ) );
m_CheckSums.push( CheckSum );
++m_SyncCounter;
m_Game->EventPlayerKeepAlive( this, CheckSum );
break;
case CGameProtocol :: W3GS_CHAT_TO_HOST:
ChatPlayer = m_Protocol->RECEIVE_W3GS_CHAT_TO_HOST( Packet->GetData( ) );
if( ChatPlayer )
{
// determine if we should auto-mute this player
if( ChatPlayer->GetType( ) == CIncomingChatPlayer :: CTH_MESSAGE || ChatPlayer->GetType( ) == CIncomingChatPlayer :: CTH_MESSAGEEXTRA )
{
m_MuteMessages.push_back( GetTicks( ) );
if( m_MuteMessages.size( ) > 7 )
m_MuteMessages.erase( m_MuteMessages.begin( ) );
uint32_t RecentCount = 0;
for( unsigned int i = 0; i < m_MuteMessages.size( ); ++i )
{
if( GetTicks( ) - m_MuteMessages[i] < 7000 )
RecentCount++;
}
if( m_Game->m_GHost->m_AutoMuteSpammer && !GetMuted( ) && RecentCount >= 7 )
{
SetMuted( true );
m_MutedAuto = true;
m_Game->SendAllChat( "[" + m_Name + "] has been automatically muted for spamming. (You will be unmuted momentarily, but please do not spam again!)" );
m_MuteMessages.clear( );
}
//now check for flamers
if( m_Game->m_GHost->FlameCheck( ChatPlayer->GetMessage( ) ) )
{
m_FlameMessages.push_back( GetTicks( ) );
if( m_FlameMessages.size( ) > 10 )
m_FlameMessages.erase( m_FlameMessages.begin( ) );
RecentCount = 0;
for( unsigned int i = 0; i < m_FlameMessages.size( ); ++i )
{
if( GetTicks( ) - m_FlameMessages[i] < 80000 )
RecentCount++;
}
if( RecentCount >= 4 )
{
m_Game->SendAllChat( "Use !ignore <playername> to ignore players (for example, if they are flaming); partial names work. Don't flame back!" );
m_FlameMessages.clear( );
}
else if( RecentCount >= 3 )
{
m_Game->SendAllChat( "[Calm] has refilled [" + GetName() + "]'s cookie jar. [" + GetName() + "] now has three cookies (try !eat)!");
SetCookies(3);
}
}
}
m_Game->EventPlayerChatToHost( this, ChatPlayer );
}
delete ChatPlayer;
ChatPlayer = NULL;
break;
case CGameProtocol :: W3GS_DROPREQ:
// todotodo: no idea what's in this packet
if( !m_DropVote )
{
m_DropVote = true;
m_Game->EventPlayerDropRequest( this );
}
break;
case CGameProtocol :: W3GS_MAPSIZE:
m_ConnectionState = 2;
m_ConnectionTime = GetTicks( );
MapSize = m_Protocol->RECEIVE_W3GS_MAPSIZE( Packet->GetData( ), m_Game->m_GHost->m_Map->GetMapSize( ) );
if( MapSize )
m_Game->EventPlayerMapSize( this, MapSize );
delete MapSize;
MapSize = NULL;
break;
case CGameProtocol :: W3GS_PONG_TO_HOST:
Pong = m_Protocol->RECEIVE_W3GS_PONG_TO_HOST( Packet->GetData( ) );
// we discard pong values of 1
// the client sends one of these when connecting plus we return 1 on error to kill two birds with one stone
if( Pong != 1 )
{
// we also discard pong values when we're downloading because they're almost certainly inaccurate
// this statement also gives the player a 5 second grace period after downloading the map to allow queued (i.e. delayed) ping packets to be ignored
if( !m_DownloadStarted || ( m_DownloadFinished && GetTime( ) - m_FinishedDownloadingTime >= 5 ) )
{
// we also discard pong values when anyone else is downloading if we're configured to
if( m_Game->m_GHost->m_PingDuringDownloads || !m_Game->IsDownloading( ) )
{
m_Pings.push_back( GetTicks( ) - Pong );
if( m_Pings.size( ) > 20 )
m_Pings.erase( m_Pings.begin( ) );
}
}
}
m_Game->EventPlayerPongToHost( this, Pong );
break;
}
}
else if( Packet->GetPacketType( ) == GPS_HEADER_CONSTANT )
{
BYTEARRAY Data = Packet->GetData( );
if( Packet->GetID( ) == CGPSProtocol :: GPS_INIT )
{
if( m_Game->m_GHost->m_Reconnect )
{
m_GProxy = true;
m_Socket->PutBytes( m_Game->m_GHost->m_GPSProtocol->SEND_GPSS_INIT( m_Game->m_GHost->m_ReconnectPort, m_PID, m_GProxyReconnectKey, m_Game->GetGProxyEmptyActions( ) ) );
CONSOLE_Print( "[GAME: " + m_Game->GetGameName( ) + "] player [" + m_Name + "] is using GProxy++" );
}
else
{
// todotodo: send notice that we're not permitting reconnects
// note: GProxy++ should never send a GPS_INIT message if bot_reconnect = 0 because we don't advertise the game with invalid map dimensions
// but it would be nice to cover this case anyway
}
}
else if( Packet->GetID( ) == CGPSProtocol :: GPS_RECONNECT )
{
// this is handled in ghost.cpp
}
else if( Packet->GetID( ) == CGPSProtocol :: GPS_ACK && Data.size( ) == 8 )
{
uint32_t LastPacket = UTIL_ByteArrayToUInt32( Data, false, 4 );
uint32_t PacketsAlreadyUnqueued = m_TotalPacketsSent - m_GProxyBuffer.size( );
if( LastPacket > PacketsAlreadyUnqueued )
{
uint32_t PacketsToUnqueue = LastPacket - PacketsAlreadyUnqueued;
if( PacketsToUnqueue > m_GProxyBuffer.size( ) )
PacketsToUnqueue = m_GProxyBuffer.size( );
while( PacketsToUnqueue > 0 )
{
m_GProxyBuffer.pop( );
--PacketsToUnqueue;
}
}
}
}
delete Packet;
}
}
void CGamePlayer :: Send( BYTEARRAY data )
{
// must start counting packet total from beginning of connection
// but we can avoid buffering packets until we know the client is using GProxy++ since that'll be determined before the game starts
// this prevents us from buffering packets for non-GProxy++ clients
++m_TotalPacketsSent;
if( m_GProxy && m_Game->GetGameLoaded( ) )
m_GProxyBuffer.push( data );
CPotentialPlayer :: Send( data );
}
void CGamePlayer :: EventGProxyReconnect( CTCPSocket *NewSocket, uint32_t LastPacket )
{
delete m_Socket;
m_Socket = NewSocket;
m_Socket->PutBytes( m_Game->m_GHost->m_GPSProtocol->SEND_GPSS_RECONNECT( m_TotalPacketsReceived ) );
uint32_t PacketsAlreadyUnqueued = m_TotalPacketsSent - m_GProxyBuffer.size( );
if( LastPacket > PacketsAlreadyUnqueued )
{
uint32_t PacketsToUnqueue = LastPacket - PacketsAlreadyUnqueued;
if( PacketsToUnqueue > m_GProxyBuffer.size( ) )
PacketsToUnqueue = m_GProxyBuffer.size( );
while( PacketsToUnqueue > 0 )
{
m_GProxyBuffer.pop( );
--PacketsToUnqueue;
}
}
// send remaining packets from buffer, preserve buffer
queue<BYTEARRAY> TempBuffer;
while( !m_GProxyBuffer.empty( ) )
{
m_Socket->PutBytes( m_GProxyBuffer.front( ) );
TempBuffer.push( m_GProxyBuffer.front( ) );
m_GProxyBuffer.pop( );
}
m_GProxyBuffer = TempBuffer;
m_GProxyDisconnectNoticeSent = false;
m_Game->SendAllChat( m_Game->m_GHost->m_Language->PlayerReconnectedWithGProxy( m_Name ) );
m_CachedIP = m_Socket->GetIPString( );
}