-
Notifications
You must be signed in to change notification settings - Fork 6
/
cNetwork.cpp
2863 lines (2538 loc) · 78.1 KB
/
cNetwork.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
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
#include "stdafx.h"
#include "cNetwork.h"
//-a teqilla -h 74.201.102.233:9000
bool SockCompare(SOCKADDR_IN *a, SOCKADDR_IN *b);
bool SockCompare(SOCKADDR_IN *a, SOCKADDR_IN *b)
{
if ((memcmp(&a->sin_addr, &b->sin_addr, sizeof(in_addr)))
||
(
(a->sin_port != b->sin_port)
&&
(a->sin_port != b->sin_port + 0x0100)
// XXX: Loginserver is retarded and sends from one port higher sometimes, so we have to account
// and allow for that...
)
) return false;
return true;
}
cNetwork::cNetwork()
{
m_dwGUIDLogin = 0;
f74ccount = 0;
m_zPassword[0] = 0;
WSADATA wsaData;
USHORT wVR = 0x0202;
WSAStartup( wVR, &wsaData );
SOCKADDR_IN siSockAddr;
siSockAddr.sin_family = AF_INET;
siSockAddr.sin_addr.s_addr = INADDR_ANY;
m_sSocket = socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP );
iConnPacketCount = 0;
bPortalMode = false;
int iError = SOCKET_ERROR;
int iSrcPort = 0; // binding to port "0" tells winsock to get a random open port
while (iError == SOCKET_ERROR)
{
siSockAddr.sin_port = htons( iSrcPort );
iError = bind(m_sSocket, (struct sockaddr *) &siSockAddr, sizeof(SOCKADDR_IN));
iSrcPort++;
}
m_dwStartTicks = GetTickCount();
m_zTicketSize = 0;
char acServerIP[32];
int acServerPort = 0;
/* parse command line arguments */
/* the options are the same as the original client */
for (int arg=0; arg < __argc; arg++)
{
/* options always have two characters and start with '-' */
if (strlen(__argv[arg]) != 2) { continue; }
if (__argv[arg][0] == '-')
{
switch (__argv[arg][1])
{
/* server IP address */
case 'h':
{
if (arg + 1 < __argc) {
strcpy(acServerIP, __argv[arg+1]);
if (strchr(acServerIP, ':') != NULL) {
acServerPort = atoi(strchr(acServerIP, ':') + 1);
*strchr(acServerIP, ':') = 0;
}
}
break;
}
/* port number */
case 'p':
{
if (arg + 1 < __argc) {
acServerPort = atoi(__argv[arg+1]);
}
break;
}
/* account */
case 'a':
{
if (arg + 1 < __argc) {
ZeroMemory(m_zAccountName, 40);
strcpy(m_zAccountName, __argv[arg+1]);
// check if password is provided
char* password_index = strchr(m_zAccountName, ':');
if (password_index != NULL) {
strcpy(m_zPassword, password_index + 1);
// end account name string at the colon
*password_index = 0;
}
}
break;
}
/* password */
case 'v':
{
if (arg + 1 < __argc) {
ZeroMemory(m_zPassword, 100);
strcpy(m_zPassword, __argv[arg+1]);
}
break;
}
}
}
}
if (m_zPassword[0] == 0) {
// password wasn't provided at command line so use GLSTicket
HKEY hkTicket;
if (!RegOpenKey(HKEY_CURRENT_USER, "Software\\Turbine\\AC1", &hkTicket))
{
m_zTicketSize = 0xf4;
DWORD tpout = 0x100;
if (RegQueryValueEx(hkTicket, "GLSTicket", NULL, NULL, m_zTicket, &tpout))
{
MessageBox(NULL, "GLSTicket not found!", "Error", MB_OK);
}
}
}
else {
m_zTicketSize = 0;
}
m_siLoginServer.m_saServer.sin_family = AF_INET;
m_siLoginServer.m_saServer.sin_addr.s_addr = inet_addr(acServerIP);
m_siLoginServer.m_wBasePort = acServerPort;
m_treeNameIDCache.clear();
m_pActiveWorld = 0;
Reset();
}
cNetwork::~cNetwork()
{
// Disconnect();
// closesocket(m_sSocket);
WSACleanup();
}
void cNetwork::Reset()
{
//Reset the login servers.
for (std::list<cPacket *>::iterator it = m_siLoginServer.m_lSentPackets.begin(); it != m_siLoginServer.m_lSentPackets.end(); ++it)
{
delete (*it);
}
m_siLoginServer.m_lSentPackets.clear();
m_siLoginServer.m_dwSendSequence = 0;
m_siLoginServer.m_wLogicalID = 0;
m_siLoginServer.m_wTable = 0;
m_siLoginServer.m_dwFlags = 0;
m_siLoginServer.m_dwLastPing = GetTickCount();
m_siLoginServer.m_dwLastSyncSent = 0;
m_siLoginServer.m_dwRecvSequence = 0;
m_siLoginServer.m_dwLastPacketAck = GetTickCount();
m_siLoginServer.m_dwLastPacketSent = GetTickCount();
m_siLoginServer.m_dwLastConnectAttempt = GetTickCount();
//Now the world servers..
for (std::list<stServerInfo>::iterator i = m_siWorldServers.begin(); i != m_siWorldServers.end(); i++)
{
for (std::list<cPacket *>::iterator j = (*i).m_lSentPackets.begin(); j != (*i).m_lSentPackets.end(); ++j)
{
delete (*j);
}
(*i).m_lSentPackets.clear();//Not really necessary?
}
m_siWorldServers.clear();
m_dwStartTicks = GetTickCount();
m_dwGameEventOut = 0;
// start 0. we pre-increment for each fragment so the first one out will be 1
// XXX: should we be keeping track of this separately for each server? also when do we start it back at 0?
m_dwFragmentSequenceOut = 0;
}
static DWORD checksum(const void* data, size_t size)
{
DWORD result = static_cast<DWORD>(size) << 16;
for (size_t i = 0; i < size / 4; i++)
{
result += static_cast<const DWORD*>(data)[i];
}
int shift = 24;
for (size_t i = (size / 4) * 4; i < size; i++)
{
result += static_cast<const BYTE*>(data)[i] << shift;
shift -= 8;
}
return result;
}
static DWORD checksumHeader(stTransitHeader& header)
{
DWORD origChecksum = header.m_dwCRC;
header.m_dwCRC = 0xBADD70DD;
DWORD result = checksum(&header, sizeof(stTransitHeader));
header.m_dwCRC = origChecksum;
return result;
}
static DWORD checksumContent(stTransitHeader& header, const void* data)
{
if (header.m_dwFlags & kBlobFragments)
{
cByteStream reader((BYTE *) data, header.m_wSize);
if (header.m_dwFlags & kServerSwitch)
{
reader.ReadGroup(8);
}
if (header.m_dwFlags & kRequestRetransmit)
{
DWORD nseq = reader.ReadDWORD();
reader.ReadGroup(nseq * sizeof(DWORD));
}
if (header.m_dwFlags & kRejectRetransmit)
{
DWORD nseq = reader.ReadDWORD();
reader.ReadGroup(nseq * sizeof(DWORD));
}
if (header.m_dwFlags & kAckSequence)
{
reader.ReadGroup(4);
}
if (header.m_dwFlags & kCICMDCommand)
{
reader.ReadGroup(8);
}
if (header.m_dwFlags & kTimeSync)
{
reader.ReadGroup(8);
}
if (header.m_dwFlags & kEchoRequest)
{
reader.ReadGroup(4);
}
if (header.m_dwFlags & kEchoResponse)
{
reader.ReadGroup(8);
}
if (header.m_dwFlags & kFlow)
{
reader.ReadGroup(6);
}
DWORD result = checksum(data, reader.GetOffset());
while (!reader.AtEOF())
{
const stFragmentHeader* fragment = (stFragmentHeader*) reader.ReadGroup(sizeof(stFragmentHeader));
reader.ReadGroup(fragment->m_wSize - sizeof(stFragmentHeader));
result += checksum(fragment, fragment->m_wSize);
}
return result;
}
return checksum(data, header.m_wSize);
}
static DWORD checksumPacket(cPacket *packet, ChecksumXorGenerator * xorGen)
{
stTransitHeader *header = packet->GetTransit();
DWORD xorVal = (header->m_dwFlags & kEncryptedChecksum) ? xorGen->get(header->m_dwSequence) : 0;
return checksumHeader(*header) + (checksumContent(*header, packet->GetPayload()) ^ xorVal);
}
void cNetwork::SendPacket(cPacket *Packet, stServerInfo *Target, bool IncludeSeq, bool IncrementSeq)
{
#ifndef TerrainOnly
if (!Target)
return;
stTransitHeader *Head = Packet->GetTransit();
//calc size (remove header from length)
Head->m_wSize = Packet->GetLength() - (int) sizeof(stTransitHeader);
if (IncrementSeq)
{
Target->m_dwSendSequence++;
}
if (IncludeSeq) {
Head->m_dwSequence = Target->m_dwSendSequence;
Head->m_wTime = GetTime();
}
else {
Head->m_dwSequence = 0;
Head->m_wTime = 0;
}
if (Target->m_dwFlags & SF_CONNECTED) {
Head->m_wID = Target->m_wLogicalID;
Head->m_wTable = Target->m_wTable;
}
else {
Head->m_wID = 0;
Head->m_wTable = 0;
}
if (Packet->GetTransit()->m_dwFlags & kEncryptedChecksum)
{
if (!(Target->m_dwFlags & SF_CRCSEEDS)) {
m_Interface->OutputConsoleString("WARNING: trying to send encrypted-checksum packet with no seeds (OK if loginserver)");
}
}
Head->m_dwCRC = checksumPacket(Packet, Target->clientXorGen);
SendPacket(Packet, Target);
#endif
}
/* Send packet to login server */
void cNetwork::SendLSPacket(cPacket *Packet, bool IncludeSeq, bool IncrementSeq)
{
return SendPacket(Packet, &m_siLoginServer, IncludeSeq, IncrementSeq);
// stTransitHeader *Head = Packet->GetTransit();
// //calc size (remove header from length)
// Head->m_wSize = Packet->GetLength() - (int) sizeof(stTransitHeader);
//if (IncrementSeq)
//{
// m_siLoginServer.m_dwSendSequence++;
//}
//if (IncludeSeq) {
// Head->m_dwSequence = m_siLoginServer.m_dwSendSequence;
// Head->m_wTime = GetTime();
//}
//else {
// Head->m_dwSequence = 0;
// Head->m_wTime = 0;
//}
//Head->m_wID = m_siLoginServer.m_wLogicalID;
//Head->m_wTable = m_siLoginServer.m_wTable;
//Head->m_dwCRC = checksumPacket(Packet, m_siLoginServer.clientXorGen);
//SendPacket(Packet, &m_siLoginServer);
}
void cNetwork::SendLostPacket(int iSendSequence, stServerInfo *Target)
{
Lock();
for (std::list<cPacket *>::iterator i = Target->m_lSentPackets.begin(); i != Target->m_lSentPackets.end(); i++)
{
cPacket *Packet = *i;
if (Packet->GetTransit()->m_dwSequence == iSendSequence)
{
//Match
m_Interface->OutputConsoleString("Resending %X (%X) on %s", iSendSequence, Packet->GetTransit()->m_dwFlags, inet_ntoa(Target->m_saServer.sin_addr));
if (Packet->GetTransit()->m_dwFlags & 0x200)
{
Packet->GetTransit()->m_wTime = GetTime();
Packet->GetTransit()->m_dwFlags = 0x00000201;
//DWORD dwNewCRC;
//Packet->GetTransit()->m_dwCRC = dwNewCRC;
sendto(m_sSocket, (char *)Packet->GetData(), Packet->GetLength(), NULL, (SOCKADDR *)&Target->m_saServer, sizeof( SOCKADDR ) );
Unlock();
return;
}
else
{
Packet->GetTransit()->m_wTime = GetTime();
sendto(m_sSocket, (char *)Packet->GetData(), Packet->GetLength(), NULL, (SOCKADDR *)&Target->m_saServer, sizeof( SOCKADDR ) );
Unlock();
return;
}
break;
}
}
Unlock();
m_Interface->OutputConsoleString("Couldn't resend %X on server %s, packet not found!", iSendSequence, inet_ntoa(Target->m_saServer.sin_addr));
}
void cNetwork::SendPacket(cPacket *Packet, stServerInfo *Target)
{
BYTE *pbData = Packet->GetData();
int iLength = Packet->GetLength();
// server wants connect response on next higher port
if (Packet->GetTransit()->m_dwFlags == kConnectResponse)
{
Target->m_saServer.sin_port = htons(Target->m_wBasePort + 1);
} else {
Target->m_saServer.sin_port = htons(Target->m_wBasePort);
}
//m_Interface->OutputConsoleString("Sending Packet: Seq: %i, Dest: %s:%i", Packet->GetTransit()->m_dwSequence, inet_ntoa(Target->m_saServer.sin_addr), htons(Target->m_saServer.sin_port));
int tp = sendto(m_sSocket, (char *) pbData, iLength, NULL, (SOCKADDR *)&Target->m_saServer, sizeof( SOCKADDR ) );
//don't cache packets without a sequence number
//don't cache ping packets, they have a mirrored send sequence
//don't cache 0x100 packets, they have a mirrored send sequence
if (Packet->GetTransit()->m_dwSequence == 0 ||
Packet->GetTransit()->m_dwFlags & 4 ||
Packet->GetTransit()->m_dwFlags & 0x100 ||
Packet->GetTransit()->m_dwFlags & 0x400)
delete Packet;
else
{
Lock();
Target->m_lSentPackets.push_back(Packet);
Target->m_dwLastPacketSent = GetTickCount();
Unlock();
}
}
void cNetwork::SetInterface(cInterface *Interface)
{
m_Interface = Interface;
}
void cNetwork::SetObjectDB(cObjectDB *ObjectDB)
{
m_ObjectDB = ObjectDB;
}
void cNetwork::SetCharInfo(cCharInfo *CharInfo)
{
m_CharInfo = CharInfo;
}
WORD cNetwork::GetTime()
{
return (WORD)((GetTickCount() - m_dwStartTicks) / 500.0f);
}
void cNetwork::Connect()
{
m_Interface->OutputConsoleString("--- New Session... Connecting... ---");
m_Interface->SetInterfaceMode(eConnecting);
m_Interface->SetConnProgress(0);
//Clear all connection stuff, incase of repeated connect attempts.
Reset();
cPacket *LoginPacket = new cPacket();
stTransitHeader header;
header.m_dwFlags = 0x00010000;
LoginPacket->Add(&header, sizeof(stTransitHeader));
LoginPacket->Add(std::string("1802")); // magic string
// Data length left in packet including ticket (FIXME: calculate this, but ACEmulator doesn't seem to care)
if (m_zPassword[0] != 0) {
LoginPacket->Add((DWORD)0x00000020);
} else {
LoginPacket->Add((DWORD)0x00000116);
}
// Authentication Type
if (m_zPassword[0] != 0) {
LoginPacket->Add((DWORD)kAuthAccountPassword);
} else {
LoginPacket->Add((DWORD)kAuthGlsTicket);
}
LoginPacket->Add((DWORD)0x00000000); // Authentication Flags
LoginPacket->Add((DWORD)time(NULL)); // Timestamp
LoginPacket->Add(std::string(m_zAccountName)); // Account name
// Empty string for special admin account name
LoginPacket->Add(std::string());
if (m_zPassword[0] != 0) {
LoginPacket->AddString32L(std::string(m_zPassword)); // Password uses weird 32L format
} else {
LoginPacket->Add((DWORD)0x000000F6);
LoginPacket->Add((WORD)0xF480);
LoginPacket->Add(m_zTicket, m_zTicketSize);
}
SendLSPacket(LoginPacket, true, false);
m_siLoginServer.m_dwConnectAttempts++;
m_siLoginServer.m_dwLastConnectAttempt = GetTickCount();
}
void cNetwork::CloseConnection(stServerInfo *Server)
{
static BYTE CLOSE_CONNECTION[] =
{
0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0xD4, 0x72, 0xF2, 0xBA, 0xD7, 0x01, 0x00, 0x00,
0x00, 0x00, 0x01, 0x00
};
cPacket *CloseClient = new cPacket();
CloseClient->Add(CLOSE_CONNECTION, sizeof(CLOSE_CONNECTION));
if (Server == &m_siLoginServer)
SendLSPacket(CloseClient, false, false);
else
SendPacket(CloseClient, Server, false, false);
}
void cNetwork::Disconnect()
{
if (m_siLoginServer.m_dwFlags & SF_CONNECTED) {
CloseConnection(&m_siLoginServer);
Lock();
m_siLoginServer.m_dwFlags &= ~SF_CONNECTED;
Unlock();
}
for (std::list<stServerInfo>::iterator i = m_siWorldServers.begin(); i != m_siWorldServers.end(); i++)
{
if (i->m_dwFlags & SF_CONNECTED) {
CloseConnection(&*i);
Lock();
i->m_dwFlags &= ~SF_CONNECTED;
Unlock();
}
}
}
void cNetwork::PingServer(stServerInfo *Server)
{
// m_Interface->OutputConsoleString("Pinging %s:%i...", inet_ntoa(Server->m_saServer.sin_addr), ntohs(Server->m_saServer.sin_port));
static BYTE PING_PACKET[] = {
0x00, 0x00, 0x00, 0x00,
0x04, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
};
// Lock();
memcpy(&PING_PACKET[20], &Server->m_dwRecvSequence, 4);
// Unlock();
cPacket *Ping = new cPacket;
Ping->Add(PING_PACKET, sizeof(PING_PACKET));
if (Server == &m_siLoginServer)
SendLSPacket(Ping, true, false);
else
SendPacket(Ping, Server, true, false);
// Lock();
Server->m_dwLastPing = GetTickCount();
// Unlock();
}
void cNetwork::SyncServer(stServerInfo *Server)
{
// m_Interface->OutputConsoleString("Syncing with %s:%i...", inet_ntoa(Server->m_saServer.sin_addr), ntohs(Server->m_saServer.sin_port));
static BYTE SYNC_PACKET[] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
// Lock();
DWORD TimeDiff = (GetTickCount() - Server->m_dwLastSyncRecv);
double TimeEstimate = Server->m_flServerTime + (TimeDiff / 1000.0f);
Server->m_dwLastSyncSent = GetTickCount();
// Unlock();
}
void cNetwork::CheckPings()
{
if (iConnPacketCount >= 10)
{
if (m_siLoginServer.m_dwLastPing < (GetTickCount() - 2000))
{
PingServer(&m_siLoginServer);
}
if ((m_siLoginServer.m_dwFlags & SF_CRCSEEDS) &&
(m_siLoginServer.m_dwFlags & SF_CONNECTED))
{
if (m_siLoginServer.m_dwLastSyncSent < (GetTickCount() - 2000))
{
SyncServer(&m_siLoginServer);
}
}
for (std::list<stServerInfo>::iterator i = m_siWorldServers.begin(); i != m_siWorldServers.end(); i++)
{
stServerInfo j = *i;
if (j.m_dwLastPing < (GetTickCount() - 2000))
{
PingServer(&j);
}
if ((j.m_dwFlags & SF_CRCSEEDS) &&
(j.m_dwFlags & SF_CONNECTED))
{
if (j.m_dwLastSyncSent < (GetTickCount() - 2000))
{
SyncServer(&j);
}
}
}
}
}
void cNetwork::Run()
{
//message loop for the network thread
while (!m_bQuit)
{
//keep trying to connect to login server if first time doesn't work
if (!(m_siLoginServer.m_dwFlags & SF_CONNECTED))
{
// timeout trying to connect
if ((m_siLoginServer.m_dwLastConnectAttempt + TIMEOUT_MS) < GetTickCount())
{
m_Interface->OutputConsoleString("Timed out after %d ms.", TIMEOUT_MS);
m_Interface->OutputConsoleString("Couldn't connect first time, trying again..");
Connect();
}
}
cPacket *Packet = new cPacket();
BYTE bRawData[1024];
SOCKADDR Target;
int siSize = sizeof( sockaddr_in );
int iRawSize = recvfrom( m_sSocket, (char *)bRawData, 1024, NULL, &Target, &siSize );
if (iRawSize == SOCKET_ERROR)
continue;
Packet->Add(bRawData, iRawSize);
bool bFound = false;
// make sure we recognize this server before processing the packet
stServerInfo* verifiedServer = NULL;
if (SockCompare((SOCKADDR_IN *)&Target, &m_siLoginServer.m_saServer)) {
verifiedServer = &m_siLoginServer;
}
else {
for (std::list<stServerInfo>::iterator i = m_siWorldServers.begin(); i != m_siWorldServers.end(); i++)
{
if (SockCompare((SOCKADDR_IN *)&Target, &(*i).m_saServer))
{
verifiedServer = &(*i);
}
}
}
if (verifiedServer != NULL) {
ProcessPacket(Packet, verifiedServer);
if (verifiedServer->m_dwLastPacketAck + ACK_INTERVAL_MS < GetTickCount()) {
SendAckPacket(verifiedServer);
}
} else {
/** We didn't recognize the packet source. Dump some info to the console for troubleshooting purposes. */
SOCKADDR_IN *tp = (SOCKADDR_IN *) &Target;
char tps[50];
char *tps2 = inet_ntoa(m_siLoginServer.m_saServer.sin_addr);
strcpy(tps, tps2);
m_Interface->OutputConsoleString("Received packet from unknown server: %s:%i. Login server: %s:%i"
, inet_ntoa(tp->sin_addr)
, (int)ntohs(tp->sin_port)
, tps
, (int)ntohs(m_siLoginServer.m_saServer.sin_port));
m_Interface->OutputConsoleString("World servers:");
DumpWorldServerList();
delete Packet;
}
CheckPings();
}
}
void cNetwork::SendAckPacket(stServerInfo *Server) {
stTransitHeader header;
header.m_dwFlags = kAckSequence | kFlow | kEncryptedChecksum;
cPacket *ackSequence = new cPacket();
ackSequence->Add(&header, sizeof(header));
ackSequence->Add((DWORD)Server->m_dwRecvSequence);
SendPacket(ackSequence, Server, true, false);
Server->m_dwLastPacketAck = GetTickCount();
}
void cNetwork::ProcessFragment(cByteStream* stream, stServerInfo *Server) {
//Loop through the fragments
while (!stream->AtEOF())
{
const stFragmentHeader *fragHead = (const stFragmentHeader *)stream->ReadGroup(sizeof(stFragmentHeader));
WORD payloadSize = fragHead->m_wSize - sizeof(stFragmentHeader);
BYTE *fragData = stream->ReadGroup(payloadSize);
if (fragHead->m_wCount == 1)
{
// if count is 1 it's just a singular message, no group. process immediately!
cMessage *Msg = new cMessage(fragData, fragHead);
ProcessMessage(Msg, Server);
}
else
{
//Check for existing fragments
bool bAdded = false;
for (std::list< cMessage * >::iterator it = Server->m_lIncomingMessages.begin(); it != Server->m_lIncomingMessages.end(); it++)
{
if (bAdded)
break;
cMessage *scan = *it;
/* fragment matches existing sequence we have started receiving */
if (scan->m_dwSequence == fragHead->m_dwSequence)
{
scan->AddChunk(fragData, payloadSize, fragHead->m_wIndex);
bAdded = true;
if (scan->IsComplete())
{
ProcessMessage(scan, Server);
Server->m_lIncomingMessages.erase(it);
}
break;
}
}
//No existing group matches, create one
if (!bAdded)
{
cMessage *Msg = new cMessage(fragData, fragHead);
Server->m_lIncomingMessages.push_back(Msg);
}
}
}
}
void cNetwork::ProcessPacket(cPacket *Packet, stServerInfo *Server)
{
// Lock();
stTransitHeader *Head = (stTransitHeader *) Packet->GetData();
BYTE *Data = Packet->GetData() + sizeof(stTransitHeader);
cByteStream stream(Data, Head->m_wSize);
DWORD dwFlags = Head->m_dwFlags;
if (dwFlags & kServerSwitch) {
// server ID?
stream.ReadDWORD();
stream.ReadDWORD();
}
if (dwFlags & kRetransmission)
{
// XXX: not sure how to handle this one yet
//Flags a packet that has been resent
dwFlags &= ~kRetransmission;
}
if (dwFlags & kRequestRetransmit)
{
// XXX: not sure how to handle this one yet
dwFlags &= ~kRejectRetransmit;
}
if (dwFlags & kRejectRetransmit)
{
// XXX: not sure how to handle this one yet
dwFlags &= ~kRejectRetransmit;
}
if (dwFlags & kEncryptedChecksum)
{
//TODO: Check the checksum
dwFlags &= ~kEncryptedChecksum;
}
if (dwFlags & kAckSequence)
{
DWORD ackSequenceNumber = stream.ReadDWORD();
Server->m_dwSendSequence = max(Server->m_dwSendSequence, ackSequenceNumber);
// TODO: Clear saved packets with sequences before the acked one
dwFlags &= ~kAckSequence;
}
else {
// update sequence number only if not an ack
// XXX: are there other cases we should not update sequence number?
// XXX: are there cases where we should update even if it's just an ack?
if (Head->m_dwSequence != Server->m_dwRecvSequence + 1) {
Server->m_dwRecvSequence += 1;
}
else {
if (Head->m_dwSequence <= Server->m_dwRecvSequence && Head->m_dwSequence != 0) {
// we already received this packet
m_Interface->OutputConsoleString("Received packet #%d again", Head->m_dwSequence);
}
else if (Head->m_dwSequence > Server->m_dwRecvSequence + 1) {
// we missed a packet
// TODO: handle out of order packet by storing it and playing back later when we get the preceding packet
m_Interface->OutputConsoleString("Received out of order packet with id #%d", Head->m_dwSequence);
Server->m_dwRecvSequence = Head->m_dwSequence;
}
}
}
// Second step of the connection process is to receive a Connect Request packet from the server
if (dwFlags & kConnectRequest)
{
m_Interface->OutputConsoleString("Received connection request from server...");
// Connection request from the server
Server->m_wTable = Head->m_wTable;
Server->m_dwLastSyncRecv = GetTickCount();
Server->m_dwFlags |= SF_CONNECTED;
Server->m_flServerTime = stream.ReadDouble(); //Time sync
Server->m_qwCookie = stream.ReadQWORD(); // Connection cookie
Server->m_wLogicalID = stream.ReadWORD(); // Client ID for our session
WORD paddingWord = stream.ReadWORD();
DWORD serverSeed = stream.ReadDWORD(); // for encrtypted checksum
DWORD clientSeed = stream.ReadDWORD(); // for encrypted checksum
Server->serverXorGen = new ChecksumXorGenerator();
Server->clientXorGen = new ChecksumXorGenerator();
Server->serverXorGen->init(serverSeed);
Server->clientXorGen->init(clientSeed);
Server->m_dwFlags |= SF_CRCSEEDS;
DWORD unknownPadding = stream.ReadDWORD();
m_Interface->SetConnProgress(0.1f);
// XXX: delay to avoid race condition where server hasn't entered AuthConnectResponse state
Sleep(500);
m_Interface->SetConnProgress(0.5f);
m_Interface->OutputConsoleString("Sending connect response...");
// Final third step of the connection process is to send connect response packet with cookie
SendConnectResponse();
m_Interface->SetConnProgress(0.2f);
dwFlags &= ~kConnectRequest;
// login server is world server unless we get a redirect
// use the same CRC, etc.
SOCKADDR_IN tpaddr;
memcpy(&tpaddr, &Server->m_saServer, sizeof(tpaddr));
tpaddr.sin_port = htons(Server->m_wBasePort);
AddWorldServer(tpaddr);
SetActiveWorldServer(tpaddr);
m_pActiveWorld->clientXorGen = Server->clientXorGen;
m_pActiveWorld->serverXorGen = Server->serverXorGen;
m_pActiveWorld->m_dwFlags |= SF_CRCSEEDS | SF_CONNECTED;
m_pActiveWorld->m_wLogicalID = Server->m_wLogicalID;
m_pActiveWorld->m_wTable = 0x14; // XXX: from pcaps?
}
if (dwFlags & kNetError1)
{
//? I seem to get these when connecting with a stale gls ticket
MessageBox(NULL, "Stale GLS Ticket", "Error", MB_OK);
dwFlags &= ~kNetError1;
}
if (dwFlags & kBlobFragments)
{
ProcessFragment(&stream, Server);
dwFlags &= ~kBlobFragments;
}
if (dwFlags & kTimeSync)
{
double serverTime = stream.ReadDouble();
time_t sT = (DWORD)serverTime;
time_t offset = time(NULL) - sT;
char *woohoo = ctime(&offset);
Server->m_dwLastSyncRecv = GetTickCount();
Server->m_flServerTime = serverTime;
dwFlags &= ~kTimeSync;
}
if (dwFlags > 0)
{
m_Interface->OutputConsoleString("LS: Unhandled Flags: %08X", dwFlags);
}
// if (dwFlags & 0x00800000) { //Displays a server error
// DWORD error = stream.ReadDWORD();
// ServerLoginError( error );
// dwFlags &= ~0x00800000;
//}
//case 0x00000000: //stripped packets
// {
// break;
// }
//case 0x00000002: //requests lost packets
// {
// DWORD packetCount = *((DWORD *)&Data[iPos]); iPos += 4;
// for (int i = 0; i < (int)packetCount; i++)
// {
// DWORD packetSeq = *((DWORD *)&Data[iPos]); iPos += 4;
// SendLostPacket(packetSeq, &m_siLoginServer);
// }
// break;
// }
//case 0x00000004: //ping
// {
// Lock();
// DWORD serverSequence = *((DWORD *)&Data[iPos]);
// if ((int)serverSequence < Server->m_iSendSequence)
// {
// //allow 1000 latency
// if ((Server->m_dwLastPacketSent + 1000) < GetTickCount())
// {
// //server lost some packets
// for (int i = serverSequence + 1; i <= Server->m_iSendSequence; i++)
// {
// SendLostPacket(i, &m_siLoginServer);
// }
// }
// }
// else if ((int)serverSequence > Server->m_iSendSequence)
// {
// m_Interface->OutputConsoleString("Login sequence is AHEAD of the client (previous connection?)");
// }
// Unlock();
// break;
// }
//case 0x00000008: //declines requested packets
// break;
//case 0x00000100: //update CRC
// m_Interface->OutputConsoleString("Received 0x100 on login server?");
// break;
// case 0x00000200: //game-related messages
//
// //Loop through the fragments
// while ((iPos + sizeof(stFragmentHeader)) < Head->m_wSize)
// {
// stFragmentHeader *FragHead = (stFragmentHeader *)&Data[iPos];
// BYTE *FragData = sizeof(stFragmentHeader) + &Data[iPos];
// iPos += FragHead->m_wSize;
//
// if (FragHead->m_wCount == 1)
// {
// cMessage *Msg = new cMessage(FragData, FragHead);
// ProcessMessage(Msg, &m_siLoginServer);
// }
// else
// {
// if (Server->m_lIncomingMessages.size() > 0)
// {
// //Check for existing fragments