1 (* Copyright (C) Doom 2D: Forever Developers
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.
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.
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/>.
15 {$INCLUDE ../shared/a_modes.inc}
21 e_log
, e_msg
, ENet
, Classes
, md5
, MAPDEF
{$IFDEF USE_MINIUPNPC}, miniupnpc
;{$ELSE};{$ENDIF}
24 NET_PROTOCOL_VER
= 182;
30 NET_CHAN_IMPORTANT
= 1;
33 NET_CHAN_PLAYERPOS
= 4;
35 NET_CHAN_MONSTERPOS
= 6;
36 NET_CHAN_LARGEDATA
= 7;
38 NET_CHAN_DOWNLOAD
= 9;
40 NET_CHAN_DOWNLOAD_EX
= 11;
47 NET_PING_PORT
= $DF2D;
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;
70 NET_CONNECT_TIMEOUT
= 1000 * 10;
72 BANLIST_FILENAME
= 'banlist.txt';
73 NETDUMP_FILENAME
= 'netdump';
75 {$IF DEFINED(FREEBSD) OR DEFINED(DARWIN)}
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
88 TNetMapResourceInfoArray
= array of TNetMapResourceInfo
;
90 TNetFileTransfer
= record
94 size
: Integer; // file size in bytes
96 lastSentChunk
: Integer;
97 lastAckChunk
: Integer;
98 lastAckTime
: Int64; // msecs; if not "in progress", we're waiting for the first ack
100 diskBuffer
: PChar; // of `chunkSize` bytes
110 RequestedFullUpdate
: Boolean;
111 WaitForFirstSpawn
: Boolean; // set to `true` in server, used to spawn a player on first full state request
114 Transfer
: TNetFileTransfer
; // only one transfer may be active
115 NetOut
: array [0..1] of TMsg
;
121 pTNetClient
= ^TNetClient
;
123 AByte
= array of Byte;
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;
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;
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
;
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 ();
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.
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
,
266 FILE_CHUNK_SIZE
= 8192;
269 enet_init_success
: Boolean = false;
270 g_Net_DownloadTimeout
: Single;
274 function g_Net_IsNetworkAvailable (): Boolean;
276 result
:= enet_init_success
;
279 procedure g_Net_InitLowLevel ();
281 if enet_init_success
then raise Exception
.Create('wuta?!');
282 enet_init_success
:= (enet_initialize() = 0);
285 procedure g_Net_DeinitLowLevel ();
287 if enet_init_success
then
290 enet_init_success
:= false;
295 //**************************************************************************
299 //**************************************************************************
301 procedure clearNetClientTransfers (var nc
: TNetClient
);
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;
311 procedure clearNetClient (var nc
: TNetClient
);
313 clearNetClientTransfers(nc
);
317 procedure clearNetClients (clearArray
: Boolean);
321 for f
:= Low(NetClients
) to High(NetClients
) do clearNetClient(NetClients
[f
]);
322 if (clearArray
) then SetLength(NetClients
, 0);
326 function g_Net_UserRequestExit (): Boolean;
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
)
338 //**************************************************************************
340 // file transfer declaraions and host packet processor
342 //**************************************************************************
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
);
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();
370 // send file transfer message from server to client
371 function ftransSendServerMsg (var nc
: TNetClient
; var m
: TMsg
): Boolean;
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;
384 // send file transfer message from client to server
385 function ftransSendClientMsg (var m
: TMsg
): Boolean;
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
;
399 procedure ProcessChunkSend (var nc
: TNetClient
);
401 tf
: ^TNetFileTransfer
;
407 if (tf
.stream
= nil) then exit
;
409 // arbitrary timeout number
410 if (ct
-tf
.lastAckTime
>= 5000) then
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
430 if (tf
.lastSentChunk
= chunks
) then
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
);
440 trans_omsg
.Write(Byte(NTF_SERVER_CHUNK
));
441 trans_omsg
.Write(LongInt(tf
.lastSentChunk
));
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
449 tf
.stream
.Seek(tf
.lastSentChunk
*tf
.chunkSize
, soFromBeginning
);
450 tf
.stream
.ReadBuffer(tf
.diskBuffer
^, rd
);
451 trans_omsg
.WriteData(tf
.diskBuffer
, rd
);
458 ftransSendServerMsg(nc
, trans_omsg
);
462 // server file transfer packet processor
463 // received packet is in `NetEvent`
464 procedure ProcessDownloadExPacket ();
471 tf
: ^TNetFileTransfer
;
481 // find client index by peer
482 for f
:= Low(NetClients
) to High(NetClients
) do
484 if (not NetClients
[f
].Used
) then continue
;
485 if (NetClients
[f
].Peer
= NetEvent
.peer
) then
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
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]);
508 NTF_CLIENT_FILE_REQUEST
: // file request
510 if (tf
.stream
<> nil) then
515 if (NetEvent
.packet
^.dataLength
< 2) then
520 // new transfer request; build packet
521 if not msg
.Init(NetEvent
.packet
^.data
+1, NetEvent
.packet
^.dataLength
-1, True) then
526 // get resource index
527 ridx
:= msg
.ReadLongInt();
528 if (ridx
< -1) or (ridx
>= length(gExternalResources
)) then
530 e_LogWritefln('Invalid resource index %d', [ridx
], TMsgType
.Warning
);
534 if (ridx
< 0) then fname
:= MapsDir
+gGameSettings
.WAD
else fname
:= {GameDir+'/wads/'+}gExternalResources
[ridx
].diskName
;
535 if (length(fname
) = 0) then
537 e_WriteLog('Invalid filename: '+fname
, TMsgType
.Warning
);
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
545 e_LogWritefln('NETWORK: file "%s" not found!', [fname
], TMsgType
.Fatal
);
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
);
555 tf
.stream
:= openDiskFileRO(tf
.diskName
);
559 if (tf
.stream
= nil) then
561 e_WriteLog(Format('NETWORK: file "%s" not found!', [fname
]), TMsgType
.Fatal
);
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
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
;
582 NTF_CLIENT_ABORT
: // do not send requested file, or abort current transfer
584 e_LogWritefln('client #%d aborted file transfer', [nc
.ID
]);
585 clearNetClientTransfers(nc
^);
587 NTF_CLIENT_START
: // start transfer; client may resume download by sending non-zero starting chunk
589 if not Assigned(tf
.stream
) then
594 if (tf
.lastSentChunk
<> -1) or (tf
.lastAckChunk
<> -1) or (tf
.inProgress
) then
596 // double ack, get lost
600 if (NetEvent
.packet
^.dataLength
< 2) then
606 if not msg
.Init(NetEvent
.packet
^.data
+1, NetEvent
.packet
^.dataLength
-1, True) then
611 chunk
:= msg
.ReadLongInt();
612 if (chunk
< 0) or (chunk
> (tf
.size
+tf
.chunkSize
-1) div tf
.chunkSize
) then
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
^);
624 NTF_CLIENT_ACK
: // chunk ack; chunk number follows
626 if not Assigned(tf
.stream
) then
631 if (tf
.lastSentChunk
< 0) or (not tf
.inProgress
) then
633 // double ack, get lost
637 if (NetEvent
.packet
^.dataLength
< 2) then
643 if not msg
.Init(NetEvent
.packet
^.data
+1, NetEvent
.packet
^.dataLength
-1, True) then
648 chunk
:= msg
.ReadLongInt();
649 if (chunk
< 0) or (chunk
> (tf
.size
+tf
.chunkSize
-1) div tf
.chunkSize
) then
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
^);
660 NTF_CLIENT_MAP_REQUEST
:
662 e_LogWritefln('client #%d requested map info', [nc
.ID
]);
664 dfn
:= findDiskWad(MapsDir
+gGameSettings
.WAD
);
665 if (dfn
= '') then dfn
:= '!wad_not_found!.wad'; //FIXME
666 //md5 := MD5File(dfn);
668 if (not GetDiskFileInfo(dfn
, fi
)) then
670 e_LogWritefln('client #%d requested map info, but i cannot get file info', [nc
.ID
]);
676 st := openDiskFileRO(dfn);
677 if not assigned(st) then exit; //wtf?!
682 trans_omsg
.Write(Byte(NTF_SERVER_MAP_INFO
));
684 trans_omsg
.Write(gGameSettings
.WAD
);
686 trans_omsg
.Write(md5
);
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
695 //trans_omsg.Write(ExtractFileName(gExternalResources[f])); // GameDir+'/wads/'+ResList.Strings[i]
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
));
703 if not ftransSendServerMsg(nc
^, trans_omsg
) then exit
;
714 //**************************************************************************
716 // file transfer crap (both client and server)
718 //**************************************************************************
720 function getNewTimeoutEnd (): Int64;
722 result
:= GetTimerMS();
723 if (g_Net_DownloadTimeout
<= 0) then
725 result
:= result
+1000*60*3; // 3 minutes
729 result
:= result
+trunc(g_Net_DownloadTimeout
*1000);
734 // send map request to server, and wait for "map info" server reply
736 // returns `false` on error or user abort
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
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;
755 freePacket
: Boolean = false;
760 ri
: ^TNetMapResourceInfo
;
762 SetLength(resList
, 0);
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);
772 ett
:= getNewTimeoutEnd();
774 status
:= enet_host_service(NetHost
, @ev
, 300);
778 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' network error', True);
783 if (status
<= 0) then
789 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' timeout reached', True);
798 ENET_EVENT_TYPE_RECEIVE
:
801 if (ev
.channelID
<> NET_CHAN_DOWNLOAD_EX
) then
803 //e_LogWritefln('g_Net_Wait_MapInfo: skip message from non-transfer channel', []);
805 g_Net_Client_HandlePacket(ev
.packet
, g_Net_ClientLightMsgHandler
);
806 if (g_Res_received_map_start
< 0) then begin result
:= -666; exit
; end;
810 ett
:= getNewTimeoutEnd();
811 if (ev
.packet
.dataLength
< 1) then
813 e_LogWritefln('g_Net_Wait_MapInfo: invalid server packet (no data)', []);
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
822 e_LogWritefln('g_Net_Wait_MapInfo: waiting for map info reply, but got file info reply', []);
826 else if (rMsgId
= NTF_SERVER_ABORT
) then
828 e_LogWritefln('g_Net_Wait_MapInfo: server aborted transfer', []);
832 else if (rMsgId
= NTF_SERVER_MAP_INFO
) then
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
839 tf
.diskName
:= msg
.ReadString();
840 e_LogWritefln('g_Net_Wait_MapInfo: map wad is `%s`', [tf
.diskName
]);
842 tf
.hash
:= msg
.ReadMD5();
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
850 e_LogWritefln('g_Net_Wait_Event: invalid number of map external resources (%d)', [rc
]);
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
860 s
:= msg
.ReadString();
861 if (length(s
) = 0) then begin result
:= -1; exit
; end;
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;
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
878 e_LogWritefln('g_Net_Wait_MapInfo: got map info', []);
879 Result
:= 0; // success
884 e_LogWritefln('g_Net_Wait_Event: invalid server packet type', []);
890 ENET_EVENT_TYPE_DISCONNECT
:
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);
899 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' unknown ENet event ' + IntToStr(Ord(ev
.kind
)), True);
904 if (freePacket
) then begin freePacket
:= false; enet_packet_destroy(ev
.packet
); end;
907 if g_Net_UserRequestExit() then
909 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' user abort', True);
915 if (freePacket
) then enet_packet_destroy(ev
.packet
);
920 // send file request to server, and wait for server reply
922 // returns `false` on error or user abort
924 // diskName (actually, base name)
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;
940 freePacket
: Boolean = false;
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);
953 ett
:= getNewTimeoutEnd();
955 status
:= enet_host_service(NetHost
, @ev
, 300);
959 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' network error', True);
964 if (status
<= 0) then
970 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' timeout reached', True);
979 ENET_EVENT_TYPE_RECEIVE
:
982 if (ev
.channelID
<> NET_CHAN_DOWNLOAD_EX
) then
984 //e_LogWriteln('g_Net_Wait_Event: skip message from non-transfer channel');
986 g_Net_Client_HandlePacket(ev
.packet
, g_Net_ClientLightMsgHandler
);
987 if (g_Res_received_map_start
< 0) then begin result
:= -666; exit
; end;
991 ett
:= getNewTimeoutEnd();
992 if (ev
.packet
.dataLength
< 1) then
994 e_LogWriteln('g_Net_Wait_Event: invalid server packet (no data)');
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
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
1010 e_LogWritefln('g_Net_RequestResFileInfo: invalid file info packet', []);
1014 e_LogWritefln('got file info for resource #%d: size=%d; name=%s', [resIndex
, tf
.size
, tf
.diskName
]);
1015 Result
:= 0; // success
1018 else if (rMsgId
= NTF_SERVER_ABORT
) then
1020 e_LogWriteln('g_Net_RequestResFileInfo: server aborted transfer');
1024 else if (rMsgId
= NTF_SERVER_MAP_INFO
) then
1026 e_LogWriteln('g_Net_RequestResFileInfo: waiting for map info reply, but got file info reply');
1032 e_LogWriteln('g_Net_RequestResFileInfo: invalid server packet type');
1038 ENET_EVENT_TYPE_DISCONNECT
:
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);
1047 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' unknown ENet event ' + IntToStr(Ord(ev
.kind
)), True);
1052 if (freePacket
) then begin freePacket
:= false; enet_packet_destroy(ev
.packet
); end;
1055 if g_Net_UserRequestExit() then
1057 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' user abort', True);
1063 if (freePacket
) then enet_packet_destroy(ev
.packet
);
1068 // call this to cancel file transfer requested by `g_Net_RequestResFileInfo()`
1069 function g_Net_AbortResTransfer (var tf
: TNetFileTransfer
): Boolean;
1072 e_LogWritefln('aborting file transfer...', []);
1075 trans_omsg
.Write(Byte(NTF_CLIENT_ABORT
));
1076 result
:= ftransSendClientMsg(trans_omsg
);
1077 if result
then enet_host_flush(NetHost
);
1081 // call this to start file transfer requested by `g_Net_RequestResFileInfo()`
1083 // returns `false` on error or 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;
1100 freePacket
: Boolean = false;
1103 nextChunk
: Integer = 0;
1104 chunkTotal
: Integer;
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
);
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
);
1131 // wait for reply data
1132 FillChar(ev
, SizeOf(ev
), 0);
1134 GetMem(buf
, tf
.chunkSize
);
1136 ett
:= getNewTimeoutEnd();
1138 //stx := -GetTimerMS();
1139 status
:= enet_host_service(NetHost
, @ev
, 300);
1141 if (status < 0) then
1143 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' network error', True);
1148 if (status
<= 0) then
1150 // check for timeout
1154 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' timeout reached', True);
1163 ENET_EVENT_TYPE_RECEIVE
:
1166 if (ev
.channelID
<> NET_CHAN_DOWNLOAD_EX
) then
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;
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
1181 e_LogWritefln('g_Net_ReceiveResourceFile: invalid server packet (no data)', []);
1185 Ptr
:= ev
.packet
^.data
;
1186 rMsgId
:= Byte(Ptr
^);
1187 if (rMsgId
= NTF_SERVER_DONE
) then
1189 e_LogWritefln('file transfer complete.', []);
1193 else if (rMsgId
= NTF_SERVER_CHUNK
) then
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
1200 e_LogWritefln('received chunk %d, but expected chunk %d', [chunk
, nextChunk
]);
1204 if (csize
< 0) or (csize
> tf
.chunkSize
) then
1206 e_LogWritefln('received chunk with size %d, but expected chunk size is %d', [csize
, tf
.chunkSize
]);
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();
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;
1221 else if (rMsgId
= NTF_SERVER_ABORT
) then
1223 e_LogWritefln('g_Net_ReceiveResourceFile: server aborted transfer', []);
1229 e_LogWritefln('g_Net_ReceiveResourceFile: invalid server packet type', []);
1233 //stx := stx+GetTimerMS();
1234 //e_LogWritefln('g_Net_ReceiveResourceFile: process stx=%d', [Integer(stx)]);
1237 ENET_EVENT_TYPE_DISCONNECT
:
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);
1246 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' unknown ENet event ' + IntToStr(Ord(ev
.kind
)), True);
1251 if (freePacket
) then begin freePacket
:= false; enet_packet_destroy(ev
.packet
); end;
1254 if g_Net_UserRequestExit() then
1256 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' user abort', True);
1263 if (freePacket
) then enet_packet_destroy(ev
.packet
);
1268 //**************************************************************************
1272 //**************************************************************************
1274 function g_Net_FindSlot(): Integer;
1283 for I
:= Low(NetClients
) to High(NetClients
) do
1285 if NetClients
[I
].Used
then
1294 if C
>= NetMaxClients
then
1302 if (Length(NetClients
) >= NetMaxClients
) then
1306 SetLength(NetClients
, Length(NetClients
) + 1);
1307 N
:= High(NetClients
);
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
1327 function g_Net_Init(): Boolean;
1335 NetBuf
[NET_UNRELIABLE
].Clear();
1336 NetBuf
[NET_RELIABLE
].Clear();
1337 //SetLength(NetClients, 0);
1338 clearNetClients(true); // clear array
1344 NetAddr
.port
:= 25666;
1345 SetLength(NetBannedHosts
, 0);
1346 if FileExists(DataDir
+ BANLIST_FILENAME
) then
1348 Assign(F
, DataDir
+ BANLIST_FILENAME
);
1353 if StrToIp(IPstr
, IP
) then
1357 g_Net_SaveBanList();
1360 //Result := (enet_initialize() = 0);
1361 Result
:= enet_init_success
;
1364 procedure g_Net_Flush();
1368 F
, Chan
: enet_uint32
;
1372 Chan
:= NET_CHAN_GAME
;
1374 if NetMode
= NET_SERVER
then
1375 for T
:= NET_UNRELIABLE
to NET_RELIABLE
do
1377 if NetBuf
[T
].CurSize
> 0 then
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
);
1385 for I
:= Low(NetClients
) to High(NetClients
) do
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();
1395 // next and last iteration is always RELIABLE
1396 F
:= LongWord(ENET_PACKET_FLAG_RELIABLE
);
1397 Chan
:= NET_CHAN_IMPORTANT
;
1399 else if NetMode
= NET_CLIENT
then
1400 for T
:= NET_UNRELIABLE
to NET_RELIABLE
do
1402 if NetBuf
[T
].CurSize
> 0 then
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
);
1409 // next and last iteration is always RELIABLE
1410 F
:= LongWord(ENET_PACKET_FLAG_RELIABLE
);
1411 Chan
:= NET_CHAN_IMPORTANT
;
1415 procedure g_Net_Cleanup();
1419 NetBuf
[NET_UNRELIABLE
].Clear();
1420 NetBuf
[NET_RELIABLE
].Clear();
1422 //SetLength(NetClients, 0);
1423 clearNetClients(true); // clear array
1424 NetClientCount
:= 0;
1428 g_Net_Slist_ServerClosed();
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();
1452 procedure g_Net_Free();
1456 //enet_deinitialize();
1457 NetInitDone
:= False;
1461 //**************************************************************************
1465 //**************************************************************************
1467 function ForwardThread(Param
: Pointer): PtrInt
;
1470 if not g_Net_ForwardPorts() then Result
:= -1;
1473 function g_Net_Host(IPAddr
: LongWord; Port
: enet_uint16
; MaxClients
: Cardinal = 16): Boolean;
1475 if NetMode
<> NET_NONE
then
1477 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_INGAME
]);
1484 g_Console_Add(_lc
[I_NET_MSG
] + Format(_lc
[I_NET_MSG_HOST
], [Port
]));
1485 if not NetInitDone
then
1487 if (not g_Net_Init()) then
1489 g_Console_Add(_lc
[I_NET_MSG_FERROR
] + _lc
[I_NET_ERR_ENET
]);
1494 NetInitDone
:= True;
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
1506 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + Format(_lc
[I_NET_ERR_HOST
], [Port
]));
1512 NetPongSock
:= enet_socket_create(ENET_SOCKET_TYPE_DATAGRAM
);
1513 if NetPongSock
<> ENET_SOCKET_NULL
then
1515 NetPongAddr
.host
:= IPAddr
;
1516 NetPongAddr
.port
:= NET_PING_PORT
;
1517 if enet_socket_bind(NetPongSock
, @NetPongAddr
) < 0 then
1519 enet_socket_destroy(NetPongSock
);
1520 NetPongSock
:= ENET_SOCKET_NULL
;
1523 enet_socket_set_option(NetPongSock
, ENET_SOCKOPT_NONBLOCK
, 1);
1526 NetMode
:= NET_SERVER
;
1528 NetBuf
[NET_UNRELIABLE
].Clear();
1529 NetBuf
[NET_RELIABLE
].Clear();
1535 procedure g_Net_Host_Die();
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
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();
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
;
1573 e_WriteLog('NET: Server stopped', TMsgType
.Notify
);
1577 procedure g_Net_Host_Send(ID
: Integer; Reliable
: Boolean; Chan
: Byte = NET_CHAN_GAME
);
1584 T
:= NET_UNRELIABLE
;
1588 if ID
> High(NetClients
) then Exit
;
1589 if NetClients
[ID
].Peer
= nil then Exit
;
1591 NetClients
[ID
].NetOut
[T
].Write(Integer(NetOut
.CurSize
));
1592 NetClients
[ID
].NetOut
[T
].Write(NetOut
);
1597 NetBuf
[T
].Write(Integer(NetOut
.CurSize
));
1598 NetBuf
[T
].Write(NetOut
);
1601 if NetDump
then g_Net_DumpSendBuffer();
1605 procedure g_Net_Host_CheckPings();
1607 ClAddr
: ENetAddress
;
1611 Ping
: array [0..9] of Byte;
1614 if NetPongSock
= ENET_SOCKET_NULL
then Exit
;
1616 Buf
.data
:= Addr(Ping
[0]);
1617 Buf
.dataLength
:= 2+8;
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
1626 ClTime
:= Int64(Addr(Ping
[2])^);
1629 NetOut
.Write(Byte(Ord('D')));
1630 NetOut
.Write(Byte(Ord('F')));
1631 NetOut
.Write(NetPort
);
1632 NetOut
.Write(ClTime
);
1633 TMasterHost
.writeInfo(NetOut
);
1635 if gPlayer1
<> nil then Inc(NPl
);
1636 if gPlayer2
<> nil then Inc(NPl
);
1638 NetOut
.Write(gNumBots
);
1640 Buf
.data
:= NetOut
.Data
;
1641 Buf
.dataLength
:= NetOut
.CurSize
;
1642 enet_socket_send(NetPongSock
, @ClAddr
, @Buf
, 1);
1649 function g_Net_Host_Update(): enet_size_t
;
1660 if NetUseMaster
then g_Net_Slist_Pulse();
1661 g_Net_Host_CheckPings();
1663 while (enet_host_service(NetHost
, @NetEvent
, 0) > 0) do
1665 case (NetEvent
.kind
) of
1666 ENET_EVENT_TYPE_CONNECT
:
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
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
);
1684 ID
:= g_Net_FindSlot();
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
);
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
]));
1712 ENET_EVENT_TYPE_RECEIVE
:
1714 //e_LogWritefln('RECEIVE: chan=%u', [NetEvent.channelID]);
1715 if (NetEvent
.channelID
= NET_CHAN_DOWNLOAD_EX
) then
1717 ProcessDownloadExPacket();
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
);
1730 ENET_EVENT_TYPE_DISCONNECT
:
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
);
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
);
1752 TC
^.State
:= NET_STATE_NONE
;
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();
1772 //**************************************************************************
1776 //**************************************************************************
1778 procedure g_Net_Disconnect(Forced
: Boolean = False);
1780 if NetMode
<> NET_CLIENT
then Exit
;
1781 if (NetHost
= nil) or (NetPeer
= nil) then Exit
;
1785 enet_peer_disconnect(NetPeer
, NET_DISC_NONE
);
1787 while (enet_host_service(NetHost
, @NetEvent
, 1500) > 0) do
1789 if (NetEvent
.kind
= ENET_EVENT_TYPE_DISCONNECT
) then
1795 if (NetEvent
.kind
= ENET_EVENT_TYPE_RECEIVE
) then
1796 enet_packet_destroy(NetEvent
.packet
);
1799 if NetPeer
<> nil then
1801 enet_peer_reset(NetPeer
);
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);
1813 if NetHost
<> nil then
1815 enet_host_destroy(NetHost
);
1818 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_CLIENT_DISC
]);
1821 e_WriteLog('NET: Disconnected', TMsgType
.Notify
);
1824 procedure g_Net_Client_Send(Reliable
: Boolean; Chan
: Byte = NET_CHAN_GAME
);
1831 T
:= NET_UNRELIABLE
;
1834 NetBuf
[T
].Write(Integer(NetOut
.CurSize
));
1835 NetBuf
[T
].Write(NetOut
);
1837 if NetDump
then g_Net_DumpSendBuffer();
1839 g_Net_Flush(); // FIXME: for now, send immediately
1842 function g_Net_Client_Update(): enet_size_t
;
1845 while (enet_host_service(NetHost
, @NetEvent
, 0) > 0) do
1847 case NetEvent
.kind
of
1848 ENET_EVENT_TYPE_RECEIVE
:
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
);
1855 ENET_EVENT_TYPE_DISCONNECT
:
1857 g_Net_Disconnect(True);
1865 function g_Net_Client_UpdateWhileLoading(): enet_size_t
;
1868 while (enet_host_service(NetHost
, @NetEvent
, 0) > 0) do
1870 case NetEvent
.kind
of
1871 ENET_EVENT_TYPE_RECEIVE
:
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
);
1878 ENET_EVENT_TYPE_DISCONNECT
:
1880 g_Net_Disconnect(True);
1889 function g_Net_Connect(IP
: string; Port
: enet_uint16
): Boolean;
1892 TimeoutTime
, T
: Int64;
1894 if NetMode
<> NET_NONE
then
1896 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_ERR_INGAME
], True);
1903 g_Console_Add(_lc
[I_NET_MSG
] + Format(_lc
[I_NET_MSG_CLIENT_CONN
],
1905 if not NetInitDone
then
1907 if (not g_Net_Init()) then
1909 g_Console_Add(_lc
[I_NET_MSG_FERROR
] + _lc
[I_NET_ERR_ENET
], True);
1914 NetInitDone
:= True;
1917 NetHost
:= enet_host_create(nil, 1, NET_CHANS
, 0, 0);
1919 if (NetHost
= nil) then
1921 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CLIENT
], True);
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
1934 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CLIENT
], True);
1935 enet_host_destroy(NetHost
);
1941 // предупредить что ждем слишком долго через N секунд
1942 TimeoutTime
:= sys_GetTicks() + NET_CONNECT_TIMEOUT
;
1947 while (enet_host_service(NetHost
, @NetEvent
, 0) > 0) do
1949 if (NetEvent
.kind
= ENET_EVENT_TYPE_CONNECT
) then
1951 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_CLIENT_DONE
]);
1952 NetMode
:= NET_CLIENT
;
1954 enet_peer_timeout(NetPeer
, ENET_PEER_TIMEOUT_LIMIT
* 2, ENET_PEER_TIMEOUT_MINIMUM
* 2, ENET_PEER_TIMEOUT_MAXIMUM
* 2);
1956 NetClientPort
:= Port
;
1963 T
:= sys_GetTicks();
1964 if T
> TimeoutTime
then
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);
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
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
1983 enet_host_destroy(NetHost
);
1990 function IpToStr(IP
: LongWord): string;
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)^);
2001 function StrToIp(IPstr
: string; var IP
: LongWord): Boolean;
2005 Result
:= enet_address_set_host(@EAddr
, PChar(@IPstr
[1])) = 0;
2009 function g_Net_Client_ByName(Name
: string): pTNetClient
;
2015 for a
:= Low(NetClients
) to High(NetClients
) do
2016 if (NetClients
[a
].Used
) and (NetClients
[a
].State
= NET_STATE_GAME
) then
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
2023 Result
:= @NetClients
[a
];
2029 function g_Net_Client_ByPlayer(PID
: Word): pTNetClient
;
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
2038 Result
:= @NetClients
[a
];
2043 function g_Net_ClientName_ByID(ID
: Integer): string;
2049 if ID
= NET_EVERYONE
then
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
2054 pl
:= g_Player_Get(NetClients
[a
].Player
);
2055 if pl
= nil then Exit
;
2060 procedure g_Net_SendData(Data
: AByte
; peer
: pENetPeer
; Reliable
: Boolean; Chan
: Byte = NET_CHAN_DOWNLOAD
);
2064 dataLength
: Cardinal;
2066 dataLength
:= Length(Data
);
2069 F
:= LongWord(ENET_PACKET_FLAG_RELIABLE
)
2073 if (peer
<> nil) then
2075 P
:= enet_packet_create(@Data
[0], dataLength
, F
);
2076 if not Assigned(P
) then Exit
;
2077 enet_peer_send(peer
, Chan
, P
);
2081 P
:= enet_packet_create(@Data
[0], dataLength
, F
);
2082 if not Assigned(P
) then Exit
;
2083 enet_host_broadcast(NetHost
, Chan
, P
);
2086 enet_host_flush(NetHost
);
2089 function g_Net_IsHostBanned(IP
: LongWord; Perm
: Boolean = False): Boolean;
2094 if NetBannedHosts
= nil then
2096 for I
:= 0 to High(NetBannedHosts
) do
2097 if (NetBannedHosts
[I
].IP
= IP
) and ((not Perm
) or (NetBannedHosts
[I
].Perm
)) then
2104 procedure g_Net_BanHost(IP
: LongWord; Perm
: Boolean = True); overload
;
2110 if g_Net_IsHostBanned(IP
, Perm
) then
2114 for I
:= Low(NetBannedHosts
) to High(NetBannedHosts
) do
2115 if NetBannedHosts
[I
].IP
= 0 then
2123 SetLength(NetBannedHosts
, Length(NetBannedHosts
) + 1);
2124 P
:= High(NetBannedHosts
);
2127 NetBannedHosts
[P
].IP
:= IP
;
2128 NetBannedHosts
[P
].Perm
:= Perm
;
2131 procedure g_Net_BanHost(IP
: string; Perm
: Boolean = True); overload
;
2136 b
:= StrToIp(IP
, a
);
2138 g_Net_BanHost(a
, Perm
);
2141 procedure g_Net_UnbanNonPermHosts();
2145 if NetBannedHosts
= nil then
2147 for I
:= Low(NetBannedHosts
) to High(NetBannedHosts
) do
2148 if (NetBannedHosts
[I
].IP
> 0) and not NetBannedHosts
[I
].Perm
then
2150 NetBannedHosts
[I
].IP
:= 0;
2151 NetBannedHosts
[I
].Perm
:= True;
2155 function g_Net_UnbanHost(IP
: string): Boolean; overload
;
2159 Result
:= StrToIp(IP
, a
);
2161 Result
:= g_Net_UnbanHost(a
);
2164 function g_Net_UnbanHost(IP
: LongWord): Boolean; overload
;
2171 if NetBannedHosts
= nil then
2173 for I
:= 0 to High(NetBannedHosts
) do
2174 if NetBannedHosts
[I
].IP
= IP
then
2176 NetBannedHosts
[I
].IP
:= 0;
2177 NetBannedHosts
[I
].Perm
:= True;
2179 // no break here to clear all bans of this host, perm and non-perm
2183 procedure g_Net_SaveBanList();
2188 Assign(F
, DataDir
+ BANLIST_FILENAME
);
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
));
2197 procedure g_Net_DumpStart();
2199 if NetMode
= NET_SERVER
then
2200 NetDumpFile
:= createDiskFile(NETDUMP_FILENAME
+ '_server')
2202 NetDumpFile
:= createDiskFile(NETDUMP_FILENAME
+ '_client');
2205 procedure g_Net_DumpSendBuffer();
2207 writeInt(NetDumpFile
, gTime
);
2208 writeInt(NetDumpFile
, LongWord(NetOut
.CurSize
));
2209 writeInt(NetDumpFile
, Byte(1));
2210 NetDumpFile
.WriteBuffer(NetOut
.Data
^, NetOut
.CurSize
);
2213 procedure g_Net_DumpRecvBuffer(Buf
: penet_uint8
; Len
: LongWord);
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
);
2222 procedure g_Net_DumpEnd();
2228 function g_Net_ForwardPorts(ForwardPongPort
: Boolean = True): Boolean;
2229 {$IFDEF USE_MINIUPNPC}
2234 LanAddr
: array [0..255] of Char;
2235 StrPort
: AnsiString;
2240 if NetPortForwarded
= NetPort
then
2246 NetPongForwarded
:= False;
2247 NetPortForwarded
:= 0;
2249 DevList
:= upnpDiscover(1000, nil, nil, 0, 0, 2, Addr(Err
));
2250 if DevList
= nil then
2252 conwritefln('port forwarding failed: upnpDiscover() failed: %d', [Err
]);
2256 I
:= UPNP_GetValidIGD(DevList
, @Urls
, @Data
, Addr(LanAddr
[0]), 256);
2260 conwriteln('port forwarding failed: could not find an IGD device on this LAN');
2261 FreeUPNPDevList(DevList
);
2262 FreeUPNPUrls(@Urls
);
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')
2275 conwritefln('forwarding port %d failed: error %d', [NetPort
, I
]);
2276 FreeUPNPDevList(DevList
);
2277 FreeUPNPUrls(@Urls
);
2281 if ForwardPongPort
then
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')
2292 conwritefln('forwarding port %d failed: error %d', [NetPort
+ 1, I
]);
2293 NetPongForwarded
:= False;
2297 conwritefln('forwarded port %d successfully', [NetPort
+ 1]);
2298 NetPongForwarded
:= True;
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
);
2317 procedure g_Net_UnforwardPorts();
2318 {$IFDEF USE_MINIUPNPC}
2321 StrPort
: AnsiString;
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
2332 conwritefln(' port %d: %d', [NetPortForwarded
, I
]);
2334 if NetPongForwarded
then
2336 NetPongForwarded
:= False;
2337 StrPort
:= IntToStr(NetPortForwarded
+ 1);
2338 I
:= UPNP_DeletePortMapping(
2339 PChar(NetIGDControl
), Addr(NetIGDService
[1]),
2340 PChar(StrPort
), PChar('UDP'), nil
2342 conwritefln(' port %d: %d', [NetPortForwarded
+ 1, I
]);
2345 NetPortForwarded
:= 0;
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
);
2365 NetBuf
[NET_UNRELIABLE
].Free();
2366 NetBuf
[NET_RELIABLE
].Free();