-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathNetwork.pas
2762 lines (2420 loc) · 67.1 KB
/
Network.pas
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
unit Network;
{$I HLDS.inc}
interface
uses SysUtils, {$IFDEF MSWINDOWS} Windows, Winsock, {$ELSE} Libc, KernelIoctl, {$ENDIF} Default, SDK;
function NET_AdrToString(const A: TNetAdr; out Buf; L: UInt): PLChar; overload;
function NET_BaseAdrToString(const A: TNetAdr; out Buf; L: UInt): PLChar;
function NET_CompareBaseAdr(const A1, A2: TNetAdr): Boolean;
function NET_CompareAdr(const A1, A2: TNetAdr): Boolean;
function NET_StringToAdr(S: PLChar; out A: TNetAdr): Boolean;
function NET_StringToSockaddr(Name: PLChar; out S: TSockAddr): Boolean;
function NET_CompareClassBAdr(const A1, A2: TNetAdr): Boolean;
function NET_IsReservedAdr(const A: TNetAdr): Boolean;
function NET_IsLocalAddress(const A: TNetAdr): Boolean;
procedure NET_Config(EnableNetworking: Boolean);
procedure NET_SendPacket(Source: TNetSrc; Size: UInt; Buffer: Pointer; const Dest: TNetAdr);
procedure NET_ThreadLock;
procedure NET_ThreadUnlock;
function NET_AllocMsg(Size: UInt): PNetQueue;
function NET_GetPacket(Source: TNetSrc): Boolean;
procedure NET_ClearLagData(Client, Server: Boolean);
procedure NET_Init;
procedure NET_Shutdown;
procedure Netchan_OutOfBandPrint(Source: TNetSrc; const Addr: TNetAdr; S: PLChar); overload;
procedure Netchan_OutOfBandPrint(Source: TNetSrc; const Addr: TNetAdr; const S: array of const); overload;
// netchan
procedure Netchan_FragSend(var C: TNetchan);
procedure Netchan_AddBufferToList(var Base: PFragBuf; P: PFragBuf);
procedure Netchan_Clear(var C: TNetchan);
procedure Netchan_CreateFragments(var C: TNetchan; var SB: TSizeBuf);
procedure Netchan_CreateFileFragmentsFromBuffer(var C: TNetchan; Name: PLChar; Buffer: Pointer; Size: UInt);
function Netchan_CreateFileFragments(var C: TNetchan; Name: PLChar): Boolean;
procedure Netchan_FlushIncoming(var C: TNetchan; Stream: TNetStream);
procedure Netchan_Setup(Source: TNetSrc; var C: TNetchan; const Addr: TNetAdr; ClientID: Int; ClientPtr: PClient; Func: TFragmentSizeFunc);
function Netchan_Process(var C: TNetchan): Boolean;
procedure Netchan_Transmit(var C: TNetchan; Size: UInt; Buffer: Pointer);
function Netchan_IncomingReady(const C: TNetchan): Boolean;
function Netchan_CopyNormalFragments(var C: TNetchan): Boolean;
function Netchan_CopyFileFragments(var C: TNetchan): Boolean;
function Netchan_CanPacket(var C: TNetchan): Boolean;
procedure Netchan_Init;
var
InMessage, NetMessage: TSizeBuf;
InFrom, NetFrom, LocalIP: TNetAdr;
NoIP: Boolean = False;
clockwindow: TCVar = (Name: 'clockwindow'; Data: '0.5');
NetDrop: UInt = 0; // amount of dropped incoming packets
implementation
uses BZip2, Common, Console, FileSys, Memory, MsgBuf, Host, HostCmds, Resource, SVClient, SVMain, SysArgs, SysMain;
const
IPTOS_LOWDELAY = 16;
SD_RECEIVE = 0;
SD_SEND = 1;
SD_BOTH = 2;
INADDR_NONE = -1;
var
OldConfig: Boolean = False;
FirstInit: Boolean = True;
NetInit: Boolean = False;
IPSockets: array[TNetSrc] of TSocket;
InMsgBuffer, NetMsgBuffer: array[1..MAX_NETBUFLEN] of Byte;
// cvars
net_address: TCVar = (Name: 'net_address'; Data: '');
ipname: TCVar = (Name: 'ip'; Data: 'localhost');
ip_hostport: TCVar = (Name: 'ip_hostport'; Data: '0');
hostport: TCVar = (Name: 'hostport'; Data: '0');
defport: TCVar = (Name: 'port'; Data: '27015');
fakelag: TCVar = (Name: 'fakelag'; Data: '0');
fakeloss: TCVar = (Name: 'fakeloss'; Data: '0');
// threading
UseThread: Boolean = False;
NetSleepForever: Boolean = True;
ThreadInit: Boolean = False;
ThreadCS: TCriticalSection;
ThreadHandle: UInt;
ThreadID: UInt32;
NormalQueue: PNetQueue = nil;
NetMessages: array[TNetSrc] of PNetQueue;
Loopbacks: array[TNetSrc] of TLoopBack;
LagData: array[TNetSrc] of TLagPacket;
FakeLagTime: Single = 0;
LastLagTime: Double = 0;
LossCount: array[TNetSrc] of UInt = (0, 0, 0);
SplitCtx: array[0..MAX_SPLIT_CTX - 1] of TSplitContext;
CurrentCtx: UInt = Low(SplitCtx);
// netchan stuff
net_showpackets: TCVar = (Name: 'net_showpackets'; Data: '0');
net_showdrop: TCVar = (Name: 'net_showdrop'; Data: '0');
net_chokeloop: TCVar = (Name: 'net_chokeloop'; Data: '0');
sv_filetransfercompression: TCVar = (Name: 'sv_filetransfercompression'; Data: '1');
sv_filetransfermaxsize: TCVar = (Name: 'sv_filetransfermaxsize'; Data: '20000000');
sv_filereceivemaxsize: TCVar = (Name: 'sv_filereceivemaxsize'; Data: '1000000');
sv_receivedecalsonly: TCVar = (Name: 'sv_receivedecalsonly'; Data: '1');
// 0 - disabled
// 1 - normal packets only
// 2 - files only
// 3 - packets & files
net_compress: TCVar = (Name: 'net_compress'; Data: '3');
function NET_LastError: Int;
begin
{$IFDEF MSWINDOWS}
Result := WSAGetLastError;
{$ELSE}
Result := errno; // h_errno
{$ENDIF}
end;
procedure NET_ThreadLock;
begin
if UseThread and ThreadInit then
Sys_EnterCS(ThreadCS);
end;
procedure NET_ThreadUnlock;
begin
if UseThread and ThreadInit then
Sys_LeaveCS(ThreadCS);
end;
function ntohs(I: UInt16): UInt16;
begin
Result := (I shl 8) or (I shr 8);
end;
function htons(I: UInt16): UInt16;
begin
Result := (I shl 8) or (I shr 8);
end;
procedure NetadrToSockadr(const A: TNetAdr; out S: TSockAddr);
begin
case A.AddrType of
NA_BROADCAST:
begin
S.sin_family := AF_INET;
S.sin_port := A.Port;
Int32(S.sin_addr.S_addr) := INADDR_BROADCAST;
MemSet(S.sin_zero, SizeOf(S.sin_zero), 0);
end;
NA_IP:
begin
S.sin_family := AF_INET;
S.sin_port := A.Port;
Int32(S.sin_addr.S_addr) := PInt32(@A.IP)^;
MemSet(S.sin_zero, SizeOf(S.sin_zero), 0);
end;
else
MemSet(S, SizeOf(S), 0);
end;
end;
procedure SockadrToNetadr(const S: TSockAddr; out A: TNetAdr);
begin
if S.sa_family = AF_INET then
begin
A.AddrType := NA_IP;
PInt32(@A.IP)^ := Int32(S.sin_addr.S_addr);
A.Port := S.sin_port;
end
else
MemSet(A, SizeOf(A), 0);
end;
function NET_CompareAdr(const A1, A2: TNetAdr): Boolean;
begin
if A1.AddrType <> A2.AddrType then
Result := False
else
case A1.AddrType of
NA_LOOPBACK: Result := True;
NA_IP: Result := (PUInt32(@A1.IP)^ = PUInt32(@A2.IP)^) and (A1.Port = A2.Port);
else Result := False;
end;
end;
function NET_CompareClassBAdr(const A1, A2: TNetAdr): Boolean;
begin
if A1.AddrType <> A2.AddrType then
Result := False
else
case A1.AddrType of
NA_LOOPBACK: Result := True;
NA_IP: Result := PUInt16(@A1.IP)^ = PUInt16(@A2.IP)^;
else Result := False;
end;
end;
function NET_IsReservedAdr(const A: TNetAdr): Boolean;
begin
case A.AddrType of
NA_LOOPBACK: Result := True;
NA_IP: Result := (A.IP[1] = 10) or (A.IP[1] = 127) or
((A.IP[1] = 172) and (A.IP[2] >= 16) and (A.IP[2] <= 31)) or
((A.IP[1] = 192) and (A.IP[2] = 168));
else Result := False;
end;
end;
function NET_CompareBaseAdr(const A1, A2: TNetAdr): Boolean;
begin
if A1.AddrType <> A2.AddrType then
Result := False
else
case A1.AddrType of
NA_LOOPBACK: Result := True;
NA_IP: Result := PUInt32(@A1.IP)^ = PUInt32(@A2.IP)^;
else Result := False;
end;
end;
function NET_AdrToString(const A: TNetAdr; out Buf; L: UInt): PLChar; overload;
var
I: Int;
S: PLChar;
AdrBuf: array[1..64] of LChar;
begin
if (@Buf = nil) or (L = 0) then
Result := nil
else
begin
case A.AddrType of
NA_LOOPBACK: StrLCopy(@Buf, 'loopback', L - 1);
NA_IP, NA_BROADCAST:
begin
S := @AdrBuf;
for I := 1 to 4 do
begin
S := IntToStrE(A.IP[I], S^, 4);
S^ := '.';
Inc(UInt(S));
end;
PLChar(UInt(S) - 1)^ := ':';
IntToStr(ntohs(A.Port), S^, 6);
StrLCopy(@Buf, @AdrBuf, L - 1);
end;
else StrLCopy(@Buf, '(bad address)', L - 1);
end;
Result := @Buf;
end;
end;
function NET_BaseAdrToString(const A: TNetAdr; out Buf; L: UInt): PLChar;
var
I: Int;
S: PLChar;
AdrBuf: array[1..64] of LChar;
begin
if (@Buf = nil) or (L = 0) then
Result := nil
else
begin
case A.AddrType of
NA_LOOPBACK: StrLCopy(@Buf, 'loopback', L - 1);
NA_IP, NA_BROADCAST:
begin
S := @AdrBuf;
for I := 1 to 4 do
begin
S := IntToStrE(A.IP[I], S^, 4);
S^ := '.';
Inc(UInt(S));
end;
PLChar(UInt(S) - 1)^ := #0;
StrLCopy(@Buf, @AdrBuf, L - 1);
end;
else StrLCopy(@Buf, '(bad address)', L - 1);
end;
Result := @Buf;
end;
end;
function NET_StringToSockaddr(Name: PLChar; out S: TSockAddr): Boolean;
var
Buf: array[1..1024] of LChar;
S2: PLChar;
I: Int32;
E: PHostEnt;
begin
Result := True;
S.sin_family := AF_INET;
MemSet(S.sin_zero, SizeOf(S.sin_zero), 0);
StrLCopy(@Buf, Name, SizeOf(Buf) - 1);
S2 := StrPos(@Buf, ':');
if S2 <> nil then
begin
S2^ := #0;
S.sin_port := StrToInt(PLChar(UInt(S2) + 1));
if S.sin_port <> 0 then
S.sin_port := htons(S.sin_port);
end
else
S.sin_port := 0;
I := inet_addr(@Buf);
if I = INADDR_NONE then
begin
E := gethostbyname(@Buf);
if (E = nil) or (E.h_addr_list = nil) or (E.h_addr_list^ = nil) then
begin
S.sin_addr.S_addr := 0;
Result := False;
end
else
I := PInt32(E.h_addr_list^)^;
end;
S.sin_addr.S_addr := I;
end;
function NET_StringToAdr(S: PLChar; out A: TNetAdr): Boolean;
var
SAdr: TSockAddr;
begin
if StrComp(S, 'localhost') = 0 then
begin
MemSet(A, SizeOf(A), 0);
A.AddrType := NA_LOOPBACK;
Result := True;
end
else
begin
Result := NET_StringToSockaddr(S, SAdr);
if Result then
SockadrToNetadr(SAdr, A);
end;
end;
function NET_IsLocalAddress(const A: TNetAdr): Boolean;
begin
Result := A.AddrType = NA_LOOPBACK;
end;
function NET_ErrorString(E: UInt): PLChar;
begin
{$IFDEF MSWINDOWS}
case E of
WSAEINTR: Result := 'WSAEINTR';
WSAEBADF: Result := 'WSAEBADF';
WSAEACCES: Result := 'WSAEACCES';
WSAEFAULT: Result := 'WSAEFAULT';
WSAEINVAL: Result := 'WSAEINVAL';
WSAEMFILE: Result := 'WSAEMFILE';
WSAEWOULDBLOCK: Result := 'WSAEWOULDBLOCK';
WSAEINPROGRESS: Result := 'WSAEINPROGRESS';
WSAEALREADY: Result := 'WSAEALREADY';
WSAENOTSOCK: Result := 'WSAENOTSOCK';
WSAEDESTADDRREQ: Result := 'WSAEDESTADDRREQ';
WSAEMSGSIZE: Result := 'WSAEMSGSIZE';
WSAEPROTOTYPE: Result := 'WSAEPROTOTYPE';
WSAENOPROTOOPT: Result := 'WSAENOPROTOOPT';
WSAEPROTONOSUPPORT: Result := 'WSAEPROTONOSUPPORT';
WSAESOCKTNOSUPPORT: Result := 'WSAESOCKTNOSUPPORT';
WSAEOPNOTSUPP: Result := 'WSAEOPNOTSUPP';
WSAEPFNOSUPPORT: Result := 'WSAEPFNOSUPPORT';
WSAEAFNOSUPPORT: Result := 'WSAEAFNOSUPPORT';
WSAEADDRINUSE: Result := 'WSAEADDRINUSE';
WSAEADDRNOTAVAIL: Result := 'WSAEADDRNOTAVAIL';
WSAENETDOWN: Result := 'WSAENETDOWN';
WSAENETUNREACH: Result := 'WSAENETUNREACH';
WSAENETRESET: Result := 'WSAENETRESET';
WSAECONNABORTED: Result := 'WSAECONNABORTED';
WSAECONNRESET: Result := 'WSAECONNRESET';
WSAENOBUFS: Result := 'WSAENOBUFS';
WSAEISCONN: Result := 'WSAEISCONN';
WSAENOTCONN: Result := 'WSAENOTCONN';
WSAESHUTDOWN: Result := 'WSAESHUTDOWN';
WSAETOOMANYREFS: Result := 'WSAETOOMANYREFS';
WSAETIMEDOUT: Result := 'WSAETIMEDOUT';
WSAECONNREFUSED: Result := 'WSAECONNREFUSED';
WSAELOOP: Result := 'WSAELOOP';
WSAENAMETOOLONG: Result := 'WSAENAMETOOLONG';
WSAEHOSTDOWN: Result := 'WSAEHOSTDOWN';
WSAEHOSTUNREACH: Result := 'WSAEHOSTUNREACH';
WSAENOTEMPTY: Result := 'WSAENOTEMPTY';
WSAEPROCLIM: Result := 'WSAEPROCLIM';
WSAEUSERS: Result := 'WSAEUSERS';
WSAEDQUOT: Result := 'WSAEDQUOT';
WSAESTALE: Result := 'WSAESTALE';
WSAEREMOTE: Result := 'WSAEREMOTE';
WSASYSNOTREADY: Result := 'WSASYSNOTREADY';
WSAVERNOTSUPPORTED: Result := 'WSAVERNOTSUPPORTED';
WSANOTINITIALISED: Result := 'WSANOTINITIALISED';
WSAEDISCON: Result := 'WSAEDISCON';
WSAHOST_NOT_FOUND: Result := 'WSAHOST_NOT_FOUND';
WSATRY_AGAIN: Result := 'WSATRY_AGAIN';
WSANO_RECOVERY: Result := 'WSANO_RECOVERY';
WSANO_DATA: Result := 'WSANO_DATA';
else
Result := 'NO ERROR';
end;
{$ELSE}
Result := strerror(E);
{$ENDIF}
end;
procedure NET_TransferRawData(var S: TSizeBuf; Data: Pointer; Size: UInt);
begin
if Size > S.MaxSize then
begin
DPrint('NET_TransferRawData: Buffer overflow.');
Size := S.MaxSize;
end;
S.CurrentSize := Size;
if Size > 0 then
Move(Data^, S.Data^, Size);
end;
function NET_GetLoopPacket(Source: TNetSrc; var A: TNetAdr; var SB: TSizeBuf): Boolean;
var
P: PLoopBack;
I: Int;
begin
if Source > NS_SERVER then
Result := False
else
begin
P := @Loopbacks[Source];
if P.Send - P.Get > MAX_LOOPBACK then
P.Get := P.Send - MAX_LOOPBACK;
if P.Get < P.Send then
begin
I := P.Get and (MAX_LOOPBACK - 1);
Inc(P.Get);
NET_TransferRawData(SB, @P.Msgs[I].Data, P.Msgs[I].Size);
MemSet(A, SizeOf(A), 0);
A.AddrType := NA_LOOPBACK;
Result := True;
end
else
Result := False;
end;
end;
procedure NET_SendLoopPacket(Source: TNetSrc; Size: UInt; Buffer: Pointer);
const
A: array[TNetSrc] of TNetSrc = (NS_SERVER, NS_CLIENT, NS_MULTICAST);
var
P: PLoopBack;
I: Int;
begin
NET_ThreadLock;
P := @Loopbacks[A[Source]];
I := P.Send and (MAX_LOOPBACK - 1);
Inc(P.Send);
if Size > MAX_PACKETLEN then
begin
DPrint('NET_SendLoopPacket: Buffer overflow.');
Size := MAX_PACKETLEN;
end;
P.Msgs[I].Size := Size;
if Size > 0 then
Move(Buffer^, P.Msgs[I].Data, Size);
NET_ThreadUnlock;
end;
procedure NET_RemoveFromPacketList(P: PLagPacket);
begin
P.Next.Prev := P.Prev;
P.Prev.Next := P.Next;
P.Next := nil;
P.Prev := nil;
end;
function NET_CountLaggedList(P: PLagPacket): Int;
var
P2: PLagPacket;
begin
Result := 0;
if P <> nil then
begin
P2 := P.Prev;
while (P2 <> nil) and (P2 <> P) do
begin
Inc(Result);
P2 := P2.Prev;
end;
end;
end;
procedure NET_ClearLaggedList(P: PLagPacket);
var
P2, P3: PLagPacket;
begin
P2 := P.Prev;
while (P2 <> nil) and (P2 <> P) do
begin
P3 := P2.Prev;
NET_RemoveFromPacketList(P2);
if P2.Data <> nil then
Mem_Free(P2.Data);
Mem_Free(P2);
P2 := P3;
end;
P.Next := P;
P.Prev := P;
end;
procedure NET_AddToLagged(Source: TNetSrc; Base, New: PLagPacket; const A: TNetAdr; const SB: TSizeBuf; Time: Single);
begin
if New = nil then
DPrint('NET_AddToLagged: Bad packet.')
else
if (New.Prev <> nil) or (New.Next <> nil) then
DPrint('NET_AddToLagged: Packet already linked.')
else
begin
New.Data := Mem_Alloc(SB.CurrentSize);
if New.Data = nil then
DPrint(['NET_AddToLagged: Failed to allocate ', SB.CurrentSize, ' bytes.'])
else
begin
New.Size := SB.CurrentSize;
New.Next := Base.Next;
Base.Next.Prev := New;
Base.Next := New;
New.Prev := Base;
Move(SB.Data^, New.Data^, New.Size);
New.Addr := A;
New.Time := Time;
end;
end;
end;
procedure NET_AdjustLag;
var
X, D, SD: Double;
begin
if not AllowCheats and (fakelag.Value <> 0) then
begin
Print('Server must enable cheats to activate fakelag.');
CVar_DirectSet(fakelag, '0');
FakeLagTime := 0;
end
else
if AllowCheats and (fakelag.Value <> FakeLagTime) then
begin
X := RealTime - LastLagTime;
if X < 0 then
X := 0
else
if X > 0.1 then
X := 0.1;
LastLagTime := RealTime;
D := fakelag.Value - FakeLagTime;
SD := X * 200;
if Abs(D) < SD then
SD := Abs(D);
if D < 0 then
SD := -SD;
FakeLagTime := FakeLagTime + SD;
end;
end;
function NET_LagPacket(Add: Boolean; Source: TNetSrc; A: PNetAdr; SB: PSizeBuf): Boolean;
var
S: Single;
P, P2: PLagPacket;
begin
if FakeLagTime <= 0 then
begin
NET_ClearLagData(False, True);
Result := Add;
Exit;
end;
Result := False;
if Add then
begin
S := fakeloss.Value;
if S <> 0 then
if AllowCheats then
begin
Inc(LossCount[Source]);
if S < 0 then
begin
S := Trunc(Abs(S));
if S < 2 then
S := 2;
if (LossCount[Source] mod Trunc(S)) = 0 then
Exit;
end
else
if RandomLong(0, 100) <= Trunc(S) then
Exit;
end
else
CVar_DirectSet(fakeloss, '0');
if (A <> nil) and (SB <> nil) then
NET_AddToLagged(Source, @LagData[Source], Mem_ZeroAlloc(SizeOf(TLagPacket)), A^, SB^, RealTime);
end;
P := LagData[Source].Prev;
P2 := @LagData[Source];
if P = P2 then
Exit;
S := RealTime - FakeLagTime / 1000;
while P.Time > S do
begin
P := P.Prev;
if P = P2 then
Exit;
end;
NET_RemoveFromPacketList(P);
if P.Data <> nil then
begin
NET_TransferRawData(InMessage, P.Data, P.Size);
Move(P.Addr, InFrom, SizeOf(InFrom));
Mem_Free(P.Data);
end
else
Move(P.Addr, InFrom, SizeOf(InFrom));
Mem_Free(P);
Result := True;
end;
procedure NET_FlushSocket(Source: TNetSrc);
var
S: TSocket;
AddrLen: Int32;
Buf: array[1..MAX_MESSAGELEN] of Byte;
A: TSockAddr;
begin
S := IPSockets[Source];
if S > 0 then
begin
AddrLen := SizeOf(A);
{$IFDEF MSWINDOWS}
while recvfrom(S, Buf, SizeOf(Buf), 0, A, AddrLen) > 0 do ;
{$ELSE}
while recvfrom(S, Buf, SizeOf(Buf), 0, @A, @AddrLen) > 0 do ;
{$ENDIF}
end;
end;
function NET_FindSplitContext(const Addr: TNetAdr): PSplitContext;
var
I, J, Index: UInt;
P: PSplitContext;
MinTime: Double;
begin
MinTime := RealTime;
Index := 0;
for I := 0 to MAX_SPLIT_CTX - 1 do
begin
J := (CurrentCtx - I) and (MAX_SPLIT_CTX - 1);
P := @SplitCtx[J];
if NET_CompareAdr(P.Addr, Addr) then
begin
Result := P;
Exit;
end
else
if P.Time < MinTime then
begin
MinTime := P.Time;
Index := J;
end;
end;
P := @SplitCtx[Index];
P.Addr := Addr;
P.PacketsLeft := -1;
CurrentCtx := Index;
Result := P;
end;
procedure NET_ClearSplitContexts;
var
I: UInt;
P: PSplitContext;
begin
for I := 0 to MAX_SPLIT_CTX - 1 do
begin
P := @SplitCtx[I];
MemSet(P.Addr, SizeOf(P.Addr), 0);
P.Time := 0;
end;
end;
function NET_GetLong(Data: Pointer; Size: UInt; out OutSize: UInt; const Addr: TNetAdr): Boolean;
var
Header: TSplitHeader;
CurSplit, MaxSplit: UInt;
P: PSplitContext;
I: Int;
begin
Result := False;
Move(Data^, Header, SizeOf(Header));
CurSplit := Header.Index shr 4;
MaxSplit := Header.Index and $F;
if (CurSplit >= MAX_SPLIT) or (CurSplit >= MaxSplit) then
DPrint(['Malformed split packet current number (', CurSplit, ').'])
else
if (MaxSplit > MAX_SPLIT) or (MaxSplit = 0) then
DPrint(['Malformed split packet max number (', MaxSplit, ').'])
else
begin
P := NET_FindSplitContext(Addr);
if (P.PacketsLeft <= 0) or (P.Sequence <> Header.SplitSeq) then
begin
if net_showpackets.Value = 4 then
if P.PacketsLeft = -1 then
DPrint(['New split context with ', MaxSplit, ' packets, sequence = ', Header.SplitSeq, '.'])
else
DPrint(['Restarting split context with ', MaxSplit, ' packets, sequence = ', Header.SplitSeq, '.']);
P.Time := RealTime;
P.PacketsLeft := MaxSplit;
P.Sequence := Header.SplitSeq;
P.Size := 0;
P.Ack := [];
end
else
if net_showpackets.Value = 4 then
DPrint(['Found existing split context with ', MaxSplit, ' packets, sequence = ', Header.SplitSeq, '.']);
Dec(Size, SizeOf(Header));
if CurSplit in P.Ack then
DPrint(['Received duplicated split fragment (num = ', CurSplit + 1, '/', MaxSplit, ', sequence = ', Header.SplitSeq, '), ignoring.'])
else
if P.Size + Size > MAX_MESSAGELEN then
DPrint(['Split context overflowed with ', P.Size + Size, ' bytes (num = ', CurSplit + 1, '/', MaxSplit, ', sequence = ', Header.SplitSeq, ').'])
else
begin
if net_showpackets.Value = 4 then
DPrint(['Received split fragment (num = ', CurSplit + 1, '/', MaxSplit, ', sequence = ', Header.SplitSeq, ').']);
Dec(P.PacketsLeft);
Include(P.Ack, CurSplit);
Move(Pointer(UInt(Data) + SizeOf(Header))^, Pointer(UInt(@P.Data) + P.Size)^, Size);
Inc(P.Size, Size);
if P.PacketsLeft = 0 then
begin
for I := 0 to MaxSplit - 1 do
if not (I in P.Ack) then
begin
DPrint(['Received a split packet without all ', MaxSplit, ' parts; sequence = ', Header.SplitSeq, ', ignoring.']);
Exit;
end;
DPrint(['Received a split packet with sequence = ', Header.SplitSeq, '.']);
Move(P.Data, Data^, P.Size);
OutSize := P.Size;
MemSet(P.Addr, SizeOf(P.Addr), 0);
P.Time := 0;
Result := True;
end;
end;
end;
end;
function NET_QueuePacket(Source: TNetSrc): Boolean;
var
S: TSocket;
Buf: array[1..MAX_MESSAGELEN] of Byte;
NetAdrBuf: array[1..64] of LChar;
A: TSockAddr;
AddrLen: Int32;
Size: UInt;
E: Int;
begin
S := IPSockets[Source];
if S > 0 then
begin
AddrLen := SizeOf(TSockAddr);
{$IFDEF MSWINDOWS}
E := recvfrom(S, Buf, SizeOf(Buf), 0, A, AddrLen);
{$ELSE}
E := recvfrom(S, Buf, SizeOf(Buf), 0, @A, @AddrLen);
{$ENDIF}
if E = SOCKET_ERROR then
begin
E := NET_LastError;
if E = {$IFDEF MSWINDOWS}WSAEMSGSIZE{$ELSE}EMSGSIZE{$ENDIF} then
DPrint(['NET_QueuePacket: Ignoring oversized network message, allowed no more than ', MAX_MESSAGELEN, ' bytes.'])
else
{$IFDEF MSWINDOWS}
if (E <> WSAEWOULDBLOCK) and (E <> WSAECONNRESET) and (E <> WSAECONNREFUSED) then
{$ELSE}
if (E <> EAGAIN) and (E <> ECONNRESET) and (E <> ECONNREFUSED) then
{$ENDIF}
Print(['NET_QueuePacket: Network error "', NET_ErrorString(E), '".']);
end
else
begin
SockadrToNetadr(A, InFrom);
if E > SizeOf(Buf) then
DPrint(['NET_QueuePacket: Oversized packet from ', NET_AdrToString(InFrom, NetAdrBuf, SizeOf(NetAdrBuf)), '.'])
else
begin
Size := E;
NET_TransferRawData(InMessage, @Buf, Size);
if PInt32(InMessage.Data)^ = SPLIT_TAG then
if InMessage.CurrentSize >= SizeOf(TSplitHeader) then
Result := NET_GetLong(InMessage.Data, Size, InMessage.CurrentSize, InFrom)
else
begin
DPrint(['NET_QueuePacket: Invalid incoming split packet length (', InMessage.CurrentSize, '), should be no lesser than ', SizeOf(TSplitHeader), '.']);
Result := NET_LagPacket(False, Source, nil, nil);
end
else
Result := NET_LagPacket(True, Source, @InFrom, @InMessage);
Exit;
end;
end;
end;
Result := NET_LagPacket(False, Source, nil, nil);
end;
function NET_Sleep: Int;
var
I: TNetSrc;
FDSet: TFDSet;
Num, S: TSocket;
A: TTimeVal;
P: PTimeVal;
begin
Num := 0;
FD_ZERO(FDSet);
for I := Low(I) to High(I) do
begin
S := IPSockets[I];
if S > 0 then
begin
FD_SET(S, FDSet);
if S > Num then
Num := S;
end;
end;
if NetSleepForever then
P := nil
else
begin
A.tv_sec := 0;
A.tv_usec := 20000;
P := @A;
end;
Result := select(Num + 1, @FDSet, nil, nil, P);
end;
function ThreadProc(Parameter: Pointer): Int32;
var
B: Boolean;
I: TNetSrc;
NewMsg, P: PNetQueue;
begin
while True do
begin
while NET_Sleep > 0 do
begin
B := True;
for I := Low(I) to High(I) do
begin
NET_ThreadLock;
if NET_QueuePacket(I) then
begin
B := False;
NewMsg := NET_AllocMsg(InMessage.CurrentSize);
Move(InMessage.Data^, NewMsg.Data^, InMessage.CurrentSize);
Move(InFrom, NewMsg.Addr, SizeOf(NewMsg.Addr));
NewMsg.Prev := nil;
P := NetMessages[I];
if P <> nil then
begin
while P.Prev <> nil do
P := P.Prev;
P.Prev := NewMsg;
end
else
NetMessages[I] := NewMsg;
end;
NET_ThreadUnlock;
end;
if not B then
Break;
end;
Sys_Sleep(0);
end;
Result := 0;
EndThread(0);
end;
procedure NET_StartThread;
begin
if UseThread and not ThreadInit then
begin
Sys_InitCS(ThreadCS);
ThreadHandle := BeginThread(nil, 0, @ThreadProc, nil, 0, ThreadID);
if ThreadHandle = 0 then
begin
Sys_DeleteCS(ThreadCS);
UseThread := False;
Sys_Error('Couldn''t initialize network thread - run without -netthread.');
end
else
ThreadInit := True;
end;
end;
procedure NET_StopThread;
begin
if UseThread and ThreadInit then
begin
{$IFDEF MSWINDOWS}TerminateThread(ThreadHandle, 0){$ELSE}pthread_cancel(UInt(ThreadHandle)){$ENDIF};
Sys_DeleteCS(ThreadCS);
ThreadInit := False;
end;
end;
function NET_AllocMsg(Size: UInt): PNetQueue;
var
P: PNetQueue;
begin
if (Size <= NET_QUEUESIZE) and (NormalQueue <> nil) then
begin
P := NormalQueue;
P.Size := Size;
P.Normal := True;
NormalQueue := P.Prev;
end