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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
|
#include "communication.hh"
#include "config.hh"
#include "connections.hh"
#include "containers.hh"
#include "crypto.hh"
#include "query.hh"
#include "threads.hh"
#include "stubs.hh"
#include <poll.h>
#include <signal.h>
// NOTE(fusion): We seem to add this value of 48 every time `NetLoad` is called,
// and I assume it is to account for IPv4 (20 bytes) and TCP (20 bytes) headers
// although there are still 8 bytes on the table that I'm not sure where are
// comming from.
#define PACKET_AVERAGE_SIZE_OVERHEAD 48
#define MAX_COMMUNICATION_THREADS 1100
#define THREAD_OWN_STACK_SIZE ((int)KB(64))
static int TERMINALVERSION[3] = {770, 770, 770};
static int TCPSocket;
static ThreadHandle AcceptorThread;
static pid_t AcceptorThreadPID;
static int ActiveConnections;
static Semaphore RSAMutex(1);
static TRSAPrivateKey PrivateKey;
static TQueryManagerConnectionPool QueryManagerConnectionPool(10);
static int LoadHistory[360];
static int LoadHistoryPointer;
static int TotalLoad;
static int TotalSend;
static int TotalRecv;
static uint32 LagEnd;
static uint32 EarliestFreeAccountAdmissionRound;
static store<TWaitinglistEntry, 100> Waitinglist;
static TWaitinglistEntry *WaitinglistHead;
static Semaphore CommunicationThreadMutex(1);
static bool UseOwnStacks;
static uint8 CommunicationThreadStacks[MAX_COMMUNICATION_THREADS][THREAD_OWN_STACK_SIZE];
static pid_t LastUsingCommunicationThread[MAX_COMMUNICATION_THREADS];
static int FreeCommunicationThreadStacks[MAX_COMMUNICATION_THREADS];
static int NumberOfFreeCommunicationThreadStacks;
// Communication Thread Stacks
// =============================================================================
void GetCommunicationThreadStack(int *StackNumber, void **Stack){
*StackNumber = -1;
*Stack = NULL;
if(!UseOwnStacks){
error("GetCommunicationThreadStack: Bibliothek unterstützt keine eigenen Stacks.\n");
return;
}
CommunicationThreadMutex.down();
for(int i = 0; i < NumberOfFreeCommunicationThreadStacks; i += 1){
int FreeStack = FreeCommunicationThreadStacks[i];
if(LastUsingCommunicationThread[FreeStack] == 0
|| kill(LastUsingCommunicationThread[FreeStack], 0) == -1){
// NOTE(fusion): A little swap and pop action.
NumberOfFreeCommunicationThreadStacks -= 1;
FreeCommunicationThreadStacks[i] = FreeCommunicationThreadStacks[NumberOfFreeCommunicationThreadStacks];
*StackNumber = FreeStack;
*Stack = CommunicationThreadStacks[FreeStack];
break;
}
}
CommunicationThreadMutex.up();
}
void AttachCommunicationThreadStack(int StackNumber){
LastUsingCommunicationThread[StackNumber] = getpid();
}
void ReleaseCommunicationThreadStack(int StackNumber){
CommunicationThreadMutex.down();
FreeCommunicationThreadStacks[NumberOfFreeCommunicationThreadStacks] = StackNumber;
NumberOfFreeCommunicationThreadStacks += 1;
CommunicationThreadMutex.up();
}
void InitCommunicationThreadStacks(void){
if(UseOwnStacks){
memset(CommunicationThreadStacks, 0xAA, sizeof(CommunicationThreadStacks));
for(int i = 0; i < MAX_COMMUNICATION_THREADS; i += 1){
LastUsingCommunicationThread[i] = 0;
FreeCommunicationThreadStacks[i] = i;
}
NumberOfFreeCommunicationThreadStacks = MAX_COMMUNICATION_THREADS;
}
}
void ExitCommunicationThreadStacks(void){
if(UseOwnStacks){
if(NumberOfFreeCommunicationThreadStacks != MAX_COMMUNICATION_THREADS){
error("FreeCommunicationThreadStacks: Nicht alle Stacks freigegeben.\n");
}
int HighestStackAddress = -1;
int LowestStackAddress = THREAD_OWN_STACK_SIZE;
for(int i = 0; i < MAX_COMMUNICATION_THREADS; i += 1){
for(int Addr = 0; Addr < THREAD_OWN_STACK_SIZE; Addr += 1){
if(CommunicationThreadStacks[i][Addr] != 0xAA){
if(Addr < LowestStackAddress){
LowestStackAddress = Addr;
}
if(Addr > HighestStackAddress){
HighestStackAddress = Addr;
}
}
}
}
// NOTE(fusion): It seems we want to track whether the stack size is
// too small but I'd argue the method is not very robust.
if((HighestStackAddress - LowestStackAddress) > (THREAD_OWN_STACK_SIZE / 2)){
error("Maximale Stack-Ausdehnung: %d..%d\n", LowestStackAddress, HighestStackAddress);
}
}
}
// Load History
// =============================================================================
void InitLoadHistory(void){
for(int i = 0; i < NARRAY(LoadHistory); i += 1){
LoadHistory[i] = 0;
}
LoadHistoryPointer = 0;
TotalLoad = 0;
TotalSend = 0;
TotalRecv = 0;
LagEnd = 0;
EarliestFreeAccountAdmissionRound = 0;
InitLog("netload");
}
bool LagDetected(void){
return RoundNr <= LagEnd;
}
void NetLoad(int Amount, bool Send){
CommunicationThreadMutex.down();
if(Send){
TotalSend += Amount;
}else{
TotalRecv += Amount;
}
CommunicationThreadMutex.up();
}
void NetLoadSummary(void){
CommunicationThreadMutex.down();
Log("netload", "gesendet: %d Bytes.\n", TotalSend);
Log("netload", "empfangen: %d Bytes.\n", TotalRecv);
TotalSend = 0;
TotalRecv = 0;
CommunicationThreadMutex.up();
}
void NetLoadCheck(void){
static int LastRecv;
int DeltaRecv = TotalRecv - LastRecv;
LastRecv = TotalRecv;
if(DeltaRecv < 0){
return;
}
int DeltaRecvPerPlayer = 0;
int PlayersOnline = GetPlayersOnline();
if(PlayersOnline > 0){
DeltaRecvPerPlayer = DeltaRecv / PlayersOnline;
}
TotalLoad -= LoadHistory[LoadHistoryPointer];
TotalLoad += DeltaRecvPerPlayer;
LoadHistory[LoadHistoryPointer] = DeltaRecvPerPlayer;
LoadHistoryPointer += 1;
if(LoadHistoryPointer >= NARRAY(LoadHistory)){
LoadHistoryPointer = 0;
}
// NOTE(fusion): Running this lag check only makes sense if `LoadHistory`
// is filled up which won't be the case until this function executes at
// least as many times as there are entries in `LoadHistory`.
// Looking at `AdvanceGame`, we see that this function is called every
// 10 rounds, giving us the value of `EarliestLagCheckRound`.
constexpr uint32 EarliestLagCheckRound = 10 * NARRAY(LoadHistory);
if(RoundNr >= EarliestLagCheckRound && PlayersOnline >= 50){
int AvgDeltaRecvPerPlayer = (TotalLoad / NARRAY(LoadHistory));
if(DeltaRecvPerPlayer < (AvgDeltaRecvPerPlayer / 2)){
Log("game", "Lag erkannt!\n");
LagEnd = RoundNr + 30;
// NOTE(fusion): This formula looks weird but when we take `MaxPlayers`
// and `PremiumPlayerBuffer` to be 950 and 150 (taken from the config
// file, although their values are now loaded from the database), we
// get a line with negative values when the number of players online
// is less than 650, and exactly 60 when it is 950. Since the delay
// is 60 when `PremiumPlayerBuffer` is zero, I don't think this is a
// coincidence.
int FreeAccountAdmissionDelay = 60;
if(PremiumPlayerBuffer != 0){
FreeAccountAdmissionDelay = (PlayersOnline - (MaxPlayers - PremiumPlayerBuffer * 2));
FreeAccountAdmissionDelay = (FreeAccountAdmissionDelay * 30) / PremiumPlayerBuffer;
if(FreeAccountAdmissionDelay < 0){
FreeAccountAdmissionDelay = 0;
}
}
uint32 FreeAccountAdmissionRound = RoundNr + (uint32)FreeAccountAdmissionDelay;
if(EarliestFreeAccountAdmissionRound < FreeAccountAdmissionRound){
EarliestFreeAccountAdmissionRound = FreeAccountAdmissionRound;
}
TConnection *Connection = GetFirstConnection();
while(Connection != NULL){
if(Connection->Live()){
Connection->EmergencyPing();
}
Connection = GetNextConnection();
}
}
}
}
// Connection Output
// =============================================================================
bool WriteToSocket(TConnection *Connection, uint8 *Buffer, int Size){
// IMPORTANT(fusion): The caller must ensure `Buffer` have two extra bytes
// at the beginning and enough room at the end to properly add padding for
// XTEA encryption when needed. `Size` refers to the payload size which
// starts after the first two extra bytes. See note in `SendData`.
while((Size % 8) != 0){
Buffer[Size + 2] = rand_r(&Connection->RandomSeed);
Size += 1;
}
for(int i = 0; i < Size; i += 8){
Connection->SymmetricKey.encrypt(&Buffer[i + 2]);
}
TWriteBuffer WriteBuffer(Buffer, 2);
WriteBuffer.writeWord((uint16)Size);
int Attempts = 50;
int BytesToWrite = Size + 2;
uint8 *WritePtr = Buffer;
while(BytesToWrite > 0){
int ret = (int)write(Connection->GetSocket(), WritePtr, BytesToWrite);
if(ret > 0){
BytesToWrite -= ret;
WritePtr += ret;
}else if(ret == 0){
// TODO(fusion): Can this even happen without an error?
error("WriteToSocket: Fehler %d beim Senden an Socket %d.\n",
errno, Connection->GetSocket());
return false;
}else if(errno != EINTR){
if(errno != EAGAIN || Attempts <= 0){
if(errno == ECONNRESET || errno == EPIPE || errno == EAGAIN){
Log("game", "Verbindung an Socket %d zusammengebrochen.\n",
Connection->GetSocket());
}else{
error("WriteToSocket: Fehler %d beim Senden an Socket %d.\n",
errno, Connection->GetSocket());
}
return false;
}
DelayThread(0, 100000);
Attempts -= 1;
}
}
NetLoad(PACKET_AVERAGE_SIZE_OVERHEAD + Size + 2, true);
return true;
}
bool SendLoginMessage(TConnection *Connection, int Type, const char *Message, int WaitingTime){
// TODO(fusion): Why do we return true on invalid parameters?
// TODO(fusion):
// LOGIN_MESSAGE_ERROR = 20
// LOGIN_MESSAGE_? = 21
// LOGIN_MESSAGE_WAITING_LIST = 22
if(Type != 20 && Type != 21 && Type != 22){
error("SendLoginMessage: Ungültiger Meldungstyp %d.\n", Type);
return true;
}
if(Message == NULL){
error("SendLoginMessage: Message ist NULL.\n");
return true;
}
if(Type == 22 && (WaitingTime < 0 || WaitingTime > UINT8_MAX)){
error("SendLoginMessage: Ungültige Wartezeit %d.\n", WaitingTime);
return true;
}
if(strlen(Message) > 290){
error("SendLoginMessage: Botschaft zu lang (%s).\n", Message);
return true;
}
// IMPORTANT(fusion): This is doing the same thing as `SendData` but in a
// smaller scale and building the packet directly instead of using the
// connection's write buffer.
uint8 Data[302]; // 2 + 300
TWriteBuffer WriteBuffer(Data + 2, sizeof(Data) - 2);
WriteBuffer.writeWord(0);
WriteBuffer.writeByte((uint8)Type);
WriteBuffer.writeString(Message);
if(Type == 22){
WriteBuffer.writeByte(WaitingTime);
}
int Size = WriteBuffer.Position;
WriteBuffer.Position = 0;
WriteBuffer.writeWord((uint16)(Size - 2));
return WriteToSocket(Connection, Data, Size);
}
bool SendData(TConnection *Connection){
if(Connection == NULL){
error("SendData: Verbindung ist NULL.\n");
return false;
}
//
// IMPORTANT(fusion): The final packet will have this layout:
// PLAIN:
// 0 .. 2 => Encrypted Size
// ENCRYPTED:
// 2 .. 4 => Data Size
// 4 .. => Data + Padding
//
// The ENCRYPTED size needs to be a multiple of 8 for XTEA encryption and
// `WriteToSocket` will add padding to ensure it is. This also requires us
// to ensure the passed buffer has enough room for it, so we don't write out
// of bounds.
//
int DataSize = Connection->NextToCommit - Connection->NextToSend;
int EncryptedSize = (DataSize + 2);
int EncryptedSizeAligned = (EncryptedSize + 7) & ~7;
int PacketSize = EncryptedSizeAligned + 2;
// TODO(fusion): The maximum size of a packet depends on the size of
// `Connection->OutData` and I don't think we'd have a problem with
// having a constant size buffer on the stack here although with such
// a small stack size (64KB with our own stacks) it could become a
// problem.
uint8 *Buffer = (uint8*)alloca(PacketSize);
TWriteBuffer WriteBuffer(Buffer, PacketSize);
WriteBuffer.writeWord(0);
WriteBuffer.writeWord((uint16)DataSize);
// NOTE(fusion): `Connection->OutData` is a ring buffer so we need to check
// if the data we're currently sending is wrapping around, in which case we'd
// need to copy two separate regions instead of a single contiguous one.
constexpr int OutDataSize = sizeof(Connection->OutData);
int DataStart = Connection->NextToSend % OutDataSize;
int DataEnd = DataStart + DataSize;
if(DataEnd < OutDataSize){
WriteBuffer.writeBytes(&Connection->OutData[DataStart], DataSize);
}else{
WriteBuffer.writeBytes(&Connection->OutData[DataStart], OutDataSize - DataStart);
WriteBuffer.writeBytes(&Connection->OutData[0], DataEnd - OutDataSize);
}
bool Result = WriteToSocket(Connection, Buffer, DataSize);
if(Result){
Connection->NextToSend += DataSize;
}
return Result;
}
bool SendData(TConnection *Connection, const uint8 *Data, int Size){
if(Connection == NULL){
error("SendData: Connection ist NULL.\n");
return false;
}
// TODO(fusion): Why are we returning true for invalid parameters?
if(Data == NULL){
error("SendData: Data ist NULL.\n");
return true;
}
// TODO(fusion): Why do we leave extra two bytes unassigned at the beginning?
// `SendData` should already take care of building the packet properly so this
// is something else or a bug, if this function is even used.
memcpy(&Connection->OutData[2], Data, Size);
Connection->NextToSend = 0;
Connection->NextToCommit = Size + 2;
return SendData(Connection);
}
// Waiting List
// =============================================================================
bool GetWaitinglistEntry(const char *Name, int *NextTry, bool *FreeAccount, bool *Newbie){
bool Result = false;
CommunicationThreadMutex.down();
TWaitinglistEntry *Entry = WaitinglistHead;
while(Entry != NULL){
if(stricmp(Entry->Name, Name) == 0){
break;
}
Entry = Entry->Next;
}
if(Entry != NULL){
*NextTry = Entry->NextTry;
*FreeAccount = Entry->FreeAccount;
*Newbie = Entry->Newbie;
Result = true;
}
CommunicationThreadMutex.up();
return Result;
}
void InsertWaitinglistEntry(const char *Name, uint32 NextTry, bool FreeAccount, bool Newbie){
bool NewEntry = false;
CommunicationThreadMutex.down();
TWaitinglistEntry *Prev = NULL;
TWaitinglistEntry *Entry = WaitinglistHead;
while(Entry != NULL){
if(stricmp(Entry->Name, Name) == 0){
break;
}
Prev = Entry;
Entry = Entry->Next;
}
if(Entry == NULL){
Entry = Waitinglist.getFreeItem();
Entry->Next = NULL;
strcpy(Entry->Name, Name);
Entry->NextTry = NextTry;
Entry->FreeAccount = FreeAccount;
Entry->Newbie = Newbie;
Entry->Sleeping = false;
if(Prev != NULL){
Prev->Next = Entry;
}else{
WaitinglistHead = Entry;
}
NewEntry = true;
}else{
Entry->NextTry = NextTry;
Entry->FreeAccount = FreeAccount;
Entry->Newbie = Newbie;
}
CommunicationThreadMutex.up();
if(NewEntry){
Log("queue", "Füge %s in die Warteschlange ein.\n", Name);
}
}
void DeleteWaitinglistEntry(const char *Name){
CommunicationThreadMutex.down();
TWaitinglistEntry *Prev = NULL;
TWaitinglistEntry *Entry = WaitinglistHead;
while(Entry != NULL){
if(stricmp(Entry->Name, Name) == 0){
break;
}
Prev = Entry;
Entry = Entry->Next;
}
if(Entry != NULL){
if(Prev != NULL){
Prev->Next = Entry->Next;
}else{
WaitinglistHead = Entry->Next;
}
Waitinglist.putFreeItem(Entry);
}
CommunicationThreadMutex.up();
}
int GetWaitinglistPosition(const char *Name, bool FreeAccount, bool Newbie){
int FreeNewbies = 0;
int FreeVeterans = 0;
int PremiumNewbies = 0;
int PremiumVeterans = 0;
CommunicationThreadMutex.down();
// NOTE(fusion): Remove inactive entries from the start of the list.
while(WaitinglistHead != NULL && RoundNr > (WaitinglistHead->NextTry + 60)){
TWaitinglistEntry *Next = WaitinglistHead->Next;
Waitinglist.putFreeItem(WaitinglistHead);
WaitinglistHead = Next;
}
// NOTE(fusion): Count players up until we find the player's entry or reach
// the end of the queue.
TWaitinglistEntry *Entry = WaitinglistHead;
while(Entry != NULL){
if(stricmp(Entry->Name, Name) == 0){
break;
}
if(!Entry->Sleeping){
if(RoundNr > (Entry->NextTry + 5)){
Entry->Sleeping = true;
}else if(Entry->FreeAccount){
if(Entry->Newbie){
FreeNewbies += 1;
}else{
FreeVeterans += 1;
}
}else{
if(Entry->Newbie){
PremiumNewbies += 1;
}else{
PremiumVeterans += 1;
}
}
}
Entry = Entry->Next;
}
CommunicationThreadMutex.up();
int Result = 1;
if(FreeAccount){
Result += PremiumVeterans + FreeVeterans;
if(Newbie){
Result += PremiumNewbies + FreeNewbies;
}else if(GetNewbiesOnline() < (MaxNewbies - PremiumNewbieBuffer)){
Result += FreeNewbies;
}
}else{
Result += PremiumVeterans;
if(Newbie || GetNewbiesOnline() < MaxNewbies){
Result += PremiumNewbies;
}
}
return Result;
}
int CheckWaitingTime(const char *Name, TConnection *Connection, bool FreeAccount, bool Newbie){
int WaitingTime = 0;
const char *Reason = NULL;
int Position = GetWaitinglistPosition(Name, FreeAccount, Newbie);
int PlayersOnline = GetPlayersOnline();
int NewbiesOnline = GetNewbiesOnline();
if((PlayersOnline + Position) > GetOrderBufferSpace()){
print(3, "Order-Puffer ist fast voll.\n");
Reason = "The server is overloaded.";
WaitingTime = (Position / 2) + 10;
}else if(FreeAccount){
if(EarliestFreeAccountAdmissionRound > RoundNr){
print(3, "Keine FreeAccounts zugelassen nach MassKick.\n");
Reason = "The server is overloaded.\n"
"Only players with premium accounts\n"
"are admitted at the moment.";
WaitingTime = (int)(EarliestFreeAccountAdmissionRound - RoundNr);
WaitingTime += Position / 2;
}else if((PlayersOnline + Position) > (MaxPlayers - PremiumPlayerBuffer)){
print(3, "Kein Platz mehr für FreeAccounts.\n");
Reason = "Too many players online.\n"
"Only players with premium accounts\n"
"are admitted at the moment.";
WaitingTime = Position / 2 + 5;
}else if(Newbie && (NewbiesOnline + Position) > (MaxNewbies - PremiumNewbieBuffer)){
print(3, "Kein Platz mehr für Newbies mit FreeAccount.\n");
Reason = "There are too many players online\n"
"on the beginners' island, Rookgaard.\n"
"Only players with premium accounts\n"
"are admitted at the moment.";
WaitingTime = Position / 2 + 5;
}
}else{
if((PlayersOnline + Position) > MaxPlayers){
print(3, "Zu viele Spieler online.\n");
Reason = "There are too many players online.";
WaitingTime = Position / 2 + 3;
}else if(Newbie && (NewbiesOnline + Position) > MaxNewbies){
print(3, "Kein Platz mehr für Newbies.\n");
Reason = "There are too many players online\n"
"on the beginners' island, Rookgaard.";
WaitingTime = Position / 2 + 3;
}
}
if(WaitingTime > 240){
WaitingTime = 240;
}
if(WaitingTime > 0){
char Message[250];
snprintf(Message, sizeof(Message),
"%s\n\nYou are at place %d on the waiting list.",
Reason, Position);
SendLoginMessage(Connection, 22, Message, WaitingTime);
}
return WaitingTime;
}
// Connection Input
// =============================================================================
int ReadFromSocket(TConnection *Connection, uint8 *Buffer, int Size){
int Attempts = 50;
int BytesToRead = Size;
uint8 *ReadPtr = Buffer;
while(BytesToRead > 0){
int BytesRead = (int)read(Connection->GetSocket(), ReadPtr, BytesToRead);
if(BytesRead > 0){
BytesToRead -= BytesRead;
ReadPtr += BytesRead;
}else if(BytesRead == 0){
// NOTE(fusion): TCP FIN with no more data to read.
break;
}else if(errno != EINTR){
if(errno != EAGAIN || BytesToRead == Size || Attempts <= 0){
return -1;
}
DelayThread(0, 100000);
Attempts -= 1;
}
}
return Size - BytesToRead;
}
bool DrainSocket(TConnection *Connection, int Size){
uint8 DiscardBuffer[KB(2)];
while(Size > 0){
int BytesToRead = std::min<int>(Size, sizeof(DiscardBuffer));
int BytesRead = ReadFromSocket(Connection, DiscardBuffer, BytesToRead);
if(BytesRead <= 0){
return false;
}
Size -= BytesRead;
NetLoad(PACKET_AVERAGE_SIZE_OVERHEAD + BytesRead, false);
}
return true;
}
bool CallGameThread(TConnection *Connection){
if(GameRunning()){
Connection->WaitingForACK = true;
if(kill(GetGameThreadPID(), SIGUSR1) != 0){
error("CallGameThread: Can't send SIGUSR1 to pid %d\n", GetGameThreadPID());
SendLoginMessage(Connection, 20,
"The server is not online.\nPlease try again later.", -1);
return false;
}
}
return true;
}
bool CheckConnection(TConnection *Connection){
// TODO(fusion): Check if there is no input data?
struct pollfd pollfd = {};
pollfd.fd = Connection->GetSocket();
pollfd.events = POLLIN;
return poll(&pollfd, 1, 0) >= 0
&& (pollfd.revents & POLLIN) == 0;
}
// NOTE(fusion): `PlayerName` is an input and output parameter. It will contain
// the correct player name with upper and lower case letters if the player is
// actually logged in.
TPlayerData *PerformRegistration(TConnection *Connection, char *PlayerName,
uint32 AccountID, const char *PlayerPassword, bool GamemasterClient){
TQueryManagerPoolConnection QueryManagerConnection(&QueryManagerConnectionPool);
if(!QueryManagerConnection){
error("PerformRegistration: Kann Verbindung zum Query-Manager nicht herstellen.\n");
SendLoginMessage(Connection, 20, "Internal error, closing connection.", -1);
return NULL;
}
if(!CheckConnection(Connection)){
return NULL;
}
// TODO(fusion): What a disaster. The size of these arrays are are hardcoded
// and should be declared constants somewhere.
uint32 CharacterID;
int Sex;
char Guild[31]; // MAX_NAME_LENGTH ?
char Rank[31]; // MAX_NAME_LENGTH ?
char Title[31]; // MAX_NAME_LENGTH ?
int NumberOfBuddies;
uint32 BuddyIDs[100]; // MAX_BUDDIES ?
char BuddyNames[100][30]; // MAX_BUDDIES, MAX_NAME_LENGTH ?
uint8 Rights[12]; // MAX_RIGHT_BYTES ?
bool PremiumAccountActivated;
int Status = QueryManagerConnection->loginGame(AccountID, PlayerName,
PlayerPassword, Connection->GetIPAddress(), PrivateWorld, false,
GamemasterClient, &CharacterID, &Sex, Guild, Rank, Title,
&NumberOfBuddies, BuddyIDs, BuddyNames, Rights,
&PremiumAccountActivated);
switch(Status){
case 0:{
// NOTE(fusion): Login successful.
break;
}
case 1:{
print(3, "Spieler existiert nicht.\n");
SendLoginMessage(Connection, 20,
"Character doesn't exist.\n"
"Create a new character on the Tibia website\n"
"at \"www.tibia.com\".", -1);
return NULL;
}
case 2:{
print(3, "Spieler wurde gelöscht.\n");
SendLoginMessage(Connection, 20,
"Character doesn't exist.\n"
"Create a new character on the Tibia website.", -1);
return NULL;
}
case 3:{
print(3, "Spieler lebt nicht auf dieser Welt.\n");
SendLoginMessage(Connection, 20,
"Character doesn't live on this world.\n"
"Please login on the right world.", -1);
return NULL;
}
case 4:{
print(3, "Spieler ist nicht eingeladen.\n");
SendLoginMessage(Connection, 20,
"This world is private and you have not been invited to play on it.", -1);
return NULL;
}
case 6:{
Log("game", "Falsches Paßwort für Spieler %s; Login von %s.\n",
PlayerName, Connection->GetIPAddress());
SendLoginMessage(Connection, 20,
"Accountnumber or password is not correct.", -1);
return NULL;
}
case 7:{
Log("game", "Spieler %s blockiert; Login von %s.\n",
PlayerName, Connection->GetIPAddress());
SendLoginMessage(Connection, 20,
"Account disabled for five minutes. Please wait.", -1);
return NULL;
}
case 8:{
Log("game", "Account von Spieler %s wurde gelöscht.\n", PlayerName);
SendLoginMessage(Connection, 20,
"Accountnumber or password is not correct.", -1);
return NULL;
}
case 9:{
Log("game", "IP-Adresse %s für Spieler %s blockiert.\n",
Connection->GetIPAddress(), PlayerName);
SendLoginMessage(Connection, 20,
"IP address blocked for 30 minutes. Please wait.", -1);
return NULL;
}
case 10:{
print(3, "Account ist verbannt.\n");
SendLoginMessage(Connection, 20,
"Your account is banished.", -1);
return NULL;
}
case 11:{
print(3, "Character muss umbenannt werden.\n");
SendLoginMessage(Connection, 20,
"Your character is banished because of his/her name.", -1);
return NULL;
}
case 12:{
print(3, "IP-Adresse ist gesperrt.\n");
SendLoginMessage(Connection, 20,
"Your IP address is banished.", -1);
return NULL;
}
case 13:{
print(3, "Schon andere Charaktere desselben Accounts eingeloggt.\n");
SendLoginMessage(Connection, 20,
"You may only login with one character\n"
"of your account at the same time.", -1);
return NULL;
}
case 14:{
print(3, "Login mit Gamemaster-Client auf Nicht-Gamemaster-Account.\n");
SendLoginMessage(Connection, 20,
"You may only login with a Gamemaster account.", -1);
return NULL;
}
case 15:{
print(3, "Falsche Accountnummer %u für %s.\n", AccountID, PlayerName);
SendLoginMessage(Connection, 20,
"Login failed due to corrupt data.", -1);
return NULL;
}
case -1:{
SendLoginMessage(Connection, 20, "Internal error, closing connection.", -1);
return NULL;
}
default:{
error("PerformRegistration: Unbekannter Rückgabewert vom QueryManager.\n");
SendLoginMessage(Connection, 20, "Internal error, closing connection.", -1);
return NULL;
}
}
// TODO(fusion): Again?
if(!CheckConnection(Connection)){
QueryManagerConnection->decrementIsOnline(CharacterID);
return NULL;
}
if(AccountID == 0){
error("PerformRegistration: Spieler %s wurde noch keinem Account zugewiesen.\n", PlayerName);
SendLoginMessage(Connection, 20,
"Character is not assigned to an account.\n"
"Perform this on the Tibia website\n"
"at \"www.tibia.com\".", -1);
return NULL;
}
// TODO(fusion): We were also adding a null terminator to `PlayerName` here
// for whatever reason. I assume it is a compiler artifact because we already
// use it in the condition block just above so...
// PlayerName[29] = 0;
if(PremiumAccountActivated){
SendLoginMessage(Connection, 21,
"Your Premium Account is now activated.\n"
"Have a lot of fun in Tibia.", -1);
}
Log("game", "Spieler %s loggt ein an Socket %d von %s.\n",
PlayerName, Connection->GetSocket(), Connection->GetIPAddress());
TPlayerData *PlayerData = AssignPlayerPoolSlot(CharacterID, true);
if(PlayerData == NULL){
error("PerformRegistration: Kann keinen Slot für Spielerdaten zuweisen.\n");
QueryManagerConnection->decrementIsOnline(CharacterID);
SendLoginMessage(Connection, 20,
"There are too many players online.\n"
"Please try again later.", -1);
return NULL;
}
bool Locked = PlayerData->Locked == getpid();
// TODO(fusion): How come this isn't a race condition? Perhaps these are
// constant and can only change when loaded from the database?
if(Locked || PlayerData->AccountID == 0){
PlayerData->AccountID = AccountID;
PlayerData->Sex = Sex;
strcpy(PlayerData->Name, PlayerName);
memcpy(PlayerData->Rights, Rights, sizeof(Rights));
strcpy(PlayerData->Guild, Guild);
strcpy(PlayerData->Rank, Rank);
strcpy(PlayerData->Title, Title);
}
if(Locked && PlayerData->Buddies == 0){
PlayerData->Buddies = NumberOfBuddies;
for(int i = 0; i < NumberOfBuddies; i += 1){
PlayerData->Buddy[i] = BuddyIDs[i];
strcpy(PlayerData->BuddyName[i], BuddyNames[i]);
}
}
return PlayerData;
}
bool HandleLogin(TConnection *Connection){
// TODO(fusion): Exception handling keeps getting crazier.
TReadBuffer InputBuffer(Connection->InData, Connection->InDataSize);
try{
uint8 Command = InputBuffer.readByte();
if(Command != 10){
print(3, "Ungültiges Init-Kommando %d.\n", Command);
return false;
}
}catch(const char *str){
error("HandleLogin: Fehler beim Auslesen des Kommandos (%s).\n", str);
return false;
}
int TerminalType;
int TerminalVersion;
bool GamemasterClient;
uint32 AccountID;
char PlayerName[30];
char PlayerPassword[30];
try{
uint8 AssymmetricData[128];
InputBuffer.readBytes(AssymmetricData, 128);
RSAMutex.down();
try{
PrivateKey.decrypt(AssymmetricData);
}catch(const char *str){
RSAMutex.up();
error("HandleLogin: Fehler beim Entschlüsseln (%s).\n", str);
SendLoginMessage(Connection, 20,
"Login failed due to corrupt data.",-1);
return false;
}
RSAMutex.up();
TReadBuffer ReadBuffer(AssymmetricData, 128);
ReadBuffer.readByte();
Connection->SymmetricKey.init(&ReadBuffer);
TerminalType = (int)ReadBuffer.readWord();
TerminalVersion = (int)ReadBuffer.readWord();
GamemasterClient = ReadBuffer.readByte() != 0;
AccountID = ReadBuffer.readQuad();
ReadBuffer.readString(PlayerName, sizeof(PlayerName));
ReadBuffer.readString(PlayerPassword, sizeof(PlayerPassword));
}catch(const char *str){
print(3, "Fehler beim Auslesen der Login-Daten (%s).\n", str);
SendLoginMessage(Connection, 20,
"Login failed due to corrupt data.",-1);
return false;
}
if(PlayerName[0] == 0){
SendLoginMessage(Connection, 20,
"You must enter a character name.", -1);
return false;
}
if(TerminalType < 0 || TerminalType >= NARRAY(TERMINALVERSION)
|| TERMINALVERSION[TerminalType] != TerminalVersion){
SendLoginMessage(Connection, 20,
"Your terminal version is too old.\n"
"Please get a new version at\n"
"http://www.tibia.com.", -1);
return false;
}
if(!GameRunning()){
SendLoginMessage(Connection, 20,
"The server is not online.\n"
"Please try again later.", -1);
return false;
}
if(GameStarting()){
SendLoginMessage(Connection, 20,
"The game is just starting.\n"
"Please try again later.", -1);
return false;
}
if(GameEnding()){
SendLoginMessage(Connection, 20,
"The game is just going down.\n"
"Please try again later.", -1);
return false;
}
// NOTE(fusion): Check waitlist entry.
bool WasInWaitingList = false;
while(true){
uint32 NextTry;
bool FreeAccount;
bool Newbie;
if(!GetWaitinglistEntry(PlayerName, &NextTry, &FreeAccount, &Newbie)){
print(3, "Spieler nicht auf Warteliste.\n");
break;
}
print(3, "Spieler auf Warteliste.\n");
if(NextTry > RoundNr){
int WaitingTime = (int)(NextTry - RoundNr);
Log("queue", "%s meldet sich %d Sekunden zu früh an.\n",
PlayerName, WaitingTime);
SendLoginMessage(Connection, 22,
"It's not your turn yet.", WaitingTime);
return false;
}
if(RoundNr > (NextTry + 60)){
Log("queue", "%s meldet sich %d Sekunden zu spät an.\n",
PlayerName, (RoundNr - NextTry));
DeleteWaitinglistEntry(PlayerName);
continue;
}
int WaitingTime = CheckWaitingTime(PlayerName, Connection, FreeAccount, Newbie);
if(WaitingTime > 0){
NextTry = RoundNr + (uint32)WaitingTime;
InsertWaitinglistEntry(PlayerName, NextTry, FreeAccount, Newbie);
return false;
}
DeleteWaitinglistEntry(PlayerName);
WasInWaitingList = true;
break;
}
TPlayerData *Slot = PerformRegistration(Connection,
PlayerName, AccountID, PlayerPassword, GamemasterClient);
if(Slot == NULL){
return false;
}
bool SlotLocked = Slot->Locked == getpid();
// NOTE(fusion): These checks would have been already made if the player was
// in the waiting list so they'd be redundant.
if(!WasInWaitingList){
bool BlockLogin = false;
bool FreeAccount = !CheckBit(Slot->Rights, PREMIUM_ACCOUNT);
bool Newbie = Slot->Profession == PROFESSION_NONE
&& !CheckBit(Slot->Rights, NO_LOGOUT_BLOCK);
bool PremiumOnly = (MaxPlayers == PremiumPlayerBuffer)
|| (Newbie && MaxNewbies == PremiumNewbieBuffer);
if(!BlockLogin && FreeAccount && PremiumOnly){
SendLoginMessage(Connection, 20,
"Only players with premium accounts\n"
"are allowed to enter this world.", -1);
BlockLogin = true;
}
if(!BlockLogin && !IsPlayerOnline(PlayerName)){
int WaitingTime = CheckWaitingTime(PlayerName, Connection, FreeAccount, Newbie);
if(WaitingTime > 0){
uint32 NextTry = RoundNr + (uint32)WaitingTime;
InsertWaitinglistEntry(PlayerName, NextTry, FreeAccount, Newbie);
BlockLogin = true;
}
}
if(BlockLogin){
// TODO(fusion): This is probably an inlined function.
TQueryManagerPoolConnection QueryManagerConnection(&QueryManagerConnectionPool);
if(QueryManagerConnection){
QueryManagerConnection->decrementIsOnline(Slot->CharacterID);
}else{
error("HandleLogin: Kann Verbindung zum Query-Manager nicht herstellen.\n");
}
if(SlotLocked){
ReleasePlayerPoolSlot(Slot);
}else{
DecreasePlayerPoolSlotSticky(Slot);
}
return false;
}
}
if(SlotLocked){
IncreasePlayerPoolSlotSticky(Slot);
ReleasePlayerPoolSlot(Slot);
}
// NOTE(fusion): Rewrite packet in a different format, ready for the main
// thread to interpret.
TWriteBuffer WriteBuffer(Connection->InData + 2,
sizeof(Connection->InData) - 2);
try{
WriteBuffer.writeByte(11);
WriteBuffer.writeWord((int)TerminalType);
WriteBuffer.writeWord((int)TerminalVersion);
WriteBuffer.writeQuad(Slot->CharacterID);
}catch(const char *str){
error("HandleLogin: Fehler beim Zusammenbauen des Login-Pakets (%s).\n", str);
SendLoginMessage(Connection, 20,
"Internal error, closing connection.",-1);
return false;
}
Connection->NextToSend = 0;
Connection->NextToCommit = 0;
Connection->InDataSize = WriteBuffer.Position;
Connection->NextToWrite = 0;
Connection->Login();
return CallGameThread(Connection);
}
bool ReceiveCommand(TConnection *Connection){
// IMPORTANT(fusion): The return value of this function is used to determine
// whether the connection should be closed. Returning true will maintain it
// open. It is a weird convention but w/e.
if(Connection == NULL){
error("ReceiveCommand: Connection ist NULL.\n");
return false;
}
while(!Connection->WaitingForACK){
uint8 Help[2];
int BytesRead = ReadFromSocket(Connection, Help, 2);
if(BytesRead == 0){
return false;
}else if(BytesRead < 0){
return true;
}else if(BytesRead == 1){
NetLoad(PACKET_AVERAGE_SIZE_OVERHEAD + 1, false);
print(3, "Zu wenig Daten an Socket %d.\n", BytesRead);
return true;
}
// TODO(fusion): Size is encoded as a little endian uint16. We should
// have a few helper functions to assist with buffer reading.
int Size = ((uint16)Help[0] | ((uint16)Help[1] << 8));
if(Size == 0 || Size > (int)sizeof(Connection->InData)){
// TODO(fusion): We should definitely close the connection here.
// Nevertheless, the original handling of this edge case was just
// terrible, reading from the socket recklessly until at least `Size`
// bytes were discarded. I replaced it with a small helper function
// function `DrainSocket`.
print(3, "Paket an Socket %d zu groß oder leer, wird verworfen (%d Bytes)\n",
Connection->GetSocket(), Size);
return DrainSocket(Connection, Size);
}
BytesRead = ReadFromSocket(Connection, &Connection->InData[0], Size);
if(BytesRead < 0){
// NOTE(fusion): It doesn't make sense to call `SendLoginMessage` before
// the key exchange has completed, which happens after login.
if(Connection->State != CONNECTION_CONNECTED){
SendLoginMessage(Connection, 20,
"Internal error, closing connection.", -1);
}
return false;
}
NetLoad(PACKET_AVERAGE_SIZE_OVERHEAD + BytesRead, false);
// NOTE(fusion): It doesn't make sense to continue if we didn't receive
// the whole packet. We're already using TCP which doesn't drop data so
// it would only compound into more errors.
if(BytesRead != Size){
return false;
}
if(Connection->State == CONNECTION_CONNECTED){
alarm(0); // TODO(fusion): Not sure why.
Connection->InDataSize = Size;
if(!HandleLogin(Connection)){
return false;
}
}else{
// NOTE(fusion): It doesn't make sense to continue if the client didn't
// correctly size its packet.
if((Size % 8) != 0){
print(3, "Ungültige Paketlänge %d für verschlüsseltes Paket von %s.\n",
Size, Connection->GetName());
return false;
}
for(int i = 0; i < Size; i += 8){
Connection->SymmetricKey.decrypt(&Connection->InData[i]);
}
// NOTE(fusion): It doesn't make sense to continue if the client didn't
// correctly size its payload.
int PlainSize = ((uint16)Connection->InData[0])
| ((uint16)Connection->InData[1] << 8);
if(PlainSize == 0 || (PlainSize + 2) > Size){
print(3, "Nutzdaten (%d Bytes) von Paket an Socket %d zu groß oder leer.\n",
PlainSize, Connection->GetSocket());
return false;
}
Connection->InDataSize = PlainSize;
if(!CallGameThread(Connection)){
return false;
}
}
}
Connection->SigIOPending = true;
return true;
}
|