DEADSOFTWARE

261df8cad6e0aa6e08b42ccd41c3a312f8601410
[d2df-sdl.git] / src / game / g_net.pas
1 (* Copyright (C) Doom 2D: Forever Developers
2 *
3 * This program is free software: you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation, version 3 of the License ONLY.
6 *
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
11 *
12 * You should have received a copy of the GNU General Public License
13 * along with this program. If not, see <http://www.gnu.org/licenses/>.
14 *)
15 {$INCLUDE ../shared/a_modes.inc}
16 unit g_net;
18 interface
20 uses
21 e_log, e_msg, ENet, Classes, md5, MAPDEF{$IFDEF USE_MINIUPNPC}, miniupnpc;{$ELSE};{$ENDIF}
23 const
24 NET_PROTOCOL_VER = 182;
26 NET_MAXCLIENTS = 24;
27 NET_CHANS = 12;
29 NET_CHAN_SERVICE = 0;
30 NET_CHAN_IMPORTANT = 1;
31 NET_CHAN_GAME = 2;
32 NET_CHAN_PLAYER = 3;
33 NET_CHAN_PLAYERPOS = 4;
34 NET_CHAN_MONSTER = 5;
35 NET_CHAN_MONSTERPOS = 6;
36 NET_CHAN_LARGEDATA = 7;
37 NET_CHAN_CHAT = 8;
38 NET_CHAN_DOWNLOAD = 9;
39 NET_CHAN_SHOTS = 10;
40 NET_CHAN_DOWNLOAD_EX = 11;
42 NET_NONE = 0;
43 NET_SERVER = 1;
44 NET_CLIENT = 2;
46 NET_BUFSIZE = $FFFF;
47 NET_PING_PORT = $DF2D;
49 NET_EVERYONE = -1;
51 NET_UNRELIABLE = 0;
52 NET_RELIABLE = 1;
54 NET_DISC_NONE: enet_uint32 = 0;
55 NET_DISC_PROTOCOL: enet_uint32 = 1;
56 NET_DISC_VERSION: enet_uint32 = 2;
57 NET_DISC_FULL: enet_uint32 = 3;
58 NET_DISC_KICK: enet_uint32 = 4;
59 NET_DISC_DOWN: enet_uint32 = 5;
60 NET_DISC_PASSWORD: enet_uint32 = 6;
61 NET_DISC_TEMPBAN: enet_uint32 = 7;
62 NET_DISC_BAN: enet_uint32 = 8;
63 NET_DISC_MAX: enet_uint32 = 8;
64 NET_DISC_FILE_TIMEOUT: enet_uint32 = 13;
66 NET_STATE_NONE = 0;
67 NET_STATE_AUTH = 1;
68 NET_STATE_GAME = 2;
70 NET_CONNECT_TIMEOUT = 1000 * 10;
72 BANLIST_FILENAME = 'banlist.txt';
73 NETDUMP_FILENAME = 'netdump';
75 {$IF DEFINED(FREEBSD) OR DEFINED(DARWIN)}
76 NilThreadId = nil;
77 {$ELSE}
78 NilThreadId = 0;
79 {$ENDIF}
81 type
82 TNetMapResourceInfo = record
83 wadName: AnsiString; // wad file name, without a path
84 size: Integer; // wad file size (-1: size and hash are not known)
85 hash: TMD5Digest; // wad hash
86 end;
88 TNetMapResourceInfoArray = array of TNetMapResourceInfo;
90 TNetFileTransfer = record
91 diskName: string;
92 hash: TMD5Digest;
93 stream: TStream;
94 size: Integer; // file size in bytes
95 chunkSize: Integer;
96 lastSentChunk: Integer;
97 lastAckChunk: Integer;
98 lastAckTime: Int64; // msecs; if not "in progress", we're waiting for the first ack
99 inProgress: Boolean;
100 diskBuffer: PChar; // of `chunkSize` bytes
101 resumed: Boolean;
102 end;
104 TNetClient = record
105 ID: Byte;
106 Used: Boolean;
107 State: Byte;
108 Peer: pENetPeer;
109 Player: Word;
110 RequestedFullUpdate: Boolean;
111 WaitForFirstSpawn: Boolean; // set to `true` in server, used to spawn a player on first full state request
112 RCONAuth: Boolean;
113 Voted: Boolean;
114 Transfer: TNetFileTransfer; // only one transfer may be active
115 NetOut: array [0..1] of TMsg;
116 end;
117 TBanRecord = record
118 IP: LongWord;
119 Perm: Boolean;
120 end;
121 pTNetClient = ^TNetClient;
123 AByte = array of Byte;
125 var
126 NetInitDone: Boolean = False;
127 NetMode: Byte = NET_NONE;
128 NetDump: Boolean = False;
130 NetServerName: string = 'Unnamed Server';
131 NetPassword: string = '';
132 NetPort: Word = 25666;
134 NetAllowRCON: Boolean = False;
135 NetRCONPassword: string = '';
137 NetTimeToUpdate: Cardinal = 0;
138 NetTimeToReliable: Cardinal = 0;
139 NetTimeToMaster: Cardinal = 0;
141 NetHost: pENetHost = nil;
142 NetPeer: pENetPeer = nil;
143 NetEvent: ENetEvent;
144 NetAddr: ENetAddress;
146 NetPongAddr: ENetAddress;
147 NetPongSock: ENetSocket = ENET_SOCKET_NULL;
149 NetUseMaster: Boolean = True;
150 NetSlistIP: string = 'mpms.doom2d.org';
151 NetSlistPort: Word = 25665;
152 NetSlistList: string = 'deadsoftware.ru:25665';
154 NetClientIP: string = '127.0.0.1';
155 NetClientPort: Word = 25666;
157 NetIn, NetOut: TMsg;
158 NetBuf: array [0..1] of TMsg;
160 NetClients: array of TNetClient;
161 NetClientCount: Byte = 0;
162 NetMaxClients: Byte = 255;
163 NetBannedHosts: array of TBanRecord;
165 NetState: Integer = NET_STATE_NONE;
167 NetMyID: Integer = -1;
168 NetPlrUID1: Integer = -1;
169 NetPlrUID2: Integer = -1;
171 NetInterpLevel: Integer = 1;
172 NetUpdateRate: Cardinal = 0; // as soon as possible
173 NetRelupdRate: Cardinal = 18; // around two times a second
174 NetMasterRate: Cardinal = 60000;
176 NetForcePlayerUpdate: Boolean = False;
177 NetPredictSelf: Boolean = True;
178 NetForwardPorts: Boolean = False;
180 NetGotEverything: Boolean = False;
181 NetGotKeys: Boolean = False;
183 {$IFDEF USE_MINIUPNPC}
184 NetPortForwarded: Word = 0;
185 NetPongForwarded: Boolean = False;
186 NetIGDControl: AnsiString;
187 NetIGDService: TURLStr;
188 {$ENDIF}
190 NetPortThread: TThreadID = NilThreadId;
192 NetDumpFile: TStream;
194 g_Res_received_map_start: Integer = 0; // set if we received "map change" event
197 function g_Net_Init(): Boolean;
198 procedure g_Net_Cleanup();
199 procedure g_Net_Free();
200 procedure g_Net_Flush();
202 function g_Net_Host(IPAddr: LongWord; Port: enet_uint16; MaxClients: Cardinal = 16): Boolean;
203 procedure g_Net_Host_Die();
204 procedure g_Net_Host_Send(ID: Integer; Reliable: Boolean; Chan: Byte = NET_CHAN_GAME);
205 function g_Net_Host_Update(): enet_size_t;
207 function g_Net_Connect(IP: string; Port: enet_uint16): Boolean;
208 procedure g_Net_Disconnect(Forced: Boolean = False);
209 procedure g_Net_Client_Send(Reliable: Boolean; Chan: Byte = NET_CHAN_GAME);
210 function g_Net_Client_Update(): enet_size_t;
211 function g_Net_Client_UpdateWhileLoading(): enet_size_t;
213 function g_Net_Client_ByName(Name: string): pTNetClient;
214 function g_Net_Client_ByPlayer(PID: Word): pTNetClient;
215 function g_Net_ClientName_ByID(ID: Integer): string;
217 procedure g_Net_SendData(Data: AByte; peer: pENetPeer; Reliable: Boolean; Chan: Byte = NET_CHAN_DOWNLOAD);
218 //function g_Net_Wait_Event(msgId: Word): TMemoryStream;
219 //function g_Net_Wait_FileInfo (var tf: TNetFileTransfer; asMap: Boolean; out resList: TStringList): Integer;
221 function IpToStr(IP: LongWord): string;
222 function StrToIp(IPstr: string; var IP: LongWord): Boolean;
224 function g_Net_IsHostBanned(IP: LongWord; Perm: Boolean = False): Boolean;
225 procedure g_Net_BanHost(IP: LongWord; Perm: Boolean = True); overload;
226 procedure g_Net_BanHost(IP: string; Perm: Boolean = True); overload;
227 function g_Net_UnbanHost(IP: string): Boolean; overload;
228 function g_Net_UnbanHost(IP: LongWord): Boolean; overload;
229 procedure g_Net_UnbanNonPermHosts();
230 procedure g_Net_SaveBanList();
232 procedure g_Net_DumpStart();
233 procedure g_Net_DumpSendBuffer();
234 procedure g_Net_DumpRecvBuffer(Buf: penet_uint8; Len: LongWord);
235 procedure g_Net_DumpEnd();
237 function g_Net_ForwardPorts(ForwardPongPort: Boolean = True): Boolean;
238 procedure g_Net_UnforwardPorts();
240 function g_Net_UserRequestExit: Boolean;
242 function g_Net_Wait_MapInfo (var tf: TNetFileTransfer; var resList: TNetMapResourceInfoArray): Integer;
243 function g_Net_RequestResFileInfo (resIndex: LongInt; out tf: TNetFileTransfer): Integer;
244 function g_Net_AbortResTransfer (var tf: TNetFileTransfer): Boolean;
245 function g_Net_ReceiveResourceFile (resIndex: LongInt; var tf: TNetFileTransfer; strm: TStream): Integer;
247 function g_Net_IsNetworkAvailable (): Boolean;
248 procedure g_Net_InitLowLevel ();
249 procedure g_Net_DeinitLowLevel ();
252 implementation
254 // *enet_host_service()*
255 // fuck! https://www.mail-archive.com/enet-discuss@cubik.org/msg00852.html
256 // tl;dr: on shitdows, we can get -1 sometimes, and it is *NOT* a failure.
257 // thank you, enet. let's ignore failures altogether then.
259 uses
260 SysUtils,
261 e_input, g_nethandler, g_netmsg, g_netmaster, g_player, g_window, g_console,
262 g_main, g_game, g_language, g_weapons, utils, ctypes, g_system,
263 g_map;
265 const
266 FILE_CHUNK_SIZE = 8192;
268 var
269 enet_init_success: Boolean = false;
270 g_Net_DownloadTimeout: Single;
271 trans_omsg: TMsg;
274 function g_Net_IsNetworkAvailable (): Boolean;
275 begin
276 result := enet_init_success;
277 end;
279 procedure g_Net_InitLowLevel ();
280 begin
281 if enet_init_success then raise Exception.Create('wuta?!');
282 enet_init_success := (enet_initialize() = 0);
283 end;
285 procedure g_Net_DeinitLowLevel ();
286 begin
287 if enet_init_success then
288 begin
289 enet_deinitialize();
290 enet_init_success := false;
291 end;
292 end;
295 //**************************************************************************
296 //
297 // SERVICE FUNCTIONS
298 //
299 //**************************************************************************
301 procedure clearNetClientTransfers (var nc: TNetClient);
302 begin
303 nc.Transfer.stream.Free;
304 nc.Transfer.diskName := ''; // just in case
305 if (nc.Transfer.diskBuffer <> nil) then FreeMem(nc.Transfer.diskBuffer);
306 nc.Transfer.stream := nil;
307 nc.Transfer.diskBuffer := nil;
308 end;
311 procedure clearNetClient (var nc: TNetClient);
312 begin
313 clearNetClientTransfers(nc);
314 end;
317 procedure clearNetClients (clearArray: Boolean);
318 var
319 f: Integer;
320 begin
321 for f := Low(NetClients) to High(NetClients) do clearNetClient(NetClients[f]);
322 if (clearArray) then SetLength(NetClients, 0);
323 end;
326 function g_Net_UserRequestExit (): Boolean;
327 begin
328 Result := {e_KeyPressed(IK_SPACE) or}
329 e_KeyPressed(IK_ESCAPE) or
330 e_KeyPressed(VK_ESCAPE) or
331 e_KeyPressed(JOY0_JUMP) or
332 e_KeyPressed(JOY1_JUMP) or
333 e_KeyPressed(JOY2_JUMP) or
334 e_KeyPressed(JOY3_JUMP)
335 end;
338 //**************************************************************************
339 //
340 // file transfer declaraions and host packet processor
341 //
342 //**************************************************************************
344 const
345 // server packet type
346 NTF_SERVER_DONE = 10; // done with this file
347 NTF_SERVER_FILE_INFO = 11; // sent after client request
348 NTF_SERVER_CHUNK = 12; // next chunk; chunk number follows
349 NTF_SERVER_ABORT = 13; // server abort
350 NTF_SERVER_MAP_INFO = 14;
352 // client packet type
353 NTF_CLIENT_MAP_REQUEST = 100; // map file request; also, returns list of additional wads to download
354 NTF_CLIENT_FILE_REQUEST = 101; // resource file request (by index)
355 NTF_CLIENT_ABORT = 102; // do not send requested file, or abort current transfer
356 NTF_CLIENT_START = 103; // start transfer; client may resume download by sending non-zero starting chunk
357 NTF_CLIENT_ACK = 104; // chunk ack; chunk number follows
360 // disconnect client due to some file transfer error
361 procedure killClientByFT (var nc: TNetClient);
362 begin
363 e_LogWritefln('disconnected client #%d due to file transfer error', [nc.ID], TMsgType.Warning);
364 enet_peer_disconnect(nc.Peer, NET_DISC_FILE_TIMEOUT);
365 clearNetClientTransfers(nc);
366 g_Net_Slist_ServerPlayerLeaves();
367 end;
370 // send file transfer message from server to client
371 function ftransSendServerMsg (var nc: TNetClient; var m: TMsg): Boolean;
372 var
373 pkt: PENetPacket;
374 begin
375 result := false;
376 if (m.CurSize < 1) then exit;
377 pkt := enet_packet_create(m.Data, m.CurSize, ENET_PACKET_FLAG_RELIABLE);
378 if not Assigned(pkt) then begin killClientByFT(nc); exit; end;
379 if (enet_peer_send(nc.Peer, NET_CHAN_DOWNLOAD_EX, pkt) <> 0) then begin killClientByFT(nc); exit; end;
380 result := true;
381 end;
384 // send file transfer message from client to server
385 function ftransSendClientMsg (var m: TMsg): Boolean;
386 var
387 pkt: PENetPacket;
388 begin
389 result := false;
390 if (m.CurSize < 1) then exit;
391 pkt := enet_packet_create(m.Data, m.CurSize, ENET_PACKET_FLAG_RELIABLE);
392 if not Assigned(pkt) then exit;
393 if (enet_peer_send(NetPeer, NET_CHAN_DOWNLOAD_EX, pkt) <> 0) then exit;
394 result := true;
395 end;
398 // file chunk sender
399 procedure ProcessChunkSend (var nc: TNetClient);
400 var
401 tf: ^TNetFileTransfer;
402 ct: Int64;
403 chunks: Integer;
404 rd: Integer;
405 begin
406 tf := @nc.Transfer;
407 if (tf.stream = nil) then exit;
408 ct := GetTimerMS();
409 // arbitrary timeout number
410 if (ct-tf.lastAckTime >= 5000) then
411 begin
412 killClientByFT(nc);
413 exit;
414 end;
415 // check if we need to send something
416 if (not tf.inProgress) then exit; // waiting for the initial ack
417 // ok, we're sending chunks
418 if (tf.lastAckChunk <> tf.lastSentChunk) then exit;
419 Inc(tf.lastSentChunk);
420 // do it one chunk at a time; client ack will advance our chunk counter
421 chunks := (tf.size+tf.chunkSize-1) div tf.chunkSize;
423 if (tf.lastSentChunk > chunks) then
424 begin
425 killClientByFT(nc);
426 exit;
427 end;
429 trans_omsg.Clear();
430 if (tf.lastSentChunk = chunks) then
431 begin
432 // we're done with this file
433 e_LogWritefln('download: client #%d, DONE sending chunks #%d/#%d', [nc.ID, tf.lastSentChunk, chunks]);
434 trans_omsg.Write(Byte(NTF_SERVER_DONE));
435 clearNetClientTransfers(nc);
436 end
437 else
438 begin
439 // packet type
440 trans_omsg.Write(Byte(NTF_SERVER_CHUNK));
441 trans_omsg.Write(LongInt(tf.lastSentChunk));
442 // read chunk
443 rd := tf.size-(tf.lastSentChunk*tf.chunkSize);
444 if (rd > tf.chunkSize) then rd := tf.chunkSize;
445 trans_omsg.Write(LongInt(rd));
446 //e_LogWritefln('download: client #%d, sending chunk #%d/#%d (%d bytes)', [nc.ID, tf.lastSentChunk, chunks, rd]);
447 //FIXME: check for errors here
448 try
449 tf.stream.Seek(tf.lastSentChunk*tf.chunkSize, soFromBeginning);
450 tf.stream.ReadBuffer(tf.diskBuffer^, rd);
451 trans_omsg.WriteData(tf.diskBuffer, rd);
452 except // sorry
453 killClientByFT(nc);
454 exit;
455 end;
456 end;
457 // send packet
458 ftransSendServerMsg(nc, trans_omsg);
459 end;
462 // server file transfer packet processor
463 // received packet is in `NetEvent`
464 procedure ProcessDownloadExPacket ();
465 var
466 f: Integer;
467 nc: ^TNetClient;
468 nid: Integer = -1;
469 msg: TMsg;
470 cmd: Byte;
471 tf: ^TNetFileTransfer;
472 fname: string;
473 chunk: Integer;
474 ridx: Integer;
475 dfn: AnsiString;
476 md5: TMD5Digest;
477 //st: TStream;
478 size: LongInt;
479 fi: TDiskFileInfo;
480 begin
481 // find client index by peer
482 for f := Low(NetClients) to High(NetClients) do
483 begin
484 if (not NetClients[f].Used) then continue;
485 if (NetClients[f].Peer = NetEvent.peer) then
486 begin
487 nid := f;
488 break;
489 end;
490 end;
491 //e_LogWritefln('RECEIVE: dlpacket; client=%d (datalen=%u)', [nid, NetEvent.packet^.dataLength]);
493 if (nid < 0) then exit; // wtf?!
494 nc := @NetClients[nid];
496 if (NetEvent.packet^.dataLength = 0) then
497 begin
498 killClientByFT(nc^);
499 exit;
500 end;
502 tf := @NetClients[nid].Transfer;
503 tf.lastAckTime := GetTimerMS();
505 cmd := Byte(NetEvent.packet^.data^);
506 //e_LogWritefln('RECEIVE: nid=%d; cmd=%u', [nid, cmd]);
507 case cmd of
508 NTF_CLIENT_FILE_REQUEST: // file request
509 begin
510 if (tf.stream <> nil) then
511 begin
512 killClientByFT(nc^);
513 exit;
514 end;
515 if (NetEvent.packet^.dataLength < 2) then
516 begin
517 killClientByFT(nc^);
518 exit;
519 end;
520 // new transfer request; build packet
521 if not msg.Init(NetEvent.packet^.data+1, NetEvent.packet^.dataLength-1, True) then
522 begin
523 killClientByFT(nc^);
524 exit;
525 end;
526 // get resource index
527 ridx := msg.ReadLongInt();
528 if (ridx < -1) or (ridx >= length(gExternalResources)) then
529 begin
530 e_LogWritefln('Invalid resource index %d', [ridx], TMsgType.Warning);
531 killClientByFT(nc^);
532 exit;
533 end;
534 if (ridx < 0) then fname := MapsDir+gGameSettings.WAD else fname := {GameDir+'/wads/'+}gExternalResources[ridx].diskName;
535 if (length(fname) = 0) then
536 begin
537 e_WriteLog('Invalid filename: '+fname, TMsgType.Warning);
538 killClientByFT(nc^);
539 exit;
540 end;
541 tf.diskName := findDiskWad(fname);
542 //if (length(tf.diskName) = 0) then tf.diskName := findDiskWad(GameDir+'/wads/'+fname);
543 if (length(tf.diskName) = 0) then
544 begin
545 e_LogWritefln('NETWORK: file "%s" not found!', [fname], TMsgType.Fatal);
546 killClientByFT(nc^);
547 exit;
548 end;
549 // calculate hash
550 //tf.hash := MD5File(tf.diskName);
551 if (ridx < 0) then tf.hash := gWADHash else tf.hash := gExternalResources[ridx].hash;
552 // create file stream
553 tf.diskName := findDiskWad(fname);
554 try
555 tf.stream := openDiskFileRO(tf.diskName);
556 except
557 tf.stream := nil;
558 end;
559 if (tf.stream = nil) then
560 begin
561 e_WriteLog(Format('NETWORK: file "%s" not found!', [fname]), TMsgType.Fatal);
562 killClientByFT(nc^);
563 exit;
564 end;
565 e_LogWritefln('client #%d requested resource #%d (file is `%s` : `%s`)', [nc.ID, ridx, fname, tf.diskName]);
566 tf.size := tf.stream.size;
567 tf.chunkSize := FILE_CHUNK_SIZE; // arbitrary
568 tf.lastSentChunk := -1;
569 tf.lastAckChunk := -1;
570 tf.lastAckTime := GetTimerMS();
571 tf.inProgress := False; // waiting for the first ACK or for the cancel
572 GetMem(tf.diskBuffer, tf.chunkSize);
573 // sent file info message
574 trans_omsg.Clear();
575 trans_omsg.Write(Byte(NTF_SERVER_FILE_INFO));
576 trans_omsg.Write(tf.hash);
577 trans_omsg.Write(tf.size);
578 trans_omsg.Write(tf.chunkSize);
579 trans_omsg.Write(ExtractFileName(fname));
580 if not ftransSendServerMsg(nc^, trans_omsg) then exit;
581 end;
582 NTF_CLIENT_ABORT: // do not send requested file, or abort current transfer
583 begin
584 e_LogWritefln('client #%d aborted file transfer', [nc.ID]);
585 clearNetClientTransfers(nc^);
586 end;
587 NTF_CLIENT_START: // start transfer; client may resume download by sending non-zero starting chunk
588 begin
589 if not Assigned(tf.stream) then
590 begin
591 killClientByFT(nc^);
592 exit;
593 end;
594 if (tf.lastSentChunk <> -1) or (tf.lastAckChunk <> -1) or (tf.inProgress) then
595 begin
596 // double ack, get lost
597 killClientByFT(nc^);
598 exit;
599 end;
600 if (NetEvent.packet^.dataLength < 2) then
601 begin
602 killClientByFT(nc^);
603 exit;
604 end;
605 // build packet
606 if not msg.Init(NetEvent.packet^.data+1, NetEvent.packet^.dataLength-1, True) then
607 begin
608 killClientByFT(nc^);
609 exit;
610 end;
611 chunk := msg.ReadLongInt();
612 if (chunk < 0) or (chunk > (tf.size+tf.chunkSize-1) div tf.chunkSize) then
613 begin
614 killClientByFT(nc^);
615 exit;
616 end;
617 e_LogWritefln('client #%d started file transfer from chunk %d', [nc.ID, chunk]);
618 // start sending chunks
619 tf.inProgress := True;
620 tf.lastSentChunk := chunk-1;
621 tf.lastAckChunk := chunk-1;
622 ProcessChunkSend(nc^);
623 end;
624 NTF_CLIENT_ACK: // chunk ack; chunk number follows
625 begin
626 if not Assigned(tf.stream) then
627 begin
628 killClientByFT(nc^);
629 exit;
630 end;
631 if (tf.lastSentChunk < 0) or (not tf.inProgress) then
632 begin
633 // double ack, get lost
634 killClientByFT(nc^);
635 exit;
636 end;
637 if (NetEvent.packet^.dataLength < 2) then
638 begin
639 killClientByFT(nc^);
640 exit;
641 end;
642 // build packet
643 if not msg.Init(NetEvent.packet^.data+1, NetEvent.packet^.dataLength-1, True) then
644 begin
645 killClientByFT(nc^);
646 exit;
647 end;
648 chunk := msg.ReadLongInt();
649 if (chunk < 0) or (chunk > (tf.size+tf.chunkSize-1) div tf.chunkSize) then
650 begin
651 killClientByFT(nc^);
652 exit;
653 end;
654 // do it this way, so client may seek, or request retransfers for some reason
655 tf.lastAckChunk := chunk;
656 tf.lastSentChunk := chunk;
657 //e_LogWritefln('client #%d acked file transfer chunk %d', [nc.ID, chunk]);
658 ProcessChunkSend(nc^);
659 end;
660 NTF_CLIENT_MAP_REQUEST:
661 begin
662 e_LogWritefln('client #%d requested map info', [nc.ID]);
663 trans_omsg.Clear();
664 dfn := findDiskWad(MapsDir+gGameSettings.WAD);
665 if (dfn = '') then dfn := '!wad_not_found!.wad'; //FIXME
666 //md5 := MD5File(dfn);
667 md5 := gWADHash;
668 if (not GetDiskFileInfo(dfn, fi)) then
669 begin
670 e_LogWritefln('client #%d requested map info, but i cannot get file info', [nc.ID]);
671 killClientByFT(nc^);
672 exit;
673 end;
674 size := fi.size;
676 st := openDiskFileRO(dfn);
677 if not assigned(st) then exit; //wtf?!
678 size := st.size;
679 st.Free;
681 // packet type
682 trans_omsg.Write(Byte(NTF_SERVER_MAP_INFO));
683 // map wad name
684 trans_omsg.Write(gGameSettings.WAD);
685 // map wad md5
686 trans_omsg.Write(md5);
687 // map wad size
688 trans_omsg.Write(size);
689 // number of external resources for map
690 trans_omsg.Write(LongInt(length(gExternalResources)));
691 // external resource names
692 for f := 0 to High(gExternalResources) do
693 begin
694 // old style packet
695 //trans_omsg.Write(ExtractFileName(gExternalResources[f])); // GameDir+'/wads/'+ResList.Strings[i]
696 // new style packet
697 trans_omsg.Write('!');
698 trans_omsg.Write(LongInt(gExternalResources[f].size));
699 trans_omsg.Write(gExternalResources[f].hash);
700 trans_omsg.Write(ExtractFileName(gExternalResources[f].diskName));
701 end;
702 // send packet
703 if not ftransSendServerMsg(nc^, trans_omsg) then exit;
704 end;
705 else
706 begin
707 killClientByFT(nc^);
708 exit;
709 end;
710 end;
711 end;
714 //**************************************************************************
715 //
716 // file transfer crap (both client and server)
717 //
718 //**************************************************************************
720 function getNewTimeoutEnd (): Int64;
721 begin
722 result := GetTimerMS();
723 if (g_Net_DownloadTimeout <= 0) then
724 begin
725 result := result+1000*60*3; // 3 minutes
726 end
727 else
728 begin
729 result := result+trunc(g_Net_DownloadTimeout*1000);
730 end;
731 end;
734 // send map request to server, and wait for "map info" server reply
735 //
736 // returns `false` on error or user abort
737 // fills:
738 // diskName: map wad file name (without a path)
739 // hash: map wad hash
740 // size: map wad size
741 // chunkSize: set too
742 // resList: list of resource wads
743 // returns:
744 // <0 on error
745 // 0 on success
746 // 1 on user abort
747 // 2 on server abort
748 // for maps, first `tf.diskName` name will be map wad name, and `tf.hash`/`tf.size` will contain map info
749 function g_Net_Wait_MapInfo (var tf: TNetFileTransfer; var resList: TNetMapResourceInfoArray): Integer;
750 var
751 ev: ENetEvent;
752 rMsgId: Byte;
753 Ptr: Pointer;
754 msg: TMsg;
755 freePacket: Boolean = false;
756 ct, ett: Int64;
757 status: cint;
758 s: AnsiString;
759 rc, f: LongInt;
760 ri: ^TNetMapResourceInfo;
761 begin
762 SetLength(resList, 0);
764 // send request
765 trans_omsg.Clear();
766 trans_omsg.Write(Byte(NTF_CLIENT_MAP_REQUEST));
767 if not ftransSendClientMsg(trans_omsg) then begin result := -1; exit; end;
769 FillChar(ev, SizeOf(ev), 0);
770 Result := -1;
771 try
772 ett := getNewTimeoutEnd();
773 repeat
774 status := enet_host_service(NetHost, @ev, 300);
776 if (status < 0) then
777 begin
778 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' network error', True);
779 Result := -1;
780 exit;
781 end;
783 if (status <= 0) then
784 begin
785 // check for timeout
786 ct := GetTimerMS();
787 if (ct >= ett) then
788 begin
789 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' timeout reached', True);
790 Result := -1;
791 exit;
792 end;
793 end
794 else
795 begin
796 // some event
797 case ev.kind of
798 ENET_EVENT_TYPE_RECEIVE:
799 begin
800 freePacket := true;
801 if (ev.channelID <> NET_CHAN_DOWNLOAD_EX) then
802 begin
803 //e_LogWritefln('g_Net_Wait_MapInfo: skip message from non-transfer channel', []);
804 freePacket := false;
805 g_Net_Client_HandlePacket(ev.packet, g_Net_ClientLightMsgHandler);
806 if (g_Res_received_map_start < 0) then begin result := -666; exit; end;
807 end
808 else
809 begin
810 ett := getNewTimeoutEnd();
811 if (ev.packet.dataLength < 1) then
812 begin
813 e_LogWritefln('g_Net_Wait_MapInfo: invalid server packet (no data)', []);
814 Result := -1;
815 exit;
816 end;
817 Ptr := ev.packet^.data;
818 rMsgId := Byte(Ptr^);
819 e_LogWritefln('g_Net_Wait_MapInfo: got message %u from server (dataLength=%u)', [rMsgId, ev.packet^.dataLength]);
820 if (rMsgId = NTF_SERVER_FILE_INFO) then
821 begin
822 e_LogWritefln('g_Net_Wait_MapInfo: waiting for map info reply, but got file info reply', []);
823 Result := -1;
824 exit;
825 end
826 else if (rMsgId = NTF_SERVER_ABORT) then
827 begin
828 e_LogWritefln('g_Net_Wait_MapInfo: server aborted transfer', []);
829 Result := 2;
830 exit;
831 end
832 else if (rMsgId = NTF_SERVER_MAP_INFO) then
833 begin
834 e_LogWritefln('g_Net_Wait_MapInfo: creating map info packet...', []);
835 if not msg.Init(ev.packet^.data+1, ev.packet^.dataLength-1, True) then exit;
836 e_LogWritefln('g_Net_Wait_MapInfo: parsing map info packet (rd=%d; max=%d)...', [msg.ReadCount, msg.MaxSize]);
837 SetLength(resList, 0); // just in case
838 // map wad name
839 tf.diskName := msg.ReadString();
840 e_LogWritefln('g_Net_Wait_MapInfo: map wad is `%s`', [tf.diskName]);
841 // map wad md5
842 tf.hash := msg.ReadMD5();
843 // map wad size
844 tf.size := msg.ReadLongInt();
845 e_LogWritefln('g_Net_Wait_MapInfo: map wad size is %d', [tf.size]);
846 // number of external resources for map
847 rc := msg.ReadLongInt();
848 if (rc < 0) or (rc > 1024) then
849 begin
850 e_LogWritefln('g_Net_Wait_Event: invalid number of map external resources (%d)', [rc]);
851 Result := -1;
852 exit;
853 end;
854 e_LogWritefln('g_Net_Wait_MapInfo: map external resource count is %d', [rc]);
855 SetLength(resList, rc);
856 // external resource names
857 for f := 0 to rc-1 do
858 begin
859 ri := @resList[f];
860 s := msg.ReadString();
861 if (length(s) = 0) then begin result := -1; exit; end;
862 if (s = '!') then
863 begin
864 // extended packet
865 ri.size := msg.ReadLongInt();
866 ri.hash := msg.ReadMD5();
867 ri.wadName := ExtractFileName(msg.ReadString());
868 if (length(ri.wadName) = 0) or (ri.size < 0) then begin result := -1; exit; end;
869 end
870 else
871 begin
872 // old-style packet, only name
873 ri.wadName := ExtractFileName(s);
874 if (length(ri.wadName) = 0) then begin result := -1; exit; end;
875 ri.size := -1; // unknown
876 end;
877 end;
878 e_LogWritefln('g_Net_Wait_MapInfo: got map info', []);
879 Result := 0; // success
880 exit;
881 end
882 else
883 begin
884 e_LogWritefln('g_Net_Wait_Event: invalid server packet type', []);
885 Result := -1;
886 exit;
887 end;
888 end;
889 end;
890 ENET_EVENT_TYPE_DISCONNECT:
891 begin
892 if (ev.data <= NET_DISC_MAX) then
893 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' ' + _lc[TStrings_Locale(Cardinal(I_NET_DISC_NONE) + ev.data)], True);
894 Result := -1;
895 exit;
896 end;
897 else
898 begin
899 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' unknown ENet event ' + IntToStr(Ord(ev.kind)), True);
900 result := -1;
901 exit;
902 end;
903 end;
904 if (freePacket) then begin freePacket := false; enet_packet_destroy(ev.packet); end;
905 end;
906 ProcessLoading();
907 if g_Net_UserRequestExit() then
908 begin
909 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' user abort', True);
910 Result := 1;
911 exit;
912 end;
913 until false;
914 finally
915 if (freePacket) then enet_packet_destroy(ev.packet);
916 end;
917 end;
920 // send file request to server, and wait for server reply
921 //
922 // returns `false` on error or user abort
923 // fills:
924 // diskName (actually, base name)
925 // hash
926 // size
927 // chunkSize
928 // returns:
929 // <0 on error
930 // 0 on success
931 // 1 on user abort
932 // 2 on server abort
933 // for maps, first `tf.diskName` name will be map wad name, and `tf.hash`/`tf.size` will contain map info
934 function g_Net_RequestResFileInfo (resIndex: LongInt; out tf: TNetFileTransfer): Integer;
935 var
936 ev: ENetEvent;
937 rMsgId: Byte;
938 Ptr: Pointer;
939 msg: TMsg;
940 freePacket: Boolean = false;
941 ct, ett: Int64;
942 status: cint;
943 begin
944 // send request
945 trans_omsg.Clear();
946 trans_omsg.Write(Byte(NTF_CLIENT_FILE_REQUEST));
947 trans_omsg.Write(resIndex);
948 if not ftransSendClientMsg(trans_omsg) then begin result := -1; exit; end;
950 FillChar(ev, SizeOf(ev), 0);
951 Result := -1;
952 try
953 ett := getNewTimeoutEnd();
954 repeat
955 status := enet_host_service(NetHost, @ev, 300);
957 if (status < 0) then
958 begin
959 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' network error', True);
960 Result := -1;
961 exit;
962 end;
964 if (status <= 0) then
965 begin
966 // check for timeout
967 ct := GetTimerMS();
968 if (ct >= ett) then
969 begin
970 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' timeout reached', True);
971 Result := -1;
972 exit;
973 end;
974 end
975 else
976 begin
977 // some event
978 case ev.kind of
979 ENET_EVENT_TYPE_RECEIVE:
980 begin
981 freePacket := true;
982 if (ev.channelID <> NET_CHAN_DOWNLOAD_EX) then
983 begin
984 //e_LogWriteln('g_Net_Wait_Event: skip message from non-transfer channel');
985 freePacket := false;
986 g_Net_Client_HandlePacket(ev.packet, g_Net_ClientLightMsgHandler);
987 if (g_Res_received_map_start < 0) then begin result := -666; exit; end;
988 end
989 else
990 begin
991 ett := getNewTimeoutEnd();
992 if (ev.packet.dataLength < 1) then
993 begin
994 e_LogWriteln('g_Net_Wait_Event: invalid server packet (no data)');
995 Result := -1;
996 exit;
997 end;
998 Ptr := ev.packet^.data;
999 rMsgId := Byte(Ptr^);
1000 e_LogWritefln('received transfer packet with id %d (%u bytes)', [rMsgId, ev.packet^.dataLength]);
1001 if (rMsgId = NTF_SERVER_FILE_INFO) then
1002 begin
1003 if not msg.Init(ev.packet^.data+1, ev.packet^.dataLength-1, True) then exit;
1004 tf.hash := msg.ReadMD5();
1005 tf.size := msg.ReadLongInt();
1006 tf.chunkSize := msg.ReadLongInt();
1007 tf.diskName := ExtractFileName(msg.readString());
1008 if (tf.size < 0) or (tf.chunkSize <> FILE_CHUNK_SIZE) or (length(tf.diskName) = 0) then
1009 begin
1010 e_LogWritefln('g_Net_RequestResFileInfo: invalid file info packet', []);
1011 Result := -1;
1012 exit;
1013 end;
1014 e_LogWritefln('got file info for resource #%d: size=%d; name=%s', [resIndex, tf.size, tf.diskName]);
1015 Result := 0; // success
1016 exit;
1017 end
1018 else if (rMsgId = NTF_SERVER_ABORT) then
1019 begin
1020 e_LogWriteln('g_Net_RequestResFileInfo: server aborted transfer');
1021 Result := 2;
1022 exit;
1023 end
1024 else if (rMsgId = NTF_SERVER_MAP_INFO) then
1025 begin
1026 e_LogWriteln('g_Net_RequestResFileInfo: waiting for map info reply, but got file info reply');
1027 Result := -1;
1028 exit;
1029 end
1030 else
1031 begin
1032 e_LogWriteln('g_Net_RequestResFileInfo: invalid server packet type');
1033 Result := -1;
1034 exit;
1035 end;
1036 end;
1037 end;
1038 ENET_EVENT_TYPE_DISCONNECT:
1039 begin
1040 if (ev.data <= NET_DISC_MAX) then
1041 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' ' + _lc[TStrings_Locale(Cardinal(I_NET_DISC_NONE) + ev.data)], True);
1042 Result := -1;
1043 exit;
1044 end;
1045 else
1046 begin
1047 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' unknown ENet event ' + IntToStr(Ord(ev.kind)), True);
1048 result := -1;
1049 exit;
1050 end;
1051 end;
1052 if (freePacket) then begin freePacket := false; enet_packet_destroy(ev.packet); end;
1053 end;
1054 ProcessLoading();
1055 if g_Net_UserRequestExit() then
1056 begin
1057 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' user abort', True);
1058 Result := 1;
1059 exit;
1060 end;
1061 until false;
1062 finally
1063 if (freePacket) then enet_packet_destroy(ev.packet);
1064 end;
1065 end;
1068 // call this to cancel file transfer requested by `g_Net_RequestResFileInfo()`
1069 function g_Net_AbortResTransfer (var tf: TNetFileTransfer): Boolean;
1070 begin
1071 result := false;
1072 e_LogWritefln('aborting file transfer...', []);
1073 // send request
1074 trans_omsg.Clear();
1075 trans_omsg.Write(Byte(NTF_CLIENT_ABORT));
1076 result := ftransSendClientMsg(trans_omsg);
1077 if result then enet_host_flush(NetHost);
1078 end;
1081 // call this to start file transfer requested by `g_Net_RequestResFileInfo()`
1082 //
1083 // returns `false` on error or user abort
1084 // fills:
1085 // hash
1086 // size
1087 // chunkSize
1088 // returns:
1089 // <0 on error
1090 // 0 on success
1091 // 1 on user abort
1092 // 2 on server abort
1093 // for maps, first `tf.diskName` name will be map wad name, and `tf.hash`/`tf.size` will contain map info
1094 function g_Net_ReceiveResourceFile (resIndex: LongInt; var tf: TNetFileTransfer; strm: TStream): Integer;
1095 var
1096 ev: ENetEvent;
1097 rMsgId: Byte;
1098 Ptr: Pointer;
1099 msg: TMsg;
1100 freePacket: Boolean = false;
1101 ct, ett: Int64;
1102 status: cint;
1103 nextChunk: Integer = 0;
1104 chunkTotal: Integer;
1105 chunk: Integer;
1106 csize: Integer;
1107 buf: PChar = nil;
1108 resumed: Boolean;
1109 //stx: Int64;
1110 begin
1111 tf.resumed := false;
1112 e_LogWritefln('file `%s`, size=%d (%d)', [tf.diskName, Integer(strm.size), tf.size], TMsgType.Notify);
1113 // check if we should resume downloading
1114 resumed := (strm.size > tf.chunkSize) and (strm.size < tf.size);
1115 // send request
1116 trans_omsg.Clear();
1117 trans_omsg.Write(Byte(NTF_CLIENT_START));
1118 if resumed then chunk := strm.size div tf.chunkSize else chunk := 0;
1119 trans_omsg.Write(LongInt(chunk));
1120 if not ftransSendClientMsg(trans_omsg) then begin result := -1; exit; end;
1122 strm.Seek(chunk*tf.chunkSize, soFromBeginning);
1123 chunkTotal := (tf.size+tf.chunkSize-1) div tf.chunkSize;
1124 e_LogWritefln('receiving file `%s` (%d chunks)', [tf.diskName, chunkTotal], TMsgType.Notify);
1125 g_Game_SetLoadingText('downloading "'+ExtractFileName(tf.diskName)+'"', chunkTotal, False);
1126 tf.resumed := resumed;
1128 if (chunk > 0) then g_Game_StepLoading(chunk);
1129 nextChunk := chunk;
1131 // wait for reply data
1132 FillChar(ev, SizeOf(ev), 0);
1133 Result := -1;
1134 GetMem(buf, tf.chunkSize);
1135 try
1136 ett := getNewTimeoutEnd();
1137 repeat
1138 //stx := -GetTimerMS();
1139 status := enet_host_service(NetHost, @ev, 300);
1141 if (status < 0) then
1142 begin
1143 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' network error', True);
1144 Result := -1;
1145 exit;
1146 end;
1148 if (status <= 0) then
1149 begin
1150 // check for timeout
1151 ct := GetTimerMS();
1152 if (ct >= ett) then
1153 begin
1154 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' timeout reached', True);
1155 Result := -1;
1156 exit;
1157 end;
1158 end
1159 else
1160 begin
1161 // some event
1162 case ev.kind of
1163 ENET_EVENT_TYPE_RECEIVE:
1164 begin
1165 freePacket := true;
1166 if (ev.channelID <> NET_CHAN_DOWNLOAD_EX) then
1167 begin
1168 //e_LogWritefln('g_Net_Wait_Event: skip message from non-transfer channel', []);
1169 freePacket := false;
1170 g_Net_Client_HandlePacket(ev.packet, g_Net_ClientLightMsgHandler);
1171 if (g_Res_received_map_start < 0) then begin result := -666; exit; end;
1172 end
1173 else
1174 begin
1175 //stx := stx+GetTimerMS();
1176 //e_LogWritefln('g_Net_ReceiveResourceFile: stx=%d', [Integer(stx)]);
1177 //stx := -GetTimerMS();
1178 ett := getNewTimeoutEnd();
1179 if (ev.packet.dataLength < 1) then
1180 begin
1181 e_LogWritefln('g_Net_ReceiveResourceFile: invalid server packet (no data)', []);
1182 Result := -1;
1183 exit;
1184 end;
1185 Ptr := ev.packet^.data;
1186 rMsgId := Byte(Ptr^);
1187 if (rMsgId = NTF_SERVER_DONE) then
1188 begin
1189 e_LogWritefln('file transfer complete.', []);
1190 result := 0;
1191 exit;
1192 end
1193 else if (rMsgId = NTF_SERVER_CHUNK) then
1194 begin
1195 if not msg.Init(ev.packet^.data+1, ev.packet^.dataLength-1, True) then exit;
1196 chunk := msg.ReadLongInt();
1197 csize := msg.ReadLongInt();
1198 if (chunk <> nextChunk) then
1199 begin
1200 e_LogWritefln('received chunk %d, but expected chunk %d', [chunk, nextChunk]);
1201 Result := -1;
1202 exit;
1203 end;
1204 if (csize < 0) or (csize > tf.chunkSize) then
1205 begin
1206 e_LogWritefln('received chunk with size %d, but expected chunk size is %d', [csize, tf.chunkSize]);
1207 Result := -1;
1208 exit;
1209 end;
1210 //e_LogWritefln('got chunk #%d of #%d (csize=%d)', [chunk, (tf.size+tf.chunkSize-1) div tf.chunkSize, csize]);
1211 msg.ReadData(buf, csize);
1212 strm.WriteBuffer(buf^, csize);
1213 nextChunk := chunk+1;
1214 g_Game_StepLoading();
1215 // send ack
1216 trans_omsg.Clear();
1217 trans_omsg.Write(Byte(NTF_CLIENT_ACK));
1218 trans_omsg.Write(LongInt(chunk));
1219 if not ftransSendClientMsg(trans_omsg) then begin result := -1; exit; end;
1220 end
1221 else if (rMsgId = NTF_SERVER_ABORT) then
1222 begin
1223 e_LogWritefln('g_Net_ReceiveResourceFile: server aborted transfer', []);
1224 Result := 2;
1225 exit;
1226 end
1227 else
1228 begin
1229 e_LogWritefln('g_Net_ReceiveResourceFile: invalid server packet type', []);
1230 Result := -1;
1231 exit;
1232 end;
1233 //stx := stx+GetTimerMS();
1234 //e_LogWritefln('g_Net_ReceiveResourceFile: process stx=%d', [Integer(stx)]);
1235 end;
1236 end;
1237 ENET_EVENT_TYPE_DISCONNECT:
1238 begin
1239 if (ev.data <= NET_DISC_MAX) then
1240 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' ' + _lc[TStrings_Locale(Cardinal(I_NET_DISC_NONE) + ev.data)], True);
1241 Result := -1;
1242 exit;
1243 end;
1244 else
1245 begin
1246 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' unknown ENet event ' + IntToStr(Ord(ev.kind)), True);
1247 result := -1;
1248 exit;
1249 end;
1250 end;
1251 if (freePacket) then begin freePacket := false; enet_packet_destroy(ev.packet); end;
1252 end;
1253 ProcessLoading();
1254 if g_Net_UserRequestExit() then
1255 begin
1256 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' user abort', True);
1257 Result := 1;
1258 exit;
1259 end;
1260 until false;
1261 finally
1262 FreeMem(buf);
1263 if (freePacket) then enet_packet_destroy(ev.packet);
1264 end;
1265 end;
1268 //**************************************************************************
1269 //
1270 // common functions
1271 //
1272 //**************************************************************************
1274 function g_Net_FindSlot(): Integer;
1275 var
1276 I: Integer;
1277 F: Boolean;
1278 N, C: Integer;
1279 begin
1280 N := -1;
1281 F := False;
1282 C := 0;
1283 for I := Low(NetClients) to High(NetClients) do
1284 begin
1285 if NetClients[I].Used then
1286 Inc(C)
1287 else
1288 if not F then
1289 begin
1290 F := True;
1291 N := I;
1292 end;
1293 end;
1294 if C >= NetMaxClients then
1295 begin
1296 Result := -1;
1297 Exit;
1298 end;
1300 if not F then
1301 begin
1302 if (Length(NetClients) >= NetMaxClients) then
1303 N := -1
1304 else
1305 begin
1306 SetLength(NetClients, Length(NetClients) + 1);
1307 N := High(NetClients);
1308 end;
1309 end;
1311 if N >= 0 then
1312 begin
1313 NetClients[N].Used := True;
1314 NetClients[N].ID := N;
1315 NetClients[N].RequestedFullUpdate := False;
1316 NetClients[N].WaitForFirstSpawn := False;
1317 NetClients[N].RCONAuth := False;
1318 NetClients[N].Voted := False;
1319 NetClients[N].Player := 0;
1320 clearNetClientTransfers(NetClients[N]); // just in case
1321 end;
1323 Result := N;
1324 end;
1327 function g_Net_Init(): Boolean;
1328 var
1329 F: TextFile;
1330 IPstr: string;
1331 IP: LongWord;
1332 begin
1333 NetIn.Clear();
1334 NetOut.Clear();
1335 NetBuf[NET_UNRELIABLE].Clear();
1336 NetBuf[NET_RELIABLE].Clear();
1337 //SetLength(NetClients, 0);
1338 clearNetClients(true); // clear array
1339 NetPeer := nil;
1340 NetHost := nil;
1341 NetMyID := -1;
1342 NetPlrUID1 := -1;
1343 NetPlrUID2 := -1;
1344 NetAddr.port := 25666;
1345 SetLength(NetBannedHosts, 0);
1346 if FileExists(DataDir + BANLIST_FILENAME) then
1347 begin
1348 Assign(F, DataDir + BANLIST_FILENAME);
1349 Reset(F);
1350 while not EOF(F) do
1351 begin
1352 Readln(F, IPstr);
1353 if StrToIp(IPstr, IP) then
1354 g_Net_BanHost(IP);
1355 end;
1356 CloseFile(F);
1357 g_Net_SaveBanList();
1358 end;
1360 //Result := (enet_initialize() = 0);
1361 Result := enet_init_success;
1362 end;
1364 procedure g_Net_Flush();
1365 var
1366 T: Integer;
1367 P: pENetPacket;
1368 F, Chan: enet_uint32;
1369 I: Integer;
1370 begin
1371 F := 0;
1372 Chan := NET_CHAN_GAME;
1374 if NetMode = NET_SERVER then
1375 for T := NET_UNRELIABLE to NET_RELIABLE do
1376 begin
1377 if NetBuf[T].CurSize > 0 then
1378 begin
1379 P := enet_packet_create(NetBuf[T].Data, NetBuf[T].CurSize, F);
1380 if not Assigned(P) then continue;
1381 enet_host_broadcast(NetHost, Chan, P);
1382 NetBuf[T].Clear();
1383 end;
1385 for I := Low(NetClients) to High(NetClients) do
1386 begin
1387 if not NetClients[I].Used then continue;
1388 if NetClients[I].NetOut[T].CurSize <= 0 then continue;
1389 P := enet_packet_create(NetClients[I].NetOut[T].Data, NetClients[I].NetOut[T].CurSize, F);
1390 if not Assigned(P) then continue;
1391 enet_peer_send(NetClients[I].Peer, Chan, P);
1392 NetClients[I].NetOut[T].Clear();
1393 end;
1395 // next and last iteration is always RELIABLE
1396 F := LongWord(ENET_PACKET_FLAG_RELIABLE);
1397 Chan := NET_CHAN_IMPORTANT;
1398 end
1399 else if NetMode = NET_CLIENT then
1400 for T := NET_UNRELIABLE to NET_RELIABLE do
1401 begin
1402 if NetBuf[T].CurSize > 0 then
1403 begin
1404 P := enet_packet_create(NetBuf[T].Data, NetBuf[T].CurSize, F);
1405 if not Assigned(P) then continue;
1406 enet_peer_send(NetPeer, Chan, P);
1407 NetBuf[T].Clear();
1408 end;
1409 // next and last iteration is always RELIABLE
1410 F := LongWord(ENET_PACKET_FLAG_RELIABLE);
1411 Chan := NET_CHAN_IMPORTANT;
1412 end;
1413 end;
1415 procedure g_Net_Cleanup();
1416 begin
1417 NetIn.Clear();
1418 NetOut.Clear();
1419 NetBuf[NET_UNRELIABLE].Clear();
1420 NetBuf[NET_RELIABLE].Clear();
1422 //SetLength(NetClients, 0);
1423 clearNetClients(true); // clear array
1424 NetClientCount := 0;
1426 NetPeer := nil;
1427 NetHost := nil;
1428 g_Net_Slist_ServerClosed();
1429 NetMyID := -1;
1430 NetPlrUID1 := -1;
1431 NetPlrUID2 := -1;
1432 NetState := NET_STATE_NONE;
1434 NetPongSock := ENET_SOCKET_NULL;
1436 NetTimeToMaster := 0;
1437 NetTimeToUpdate := 0;
1438 NetTimeToReliable := 0;
1440 NetMode := NET_NONE;
1442 if NetPortThread <> NilThreadId then
1443 WaitForThreadTerminate(NetPortThread, 66666);
1445 NetPortThread := NilThreadId;
1446 g_Net_UnforwardPorts();
1448 if NetDump then
1449 g_Net_DumpEnd();
1450 end;
1452 procedure g_Net_Free();
1453 begin
1454 g_Net_Cleanup();
1456 //enet_deinitialize();
1457 NetInitDone := False;
1458 end;
1461 //**************************************************************************
1462 //
1463 // SERVER FUNCTIONS
1464 //
1465 //**************************************************************************
1467 function ForwardThread(Param: Pointer): PtrInt;
1468 begin
1469 Result := 0;
1470 if not g_Net_ForwardPorts() then Result := -1;
1471 end;
1473 function g_Net_Host(IPAddr: LongWord; Port: enet_uint16; MaxClients: Cardinal = 16): Boolean;
1474 begin
1475 if NetMode <> NET_NONE then
1476 begin
1477 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_INGAME]);
1478 Result := False;
1479 Exit;
1480 end;
1482 Result := True;
1484 g_Console_Add(_lc[I_NET_MSG] + Format(_lc[I_NET_MSG_HOST], [Port]));
1485 if not NetInitDone then
1486 begin
1487 if (not g_Net_Init()) then
1488 begin
1489 g_Console_Add(_lc[I_NET_MSG_FERROR] + _lc[I_NET_ERR_ENET]);
1490 Result := False;
1491 Exit;
1492 end
1493 else
1494 NetInitDone := True;
1495 end;
1497 NetAddr.host := IPAddr;
1498 NetAddr.port := Port;
1500 if NetForwardPorts then NetPortThread := BeginThread(ForwardThread);
1502 NetHost := enet_host_create(@NetAddr, NET_MAXCLIENTS, NET_CHANS, 0, 0);
1504 if (NetHost = nil) then
1505 begin
1506 g_Console_Add(_lc[I_NET_MSG_ERROR] + Format(_lc[I_NET_ERR_HOST], [Port]));
1507 Result := False;
1508 g_Net_Cleanup;
1509 Exit;
1510 end;
1512 NetPongSock := enet_socket_create(ENET_SOCKET_TYPE_DATAGRAM);
1513 if NetPongSock <> ENET_SOCKET_NULL then
1514 begin
1515 NetPongAddr.host := IPAddr;
1516 NetPongAddr.port := NET_PING_PORT;
1517 if enet_socket_bind(NetPongSock, @NetPongAddr) < 0 then
1518 begin
1519 enet_socket_destroy(NetPongSock);
1520 NetPongSock := ENET_SOCKET_NULL;
1521 end
1522 else
1523 enet_socket_set_option(NetPongSock, ENET_SOCKOPT_NONBLOCK, 1);
1524 end;
1526 NetMode := NET_SERVER;
1527 NetOut.Clear();
1528 NetBuf[NET_UNRELIABLE].Clear();
1529 NetBuf[NET_RELIABLE].Clear();
1531 if NetDump then
1532 g_Net_DumpStart();
1533 end;
1535 procedure g_Net_Host_Die();
1536 var
1537 I: Integer;
1538 begin
1539 if NetMode <> NET_SERVER then Exit;
1541 g_Console_Add(_lc[I_NET_MSG] + _lc[I_NET_MSG_HOST_DISCALL]);
1542 for I := 0 to High(NetClients) do
1543 if NetClients[I].Used then
1544 enet_peer_disconnect(NetClients[I].Peer, NET_DISC_DOWN);
1546 while enet_host_service(NetHost, @NetEvent, 1000) > 0 do
1547 if NetEvent.kind = ENET_EVENT_TYPE_RECEIVE then
1548 enet_packet_destroy(NetEvent.packet);
1550 for I := 0 to High(NetClients) do
1551 if NetClients[I].Used then
1552 begin
1553 FreeMemory(NetClients[I].Peer^.data);
1554 NetClients[I].Peer^.data := nil;
1555 enet_peer_reset(NetClients[I].Peer);
1556 NetClients[I].Peer := nil;
1557 NetClients[I].Used := False;
1558 NetClients[I].NetOut[NET_UNRELIABLE].Free();
1559 NetClients[I].NetOut[NET_RELIABLE].Free();
1560 end;
1562 clearNetClients(false); // don't clear array
1563 g_Net_Slist_ServerClosed();
1564 if NetPongSock <> ENET_SOCKET_NULL then
1565 enet_socket_destroy(NetPongSock);
1567 g_Console_Add(_lc[I_NET_MSG] + _lc[I_NET_MSG_HOST_DIE]);
1568 enet_host_destroy(NetHost);
1570 NetMode := NET_NONE;
1572 g_Net_Cleanup;
1573 e_WriteLog('NET: Server stopped', TMsgType.Notify);
1574 end;
1577 procedure g_Net_Host_Send(ID: Integer; Reliable: Boolean; Chan: Byte = NET_CHAN_GAME);
1578 var
1579 T: Integer;
1580 begin
1581 if (Reliable) then
1582 T := NET_RELIABLE
1583 else
1584 T := NET_UNRELIABLE;
1586 if (ID >= 0) then
1587 begin
1588 if ID > High(NetClients) then Exit;
1589 if NetClients[ID].Peer = nil then Exit;
1590 // write size first
1591 NetClients[ID].NetOut[T].Write(Integer(NetOut.CurSize));
1592 NetClients[ID].NetOut[T].Write(NetOut);
1593 end
1594 else
1595 begin
1596 // write size first
1597 NetBuf[T].Write(Integer(NetOut.CurSize));
1598 NetBuf[T].Write(NetOut);
1599 end;
1601 if NetDump then g_Net_DumpSendBuffer();
1602 NetOut.Clear();
1603 end;
1605 procedure g_Net_Host_CheckPings();
1606 var
1607 ClAddr: ENetAddress;
1608 Buf: ENetBuffer;
1609 Len: Integer;
1610 ClTime: Int64;
1611 Ping: array [0..9] of Byte;
1612 NPl: Byte;
1613 begin
1614 if NetPongSock = ENET_SOCKET_NULL then Exit;
1616 Buf.data := Addr(Ping[0]);
1617 Buf.dataLength := 2+8;
1619 Ping[0] := 0;
1621 Len := enet_socket_receive(NetPongSock, @ClAddr, @Buf, 1);
1622 if Len < 0 then Exit;
1624 if (Ping[0] = Ord('D')) and (Ping[1] = Ord('F')) then
1625 begin
1626 ClTime := Int64(Addr(Ping[2])^);
1628 NetOut.Clear();
1629 NetOut.Write(Byte(Ord('D')));
1630 NetOut.Write(Byte(Ord('F')));
1631 NetOut.Write(NetPort);
1632 NetOut.Write(ClTime);
1633 TMasterHost.writeInfo(NetOut);
1634 NPl := 0;
1635 if gPlayer1 <> nil then Inc(NPl);
1636 if gPlayer2 <> nil then Inc(NPl);
1637 NetOut.Write(NPl);
1638 NetOut.Write(gNumBots);
1640 Buf.data := NetOut.Data;
1641 Buf.dataLength := NetOut.CurSize;
1642 enet_socket_send(NetPongSock, @ClAddr, @Buf, 1);
1644 NetOut.Clear();
1645 end;
1646 end;
1649 function g_Net_Host_Update(): enet_size_t;
1650 var
1651 IP: string;
1652 Port: Word;
1653 ID: Integer;
1654 TC: pTNetClient;
1655 TP: TPlayer;
1656 begin
1657 IP := '';
1658 Result := 0;
1660 if NetUseMaster then g_Net_Slist_Pulse();
1661 g_Net_Host_CheckPings();
1663 while (enet_host_service(NetHost, @NetEvent, 0) > 0) do
1664 begin
1665 case (NetEvent.kind) of
1666 ENET_EVENT_TYPE_CONNECT:
1667 begin
1668 IP := IpToStr(NetEvent.Peer^.address.host);
1669 Port := NetEvent.Peer^.address.port;
1670 g_Console_Add(_lc[I_NET_MSG] +
1671 Format(_lc[I_NET_MSG_HOST_CONN], [IP, Port]));
1673 if (NetEvent.data <> NET_PROTOCOL_VER) then
1674 begin
1675 g_Console_Add(_lc[I_NET_MSG] + _lc[I_NET_MSG_HOST_REJECT] +
1676 _lc[I_NET_DISC_PROTOCOL]);
1677 NetEvent.peer^.data := GetMemory(SizeOf(Byte));
1678 Byte(NetEvent.peer^.data^) := 255;
1679 enet_peer_disconnect(NetEvent.peer, NET_DISC_PROTOCOL);
1680 enet_host_flush(NetHost);
1681 Exit;
1682 end;
1684 ID := g_Net_FindSlot();
1686 if ID < 0 then
1687 begin
1688 g_Console_Add(_lc[I_NET_MSG] + _lc[I_NET_MSG_HOST_REJECT] +
1689 _lc[I_NET_DISC_FULL]);
1690 NetEvent.Peer^.data := GetMemory(SizeOf(Byte));
1691 Byte(NetEvent.peer^.data^) := 255;
1692 enet_peer_disconnect(NetEvent.peer, NET_DISC_FULL);
1693 enet_host_flush(NetHost);
1694 Exit;
1695 end;
1697 NetClients[ID].Peer := NetEvent.peer;
1698 NetClients[ID].Peer^.data := GetMemory(SizeOf(Byte));
1699 Byte(NetClients[ID].Peer^.data^) := ID;
1700 NetClients[ID].State := NET_STATE_AUTH;
1701 NetClients[ID].RCONAuth := False;
1702 NetClients[ID].NetOut[NET_UNRELIABLE].Alloc(NET_BUFSIZE*2);
1703 NetClients[ID].NetOut[NET_RELIABLE].Alloc(NET_BUFSIZE*2);
1704 clearNetClientTransfers(NetClients[ID]); // just in case
1706 enet_peer_timeout(NetEvent.peer, ENET_PEER_TIMEOUT_LIMIT * 2, ENET_PEER_TIMEOUT_MINIMUM * 2, ENET_PEER_TIMEOUT_MAXIMUM * 2);
1708 Inc(NetClientCount);
1709 g_Console_Add(_lc[I_NET_MSG] + Format(_lc[I_NET_MSG_HOST_ADD], [ID]));
1710 end;
1712 ENET_EVENT_TYPE_RECEIVE:
1713 begin
1714 //e_LogWritefln('RECEIVE: chan=%u', [NetEvent.channelID]);
1715 if (NetEvent.channelID = NET_CHAN_DOWNLOAD_EX) then
1716 begin
1717 ProcessDownloadExPacket();
1718 end
1719 else
1720 begin
1721 ID := Byte(NetEvent.peer^.data^);
1722 if ID > High(NetClients) then Exit;
1723 TC := @NetClients[ID];
1725 if NetDump then g_Net_DumpRecvBuffer(NetEvent.packet^.data, NetEvent.packet^.dataLength);
1726 g_Net_Host_HandlePacket(TC, NetEvent.packet, g_Net_HostMsgHandler);
1727 end;
1728 end;
1730 ENET_EVENT_TYPE_DISCONNECT:
1731 begin
1732 ID := Byte(NetEvent.peer^.data^);
1733 if ID > High(NetClients) then Exit;
1734 clearNetClient(NetClients[ID]);
1735 TC := @NetClients[ID];
1736 if TC = nil then Exit;
1738 if not (TC^.Used) then Exit;
1740 TP := g_Player_Get(TC^.Player);
1742 if TP <> nil then
1743 begin
1744 TP.Lives := 0;
1745 TP.Kill(K_SIMPLEKILL, 0, HIT_DISCON);
1746 g_Console_Add(Format(_lc[I_PLAYER_LEAVE], [TP.Name]), True);
1747 e_WriteLog('NET: Client ' + TP.Name + ' [' + IntToStr(ID) + '] disconnected.', TMsgType.Notify);
1748 g_Player_Remove(TP.UID);
1749 end;
1751 TC^.Used := False;
1752 TC^.State := NET_STATE_NONE;
1753 TC^.Peer := nil;
1754 TC^.Player := 0;
1755 TC^.RequestedFullUpdate := False;
1756 TC^.WaitForFirstSpawn := False;
1757 TC^.NetOut[NET_UNRELIABLE].Free();
1758 TC^.NetOut[NET_RELIABLE].Free();
1760 FreeMemory(NetEvent.peer^.data);
1761 NetEvent.peer^.data := nil;
1762 g_Console_Add(_lc[I_NET_MSG] + Format(_lc[I_NET_MSG_HOST_DISC], [ID]));
1763 Dec(NetClientCount);
1765 if NetUseMaster then g_Net_Slist_ServerPlayerLeaves();
1766 end;
1767 end;
1768 end;
1769 end;
1772 //**************************************************************************
1773 //
1774 // CLIENT FUNCTIONS
1775 //
1776 //**************************************************************************
1778 procedure g_Net_Disconnect(Forced: Boolean = False);
1779 begin
1780 if NetMode <> NET_CLIENT then Exit;
1781 if (NetHost = nil) or (NetPeer = nil) then Exit;
1783 if not Forced then
1784 begin
1785 enet_peer_disconnect(NetPeer, NET_DISC_NONE);
1787 while (enet_host_service(NetHost, @NetEvent, 1500) > 0) do
1788 begin
1789 if (NetEvent.kind = ENET_EVENT_TYPE_DISCONNECT) then
1790 begin
1791 NetPeer := nil;
1792 break;
1793 end;
1795 if (NetEvent.kind = ENET_EVENT_TYPE_RECEIVE) then
1796 enet_packet_destroy(NetEvent.packet);
1797 end;
1799 if NetPeer <> nil then
1800 begin
1801 enet_peer_reset(NetPeer);
1802 NetPeer := nil;
1803 end;
1804 end
1805 else
1806 begin
1807 e_WriteLog('NET: Kicked from server: ' + IntToStr(NetEvent.data), TMsgType.Notify);
1808 if (NetEvent.data <= NET_DISC_MAX) then
1809 g_Console_Add(_lc[I_NET_MSG] + _lc[I_NET_MSG_KICK] +
1810 _lc[TStrings_Locale(Cardinal(I_NET_DISC_NONE) + NetEvent.data)], True);
1811 end;
1813 if NetHost <> nil then
1814 begin
1815 enet_host_destroy(NetHost);
1816 NetHost := nil;
1817 end;
1818 g_Console_Add(_lc[I_NET_MSG] + _lc[I_NET_MSG_CLIENT_DISC]);
1820 g_Net_Cleanup;
1821 e_WriteLog('NET: Disconnected', TMsgType.Notify);
1822 end;
1824 procedure g_Net_Client_Send(Reliable: Boolean; Chan: Byte = NET_CHAN_GAME);
1825 var
1826 T: Integer;
1827 begin
1828 if (Reliable) then
1829 T := NET_RELIABLE
1830 else
1831 T := NET_UNRELIABLE;
1833 // write size first
1834 NetBuf[T].Write(Integer(NetOut.CurSize));
1835 NetBuf[T].Write(NetOut);
1837 if NetDump then g_Net_DumpSendBuffer();
1838 NetOut.Clear();
1839 g_Net_Flush(); // FIXME: for now, send immediately
1840 end;
1842 function g_Net_Client_Update(): enet_size_t;
1843 begin
1844 Result := 0;
1845 while (enet_host_service(NetHost, @NetEvent, 0) > 0) do
1846 begin
1847 case NetEvent.kind of
1848 ENET_EVENT_TYPE_RECEIVE:
1849 begin
1850 if (NetEvent.channelID = NET_CHAN_DOWNLOAD_EX) then continue; // ignore all download packets, they're processed by separate code
1851 if NetDump then g_Net_DumpRecvBuffer(NetEvent.packet^.data, NetEvent.packet^.dataLength);
1852 g_Net_Client_HandlePacket(NetEvent.packet, g_Net_ClientMsgHandler);
1853 end;
1855 ENET_EVENT_TYPE_DISCONNECT:
1856 begin
1857 g_Net_Disconnect(True);
1858 Result := 1;
1859 Exit;
1860 end;
1861 end;
1862 end
1863 end;
1865 function g_Net_Client_UpdateWhileLoading(): enet_size_t;
1866 begin
1867 Result := 0;
1868 while (enet_host_service(NetHost, @NetEvent, 0) > 0) do
1869 begin
1870 case NetEvent.kind of
1871 ENET_EVENT_TYPE_RECEIVE:
1872 begin
1873 if (NetEvent.channelID = NET_CHAN_DOWNLOAD_EX) then continue; // ignore all download packets, they're processed by separate code
1874 if NetDump then g_Net_DumpRecvBuffer(NetEvent.packet^.data, NetEvent.packet^.dataLength);
1875 g_Net_Client_HandlePacket(NetEvent.packet, g_Net_ClientLightMsgHandler);
1876 end;
1878 ENET_EVENT_TYPE_DISCONNECT:
1879 begin
1880 g_Net_Disconnect(True);
1881 Result := 1;
1882 Exit;
1883 end;
1884 end;
1885 end;
1886 g_Net_Flush();
1887 end;
1889 function g_Net_Connect(IP: string; Port: enet_uint16): Boolean;
1890 var
1891 OuterLoop: Boolean;
1892 TimeoutTime, T: Int64;
1893 begin
1894 if NetMode <> NET_NONE then
1895 begin
1896 g_Console_Add(_lc[I_NET_MSG] + _lc[I_NET_ERR_INGAME], True);
1897 Result := False;
1898 Exit;
1899 end;
1901 Result := True;
1903 g_Console_Add(_lc[I_NET_MSG] + Format(_lc[I_NET_MSG_CLIENT_CONN],
1904 [IP, Port]));
1905 if not NetInitDone then
1906 begin
1907 if (not g_Net_Init()) then
1908 begin
1909 g_Console_Add(_lc[I_NET_MSG_FERROR] + _lc[I_NET_ERR_ENET], True);
1910 Result := False;
1911 Exit;
1912 end
1913 else
1914 NetInitDone := True;
1915 end;
1917 NetHost := enet_host_create(nil, 1, NET_CHANS, 0, 0);
1919 if (NetHost = nil) then
1920 begin
1921 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CLIENT], True);
1922 g_Net_Cleanup;
1923 Result := False;
1924 Exit;
1925 end;
1927 enet_address_set_host(@NetAddr, PChar(Addr(IP[1])));
1928 NetAddr.port := Port;
1930 NetPeer := enet_host_connect(NetHost, @NetAddr, NET_CHANS, NET_PROTOCOL_VER);
1932 if (NetPeer = nil) then
1933 begin
1934 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CLIENT], True);
1935 enet_host_destroy(NetHost);
1936 g_Net_Cleanup;
1937 Result := False;
1938 Exit;
1939 end;
1941 // предупредить что ждем слишком долго через N секунд
1942 TimeoutTime := sys_GetTicks() + NET_CONNECT_TIMEOUT;
1944 OuterLoop := True;
1945 while OuterLoop do
1946 begin
1947 while (enet_host_service(NetHost, @NetEvent, 0) > 0) do
1948 begin
1949 if (NetEvent.kind = ENET_EVENT_TYPE_CONNECT) then
1950 begin
1951 g_Console_Add(_lc[I_NET_MSG] + _lc[I_NET_MSG_CLIENT_DONE]);
1952 NetMode := NET_CLIENT;
1953 NetOut.Clear();
1954 enet_peer_timeout(NetPeer, ENET_PEER_TIMEOUT_LIMIT * 2, ENET_PEER_TIMEOUT_MINIMUM * 2, ENET_PEER_TIMEOUT_MAXIMUM * 2);
1955 NetClientIP := IP;
1956 NetClientPort := Port;
1957 if NetDump then
1958 g_Net_DumpStart();
1959 Exit;
1960 end;
1961 end;
1963 T := sys_GetTicks();
1964 if T > TimeoutTime then
1965 begin
1966 TimeoutTime := T + NET_CONNECT_TIMEOUT * 100; // одного предупреждения хватит
1967 g_Console_Add(_lc[I_NET_MSG_TIMEOUT_WARN], True);
1968 g_Console_Add(Format(_lc[I_NET_MSG_PORTS], [Integer(Port), Integer(NET_PING_PORT)]), True);
1969 end;
1971 ProcessLoading(true);
1973 if e_KeyPressed(IK_SPACE) or e_KeyPressed(IK_ESCAPE) or e_KeyPressed(VK_ESCAPE) or
1974 e_KeyPressed(JOY0_JUMP) or e_KeyPressed(JOY1_JUMP) or e_KeyPressed(JOY2_JUMP) or e_KeyPressed(JOY3_JUMP) then
1975 OuterLoop := False;
1976 end;
1978 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_TIMEOUT], True);
1979 g_Console_Add(Format(_lc[I_NET_MSG_PORTS], [Integer(Port), Integer(NET_PING_PORT)]), True);
1980 if NetPeer <> nil then enet_peer_reset(NetPeer);
1981 if NetHost <> nil then
1982 begin
1983 enet_host_destroy(NetHost);
1984 NetHost := nil;
1985 end;
1986 g_Net_Cleanup();
1987 Result := False;
1988 end;
1990 function IpToStr(IP: LongWord): string;
1991 var
1992 Ptr: Pointer;
1993 begin
1994 Ptr := Addr(IP);
1995 Result := IntToStr(PByte(Ptr + 0)^) + '.';
1996 Result := Result + IntToStr(PByte(Ptr + 1)^) + '.';
1997 Result := Result + IntToStr(PByte(Ptr + 2)^) + '.';
1998 Result := Result + IntToStr(PByte(Ptr + 3)^);
1999 end;
2001 function StrToIp(IPstr: string; var IP: LongWord): Boolean;
2002 var
2003 EAddr: ENetAddress;
2004 begin
2005 Result := enet_address_set_host(@EAddr, PChar(@IPstr[1])) = 0;
2006 IP := EAddr.host;
2007 end;
2009 function g_Net_Client_ByName(Name: string): pTNetClient;
2010 var
2011 a: Integer;
2012 pl: TPlayer;
2013 begin
2014 Result := nil;
2015 for a := Low(NetClients) to High(NetClients) do
2016 if (NetClients[a].Used) and (NetClients[a].State = NET_STATE_GAME) then
2017 begin
2018 pl := g_Player_Get(NetClients[a].Player);
2019 if pl = nil then continue;
2020 if Copy(LowerCase(pl.Name), 1, Length(Name)) <> LowerCase(Name) then continue;
2021 if NetClients[a].Peer <> nil then
2022 begin
2023 Result := @NetClients[a];
2024 Exit;
2025 end;
2026 end;
2027 end;
2029 function g_Net_Client_ByPlayer(PID: Word): pTNetClient;
2030 var
2031 a: Integer;
2032 begin
2033 Result := nil;
2034 for a := Low(NetClients) to High(NetClients) do
2035 if (NetClients[a].Used) and (NetClients[a].State = NET_STATE_GAME) then
2036 if NetClients[a].Player = PID then
2037 begin
2038 Result := @NetClients[a];
2039 Exit;
2040 end;
2041 end;
2043 function g_Net_ClientName_ByID(ID: Integer): string;
2044 var
2045 a: Integer;
2046 pl: TPlayer;
2047 begin
2048 Result := '';
2049 if ID = NET_EVERYONE then
2050 Exit;
2051 for a := Low(NetClients) to High(NetClients) do
2052 if (NetClients[a].ID = ID) and (NetClients[a].Used) and (NetClients[a].State = NET_STATE_GAME) then
2053 begin
2054 pl := g_Player_Get(NetClients[a].Player);
2055 if pl = nil then Exit;
2056 Result := pl.Name;
2057 end;
2058 end;
2060 procedure g_Net_SendData(Data: AByte; peer: pENetPeer; Reliable: Boolean; Chan: Byte = NET_CHAN_DOWNLOAD);
2061 var
2062 P: pENetPacket;
2063 F: enet_uint32;
2064 dataLength: Cardinal;
2065 begin
2066 dataLength := Length(Data);
2068 if (Reliable) then
2069 F := LongWord(ENET_PACKET_FLAG_RELIABLE)
2070 else
2071 F := 0;
2073 if (peer <> nil) then
2074 begin
2075 P := enet_packet_create(@Data[0], dataLength, F);
2076 if not Assigned(P) then Exit;
2077 enet_peer_send(peer, Chan, P);
2078 end
2079 else
2080 begin
2081 P := enet_packet_create(@Data[0], dataLength, F);
2082 if not Assigned(P) then Exit;
2083 enet_host_broadcast(NetHost, Chan, P);
2084 end;
2086 enet_host_flush(NetHost);
2087 end;
2089 function g_Net_IsHostBanned(IP: LongWord; Perm: Boolean = False): Boolean;
2090 var
2091 I: Integer;
2092 begin
2093 Result := False;
2094 if NetBannedHosts = nil then
2095 Exit;
2096 for I := 0 to High(NetBannedHosts) do
2097 if (NetBannedHosts[I].IP = IP) and ((not Perm) or (NetBannedHosts[I].Perm)) then
2098 begin
2099 Result := True;
2100 break;
2101 end;
2102 end;
2104 procedure g_Net_BanHost(IP: LongWord; Perm: Boolean = True); overload;
2105 var
2106 I, P: Integer;
2107 begin
2108 if IP = 0 then
2109 Exit;
2110 if g_Net_IsHostBanned(IP, Perm) then
2111 Exit;
2113 P := -1;
2114 for I := Low(NetBannedHosts) to High(NetBannedHosts) do
2115 if NetBannedHosts[I].IP = 0 then
2116 begin
2117 P := I;
2118 break;
2119 end;
2121 if P < 0 then
2122 begin
2123 SetLength(NetBannedHosts, Length(NetBannedHosts) + 1);
2124 P := High(NetBannedHosts);
2125 end;
2127 NetBannedHosts[P].IP := IP;
2128 NetBannedHosts[P].Perm := Perm;
2129 end;
2131 procedure g_Net_BanHost(IP: string; Perm: Boolean = True); overload;
2132 var
2133 a: LongWord;
2134 b: Boolean;
2135 begin
2136 b := StrToIp(IP, a);
2137 if b then
2138 g_Net_BanHost(a, Perm);
2139 end;
2141 procedure g_Net_UnbanNonPermHosts();
2142 var
2143 I: Integer;
2144 begin
2145 if NetBannedHosts = nil then
2146 Exit;
2147 for I := Low(NetBannedHosts) to High(NetBannedHosts) do
2148 if (NetBannedHosts[I].IP > 0) and not NetBannedHosts[I].Perm then
2149 begin
2150 NetBannedHosts[I].IP := 0;
2151 NetBannedHosts[I].Perm := True;
2152 end;
2153 end;
2155 function g_Net_UnbanHost(IP: string): Boolean; overload;
2156 var
2157 a: LongWord;
2158 begin
2159 Result := StrToIp(IP, a);
2160 if Result then
2161 Result := g_Net_UnbanHost(a);
2162 end;
2164 function g_Net_UnbanHost(IP: LongWord): Boolean; overload;
2165 var
2166 I: Integer;
2167 begin
2168 Result := False;
2169 if IP = 0 then
2170 Exit;
2171 if NetBannedHosts = nil then
2172 Exit;
2173 for I := 0 to High(NetBannedHosts) do
2174 if NetBannedHosts[I].IP = IP then
2175 begin
2176 NetBannedHosts[I].IP := 0;
2177 NetBannedHosts[I].Perm := True;
2178 Result := True;
2179 // no break here to clear all bans of this host, perm and non-perm
2180 end;
2181 end;
2183 procedure g_Net_SaveBanList();
2184 var
2185 F: TextFile;
2186 I: Integer;
2187 begin
2188 Assign(F, DataDir + BANLIST_FILENAME);
2189 Rewrite(F);
2190 if NetBannedHosts <> nil then
2191 for I := 0 to High(NetBannedHosts) do
2192 if NetBannedHosts[I].Perm and (NetBannedHosts[I].IP > 0) then
2193 Writeln(F, IpToStr(NetBannedHosts[I].IP));
2194 CloseFile(F);
2195 end;
2197 procedure g_Net_DumpStart();
2198 begin
2199 if NetMode = NET_SERVER then
2200 NetDumpFile := createDiskFile(NETDUMP_FILENAME + '_server')
2201 else
2202 NetDumpFile := createDiskFile(NETDUMP_FILENAME + '_client');
2203 end;
2205 procedure g_Net_DumpSendBuffer();
2206 begin
2207 writeInt(NetDumpFile, gTime);
2208 writeInt(NetDumpFile, LongWord(NetOut.CurSize));
2209 writeInt(NetDumpFile, Byte(1));
2210 NetDumpFile.WriteBuffer(NetOut.Data^, NetOut.CurSize);
2211 end;
2213 procedure g_Net_DumpRecvBuffer(Buf: penet_uint8; Len: LongWord);
2214 begin
2215 if (Buf = nil) or (Len = 0) then Exit;
2216 writeInt(NetDumpFile, gTime);
2217 writeInt(NetDumpFile, Len);
2218 writeInt(NetDumpFile, Byte(0));
2219 NetDumpFile.WriteBuffer(Buf^, Len);
2220 end;
2222 procedure g_Net_DumpEnd();
2223 begin
2224 NetDumpFile.Free();
2225 NetDumpFile := nil;
2226 end;
2228 function g_Net_ForwardPorts(ForwardPongPort: Boolean = True): Boolean;
2229 {$IFDEF USE_MINIUPNPC}
2230 var
2231 DevList: PUPNPDev;
2232 Urls: TUPNPUrls;
2233 Data: TIGDDatas;
2234 LanAddr: array [0..255] of Char;
2235 StrPort: AnsiString;
2236 Err, I: Integer;
2237 begin
2238 Result := False;
2240 if NetPortForwarded = NetPort then
2241 begin
2242 Result := True;
2243 exit;
2244 end;
2246 NetPongForwarded := False;
2247 NetPortForwarded := 0;
2249 DevList := upnpDiscover(1000, nil, nil, 0, 0, 2, Addr(Err));
2250 if DevList = nil then
2251 begin
2252 conwritefln('port forwarding failed: upnpDiscover() failed: %d', [Err]);
2253 exit;
2254 end;
2256 I := UPNP_GetValidIGD(DevList, @Urls, @Data, Addr(LanAddr[0]), 256);
2258 if I = 0 then
2259 begin
2260 conwriteln('port forwarding failed: could not find an IGD device on this LAN');
2261 FreeUPNPDevList(DevList);
2262 FreeUPNPUrls(@Urls);
2263 exit;
2264 end;
2266 StrPort := IntToStr(NetPort);
2267 I := UPNP_AddPortMapping(
2268 Urls.controlURL, Addr(data.first.servicetype[1]),
2269 PChar(StrPort), PChar(StrPort), Addr(LanAddr[0]), PChar('D2DF'),
2270 PChar('UDP'), nil, PChar('0')
2271 );
2273 if I <> 0 then
2274 begin
2275 conwritefln('forwarding port %d failed: error %d', [NetPort, I]);
2276 FreeUPNPDevList(DevList);
2277 FreeUPNPUrls(@Urls);
2278 exit;
2279 end;
2281 if ForwardPongPort then
2282 begin
2283 StrPort := IntToStr(NET_PING_PORT);
2284 I := UPNP_AddPortMapping(
2285 Urls.controlURL, Addr(data.first.servicetype[1]),
2286 PChar(StrPort), PChar(StrPort), Addr(LanAddr[0]), PChar('D2DF'),
2287 PChar('UDP'), nil, PChar('0')
2288 );
2290 if I <> 0 then
2291 begin
2292 conwritefln('forwarding port %d failed: error %d', [NetPort + 1, I]);
2293 NetPongForwarded := False;
2294 end
2295 else
2296 begin
2297 conwritefln('forwarded port %d successfully', [NetPort + 1]);
2298 NetPongForwarded := True;
2299 end;
2300 end;
2302 conwritefln('forwarded port %d successfully', [NetPort]);
2303 NetIGDControl := AnsiString(Urls.controlURL);
2304 NetIGDService := data.first.servicetype;
2305 NetPortForwarded := NetPort;
2307 FreeUPNPDevList(DevList);
2308 FreeUPNPUrls(@Urls);
2309 Result := True;
2310 end;
2311 {$ELSE}
2312 begin
2313 Result := False;
2314 end;
2315 {$ENDIF}
2317 procedure g_Net_UnforwardPorts();
2318 {$IFDEF USE_MINIUPNPC}
2319 var
2320 I: Integer;
2321 StrPort: AnsiString;
2322 begin
2323 if NetPortForwarded = 0 then Exit;
2325 conwriteln('unforwarding ports...');
2327 StrPort := IntToStr(NetPortForwarded);
2328 I := UPNP_DeletePortMapping(
2329 PChar(NetIGDControl), Addr(NetIGDService[1]),
2330 PChar(StrPort), PChar('UDP'), nil
2331 );
2332 conwritefln(' port %d: %d', [NetPortForwarded, I]);
2334 if NetPongForwarded then
2335 begin
2336 NetPongForwarded := False;
2337 StrPort := IntToStr(NetPortForwarded + 1);
2338 I := UPNP_DeletePortMapping(
2339 PChar(NetIGDControl), Addr(NetIGDService[1]),
2340 PChar(StrPort), PChar('UDP'), nil
2341 );
2342 conwritefln(' port %d: %d', [NetPortForwarded + 1, I]);
2343 end;
2345 NetPortForwarded := 0;
2346 end;
2347 {$ELSE}
2348 begin
2349 end;
2350 {$ENDIF}
2353 initialization
2354 conRegVar('cl_downloadtimeout', @g_Net_DownloadTimeout, 0.0, 1000000.0, '', 'timeout in seconds, 0 to disable it');
2355 SetLength(NetClients, 0);
2356 g_Net_DownloadTimeout := 60;
2357 NetIn.Alloc(NET_BUFSIZE);
2358 NetOut.Alloc(NET_BUFSIZE);
2359 NetBuf[NET_UNRELIABLE].Alloc(NET_BUFSIZE*2);
2360 NetBuf[NET_RELIABLE].Alloc(NET_BUFSIZE*2);
2361 trans_omsg.Alloc(NET_BUFSIZE);
2362 finalization
2363 NetIn.Free();
2364 NetOut.Free();
2365 NetBuf[NET_UNRELIABLE].Free();
2366 NetBuf[NET_RELIABLE].Free();
2367 end.