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.
262 g_nethandler
, g_netmsg
, g_netmaster
, g_player
, g_window
, g_console
,
263 g_main
, g_game
, g_language
, g_weapons
, utils
, ctypes
, g_system
,
267 FILE_CHUNK_SIZE
= 8192;
270 enet_init_success
: Boolean = false;
271 g_Net_DownloadTimeout
: Single;
275 function g_Net_IsNetworkAvailable (): Boolean;
277 result
:= enet_init_success
;
280 procedure g_Net_InitLowLevel ();
282 if enet_init_success
then raise Exception
.Create('wuta?!');
283 enet_init_success
:= (enet_initialize() = 0);
286 procedure g_Net_DeinitLowLevel ();
288 if enet_init_success
then
291 enet_init_success
:= false;
296 //**************************************************************************
300 //**************************************************************************
302 procedure clearNetClientTransfers (var nc
: TNetClient
);
304 nc
.Transfer
.stream
.Free
;
305 nc
.Transfer
.diskName
:= ''; // just in case
306 if (nc
.Transfer
.diskBuffer
<> nil) then FreeMem(nc
.Transfer
.diskBuffer
);
307 nc
.Transfer
.stream
:= nil;
308 nc
.Transfer
.diskBuffer
:= nil;
312 procedure clearNetClient (var nc
: TNetClient
);
314 clearNetClientTransfers(nc
);
318 procedure clearNetClients (clearArray
: Boolean);
322 for f
:= Low(NetClients
) to High(NetClients
) do clearNetClient(NetClients
[f
]);
323 if (clearArray
) then SetLength(NetClients
, 0);
327 function g_Net_UserRequestExit (): Boolean;
329 Result
:= {e_KeyPressed(IK_SPACE) or}
330 e_KeyPressed(IK_ESCAPE
) or
331 e_KeyPressed(VK_ESCAPE
) or
332 e_KeyPressed(JOY0_JUMP
) or
333 e_KeyPressed(JOY1_JUMP
) or
334 e_KeyPressed(JOY2_JUMP
) or
335 e_KeyPressed(JOY3_JUMP
)
339 //**************************************************************************
341 // file transfer declaraions and host packet processor
343 //**************************************************************************
346 // server packet type
347 NTF_SERVER_DONE
= 10; // done with this file
348 NTF_SERVER_FILE_INFO
= 11; // sent after client request
349 NTF_SERVER_CHUNK
= 12; // next chunk; chunk number follows
350 NTF_SERVER_ABORT
= 13; // server abort
351 NTF_SERVER_MAP_INFO
= 14;
353 // client packet type
354 NTF_CLIENT_MAP_REQUEST
= 100; // map file request; also, returns list of additional wads to download
355 NTF_CLIENT_FILE_REQUEST
= 101; // resource file request (by index)
356 NTF_CLIENT_ABORT
= 102; // do not send requested file, or abort current transfer
357 NTF_CLIENT_START
= 103; // start transfer; client may resume download by sending non-zero starting chunk
358 NTF_CLIENT_ACK
= 104; // chunk ack; chunk number follows
361 // disconnect client due to some file transfer error
362 procedure killClientByFT (var nc
: TNetClient
);
364 e_LogWritefln('disconnected client #%d due to file transfer error', [nc
.ID
], TMsgType
.Warning
);
365 enet_peer_disconnect(nc
.Peer
, NET_DISC_FILE_TIMEOUT
);
366 clearNetClientTransfers(nc
);
367 g_Net_Slist_ServerPlayerLeaves();
371 // send file transfer message from server to client
372 function ftransSendServerMsg (var nc
: TNetClient
; var m
: TMsg
): Boolean;
377 if (m
.CurSize
< 1) then exit
;
378 pkt
:= enet_packet_create(m
.Data
, m
.CurSize
, ENET_PACKET_FLAG_RELIABLE
);
379 if not Assigned(pkt
) then begin killClientByFT(nc
); exit
; end;
380 if (enet_peer_send(nc
.Peer
, NET_CHAN_DOWNLOAD_EX
, pkt
) <> 0) then begin killClientByFT(nc
); exit
; end;
385 // send file transfer message from client to server
386 function ftransSendClientMsg (var m
: TMsg
): Boolean;
391 if (m
.CurSize
< 1) then exit
;
392 pkt
:= enet_packet_create(m
.Data
, m
.CurSize
, ENET_PACKET_FLAG_RELIABLE
);
393 if not Assigned(pkt
) then exit
;
394 if (enet_peer_send(NetPeer
, NET_CHAN_DOWNLOAD_EX
, pkt
) <> 0) then exit
;
400 procedure ProcessChunkSend (var nc
: TNetClient
);
402 tf
: ^TNetFileTransfer
;
408 if (tf
.stream
= nil) then exit
;
410 // arbitrary timeout number
411 if (ct
-tf
.lastAckTime
>= 5000) then
416 // check if we need to send something
417 if (not tf
.inProgress
) then exit
; // waiting for the initial ack
418 // ok, we're sending chunks
419 if (tf
.lastAckChunk
<> tf
.lastSentChunk
) then exit
;
420 Inc(tf
.lastSentChunk
);
421 // do it one chunk at a time; client ack will advance our chunk counter
422 chunks
:= (tf
.size
+tf
.chunkSize
-1) div tf
.chunkSize
;
424 if (tf
.lastSentChunk
> chunks
) then
431 if (tf
.lastSentChunk
= chunks
) then
433 // we're done with this file
434 e_LogWritefln('download: client #%d, DONE sending chunks #%d/#%d', [nc
.ID
, tf
.lastSentChunk
, chunks
]);
435 trans_omsg
.Write(Byte(NTF_SERVER_DONE
));
436 clearNetClientTransfers(nc
);
441 trans_omsg
.Write(Byte(NTF_SERVER_CHUNK
));
442 trans_omsg
.Write(LongInt(tf
.lastSentChunk
));
444 rd
:= tf
.size
-(tf
.lastSentChunk
*tf
.chunkSize
);
445 if (rd
> tf
.chunkSize
) then rd
:= tf
.chunkSize
;
446 trans_omsg
.Write(LongInt(rd
));
447 //e_LogWritefln('download: client #%d, sending chunk #%d/#%d (%d bytes)', [nc.ID, tf.lastSentChunk, chunks, rd]);
448 //FIXME: check for errors here
450 tf
.stream
.Seek(tf
.lastSentChunk
*tf
.chunkSize
, soFromBeginning
);
451 tf
.stream
.ReadBuffer(tf
.diskBuffer
^, rd
);
452 trans_omsg
.WriteData(tf
.diskBuffer
, rd
);
459 ftransSendServerMsg(nc
, trans_omsg
);
463 // server file transfer packet processor
464 // received packet is in `NetEvent`
465 procedure ProcessDownloadExPacket ();
472 tf
: ^TNetFileTransfer
;
482 // find client index by peer
483 for f
:= Low(NetClients
) to High(NetClients
) do
485 if (not NetClients
[f
].Used
) then continue
;
486 if (NetClients
[f
].Peer
= NetEvent
.peer
) then
492 //e_LogWritefln('RECEIVE: dlpacket; client=%d (datalen=%u)', [nid, NetEvent.packet^.dataLength]);
494 if (nid
< 0) then exit
; // wtf?!
495 nc
:= @NetClients
[nid
];
497 if (NetEvent
.packet
^.dataLength
= 0) then
503 tf
:= @NetClients
[nid
].Transfer
;
504 tf
.lastAckTime
:= GetTimerMS();
506 cmd
:= Byte(NetEvent
.packet
^.data
^);
507 //e_LogWritefln('RECEIVE: nid=%d; cmd=%u', [nid, cmd]);
509 NTF_CLIENT_FILE_REQUEST
: // file request
511 if (tf
.stream
<> nil) then
516 if (NetEvent
.packet
^.dataLength
< 2) then
521 // new transfer request; build packet
522 if not msg
.Init(NetEvent
.packet
^.data
+1, NetEvent
.packet
^.dataLength
-1, True) then
527 // get resource index
528 ridx
:= msg
.ReadLongInt();
529 if (ridx
< -1) or (ridx
>= length(gExternalResources
)) then
531 e_LogWritefln('Invalid resource index %d', [ridx
], TMsgType
.Warning
);
535 if (ridx
< 0) then fname
:= gGameSettings
.WAD
else fname
:= gExternalResources
[ridx
].diskName
;
536 if (length(fname
) = 0) then
538 e_WriteLog('Invalid filename: '+fname
, TMsgType
.Warning
);
542 tf
.diskName
:= findDiskWad(fname
);
543 //if (length(tf.diskName) = 0) then tf.diskName := findDiskWad(GameDir+'/wads/'+fname);
544 if (length(tf
.diskName
) = 0) then
546 e_LogWritefln('NETWORK: file "%s" not found!', [fname
], TMsgType
.Fatal
);
551 //tf.hash := MD5File(tf.diskName);
552 if (ridx
< 0) then tf
.hash
:= gWADHash
else tf
.hash
:= gExternalResources
[ridx
].hash
;
553 // create file stream
554 tf
.diskName
:= findDiskWad(fname
);
556 tf
.stream
:= openDiskFileRO(tf
.diskName
);
560 if (tf
.stream
= nil) then
562 e_WriteLog(Format('NETWORK: file "%s" not found!', [fname
]), TMsgType
.Fatal
);
566 e_LogWritefln('client #%d requested resource #%d (file is `%s` : `%s`)', [nc
.ID
, ridx
, fname
, tf
.diskName
]);
567 tf
.size
:= tf
.stream
.size
;
568 tf
.chunkSize
:= FILE_CHUNK_SIZE
; // arbitrary
569 tf
.lastSentChunk
:= -1;
570 tf
.lastAckChunk
:= -1;
571 tf
.lastAckTime
:= GetTimerMS();
572 tf
.inProgress
:= False; // waiting for the first ACK or for the cancel
573 GetMem(tf
.diskBuffer
, tf
.chunkSize
);
574 // sent file info message
576 trans_omsg
.Write(Byte(NTF_SERVER_FILE_INFO
));
577 trans_omsg
.Write(tf
.hash
);
578 trans_omsg
.Write(tf
.size
);
579 trans_omsg
.Write(tf
.chunkSize
);
580 trans_omsg
.Write(ExtractFileName(fname
));
581 if not ftransSendServerMsg(nc
^, trans_omsg
) then exit
;
583 NTF_CLIENT_ABORT
: // do not send requested file, or abort current transfer
585 e_LogWritefln('client #%d aborted file transfer', [nc
.ID
]);
586 clearNetClientTransfers(nc
^);
588 NTF_CLIENT_START
: // start transfer; client may resume download by sending non-zero starting chunk
590 if not Assigned(tf
.stream
) then
595 if (tf
.lastSentChunk
<> -1) or (tf
.lastAckChunk
<> -1) or (tf
.inProgress
) then
597 // double ack, get lost
601 if (NetEvent
.packet
^.dataLength
< 2) then
607 if not msg
.Init(NetEvent
.packet
^.data
+1, NetEvent
.packet
^.dataLength
-1, True) then
612 chunk
:= msg
.ReadLongInt();
613 if (chunk
< 0) or (chunk
> (tf
.size
+tf
.chunkSize
-1) div tf
.chunkSize
) then
618 e_LogWritefln('client #%d started file transfer from chunk %d', [nc
.ID
, chunk
]);
619 // start sending chunks
620 tf
.inProgress
:= True;
621 tf
.lastSentChunk
:= chunk
-1;
622 tf
.lastAckChunk
:= chunk
-1;
623 ProcessChunkSend(nc
^);
625 NTF_CLIENT_ACK
: // chunk ack; chunk number follows
627 if not Assigned(tf
.stream
) then
632 if (tf
.lastSentChunk
< 0) or (not tf
.inProgress
) then
634 // double ack, get lost
638 if (NetEvent
.packet
^.dataLength
< 2) then
644 if not msg
.Init(NetEvent
.packet
^.data
+1, NetEvent
.packet
^.dataLength
-1, True) then
649 chunk
:= msg
.ReadLongInt();
650 if (chunk
< 0) or (chunk
> (tf
.size
+tf
.chunkSize
-1) div tf
.chunkSize
) then
655 // do it this way, so client may seek, or request retransfers for some reason
656 tf
.lastAckChunk
:= chunk
;
657 tf
.lastSentChunk
:= chunk
;
658 //e_LogWritefln('client #%d acked file transfer chunk %d', [nc.ID, chunk]);
659 ProcessChunkSend(nc
^);
661 NTF_CLIENT_MAP_REQUEST
:
663 e_LogWritefln('client #%d requested map info', [nc
.ID
]);
665 dfn
:= findDiskWad(gGameSettings
.WAD
);
666 if (dfn
= '') then dfn
:= '!wad_not_found!.wad'; //FIXME
667 //md5 := MD5File(dfn);
669 if (not GetDiskFileInfo(dfn
, fi
)) then
671 e_LogWritefln('client #%d requested map info, but i cannot get file info', [nc
.ID
]);
677 st := openDiskFileRO(dfn);
678 if not assigned(st) then exit; //wtf?!
683 trans_omsg
.Write(Byte(NTF_SERVER_MAP_INFO
));
685 trans_omsg
.Write(gGameSettings
.WAD
);
687 trans_omsg
.Write(md5
);
689 trans_omsg
.Write(size
);
690 // number of external resources for map
691 trans_omsg
.Write(LongInt(length(gExternalResources
)));
692 // external resource names
693 for f
:= 0 to High(gExternalResources
) do
696 //trans_omsg.Write(ExtractFileName(gExternalResources[f])); // GameDir+'/wads/'+ResList.Strings[i]
698 trans_omsg
.Write('!');
699 trans_omsg
.Write(LongInt(gExternalResources
[f
].size
));
700 trans_omsg
.Write(gExternalResources
[f
].hash
);
701 trans_omsg
.Write(ExtractFileName(gExternalResources
[f
].diskName
));
704 if not ftransSendServerMsg(nc
^, trans_omsg
) then exit
;
715 //**************************************************************************
717 // file transfer crap (both client and server)
719 //**************************************************************************
721 function getNewTimeoutEnd (): Int64;
723 result
:= GetTimerMS();
724 if (g_Net_DownloadTimeout
<= 0) then
726 result
:= result
+1000*60*3; // 3 minutes
730 result
:= result
+trunc(g_Net_DownloadTimeout
*1000);
735 // send map request to server, and wait for "map info" server reply
737 // returns `false` on error or user abort
739 // diskName: map wad file name (without a path)
740 // hash: map wad hash
741 // size: map wad size
742 // chunkSize: set too
743 // resList: list of resource wads
749 // for maps, first `tf.diskName` name will be map wad name, and `tf.hash`/`tf.size` will contain map info
750 function g_Net_Wait_MapInfo (var tf
: TNetFileTransfer
; var resList
: TNetMapResourceInfoArray
): Integer;
756 freePacket
: Boolean = false;
761 ri
: ^TNetMapResourceInfo
;
763 SetLength(resList
, 0);
767 trans_omsg
.Write(Byte(NTF_CLIENT_MAP_REQUEST
));
768 if not ftransSendClientMsg(trans_omsg
) then begin result
:= -1; exit
; end;
770 FillChar(ev
, SizeOf(ev
), 0);
773 ett
:= getNewTimeoutEnd();
775 status
:= enet_host_service(NetHost
, @ev
, 300);
779 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' network error', True);
784 if (status
<= 0) then
790 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' timeout reached', True);
799 ENET_EVENT_TYPE_RECEIVE
:
802 if (ev
.channelID
<> NET_CHAN_DOWNLOAD_EX
) then
804 //e_LogWritefln('g_Net_Wait_MapInfo: skip message from non-transfer channel', []);
806 g_Net_Client_HandlePacket(ev
.packet
, g_Net_ClientLightMsgHandler
);
807 if (g_Res_received_map_start
< 0) then begin result
:= -666; exit
; end;
811 ett
:= getNewTimeoutEnd();
812 if (ev
.packet
.dataLength
< 1) then
814 e_LogWritefln('g_Net_Wait_MapInfo: invalid server packet (no data)', []);
818 Ptr
:= ev
.packet
^.data
;
819 rMsgId
:= Byte(Ptr
^);
820 e_LogWritefln('g_Net_Wait_MapInfo: got message %u from server (dataLength=%u)', [rMsgId
, ev
.packet
^.dataLength
]);
821 if (rMsgId
= NTF_SERVER_FILE_INFO
) then
823 e_LogWritefln('g_Net_Wait_MapInfo: waiting for map info reply, but got file info reply', []);
827 else if (rMsgId
= NTF_SERVER_ABORT
) then
829 e_LogWritefln('g_Net_Wait_MapInfo: server aborted transfer', []);
833 else if (rMsgId
= NTF_SERVER_MAP_INFO
) then
835 e_LogWritefln('g_Net_Wait_MapInfo: creating map info packet...', []);
836 if not msg
.Init(ev
.packet
^.data
+1, ev
.packet
^.dataLength
-1, True) then exit
;
837 e_LogWritefln('g_Net_Wait_MapInfo: parsing map info packet (rd=%d; max=%d)...', [msg
.ReadCount
, msg
.MaxSize
]);
838 SetLength(resList
, 0); // just in case
840 tf
.diskName
:= msg
.ReadString();
841 e_LogWritefln('g_Net_Wait_MapInfo: map wad is `%s`', [tf
.diskName
]);
843 tf
.hash
:= msg
.ReadMD5();
845 tf
.size
:= msg
.ReadLongInt();
846 e_LogWritefln('g_Net_Wait_MapInfo: map wad size is %d', [tf
.size
]);
847 // number of external resources for map
848 rc
:= msg
.ReadLongInt();
849 if (rc
< 0) or (rc
> 1024) then
851 e_LogWritefln('g_Net_Wait_Event: invalid number of map external resources (%d)', [rc
]);
855 e_LogWritefln('g_Net_Wait_MapInfo: map external resource count is %d', [rc
]);
856 SetLength(resList
, rc
);
857 // external resource names
858 for f
:= 0 to rc
-1 do
861 s
:= msg
.ReadString();
862 if (length(s
) = 0) then begin result
:= -1; exit
; end;
866 ri
.size
:= msg
.ReadLongInt();
867 ri
.hash
:= msg
.ReadMD5();
868 ri
.wadName
:= ExtractFileName(msg
.ReadString());
869 if (length(ri
.wadName
) = 0) or (ri
.size
< 0) then begin result
:= -1; exit
; end;
873 // old-style packet, only name
874 ri
.wadName
:= ExtractFileName(s
);
875 if (length(ri
.wadName
) = 0) then begin result
:= -1; exit
; end;
876 ri
.size
:= -1; // unknown
879 e_LogWritefln('g_Net_Wait_MapInfo: got map info', []);
880 Result
:= 0; // success
885 e_LogWritefln('g_Net_Wait_Event: invalid server packet type', []);
891 ENET_EVENT_TYPE_DISCONNECT
:
893 if (ev
.data
<= NET_DISC_MAX
) then
894 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' ' + _lc
[TStrings_Locale(Cardinal(I_NET_DISC_NONE
) + ev
.data
)], True);
900 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' unknown ENet event ' + IntToStr(Ord(ev
.kind
)), True);
905 if (freePacket
) then begin freePacket
:= false; enet_packet_destroy(ev
.packet
); end;
908 if g_Net_UserRequestExit() then
910 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' user abort', True);
916 if (freePacket
) then enet_packet_destroy(ev
.packet
);
921 // send file request to server, and wait for server reply
923 // returns `false` on error or user abort
925 // diskName (actually, base name)
934 // for maps, first `tf.diskName` name will be map wad name, and `tf.hash`/`tf.size` will contain map info
935 function g_Net_RequestResFileInfo (resIndex
: LongInt; out tf
: TNetFileTransfer
): Integer;
941 freePacket
: Boolean = false;
947 trans_omsg
.Write(Byte(NTF_CLIENT_FILE_REQUEST
));
948 trans_omsg
.Write(resIndex
);
949 if not ftransSendClientMsg(trans_omsg
) then begin result
:= -1; exit
; end;
951 FillChar(ev
, SizeOf(ev
), 0);
954 ett
:= getNewTimeoutEnd();
956 status
:= enet_host_service(NetHost
, @ev
, 300);
960 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' network error', True);
965 if (status
<= 0) then
971 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' timeout reached', True);
980 ENET_EVENT_TYPE_RECEIVE
:
983 if (ev
.channelID
<> NET_CHAN_DOWNLOAD_EX
) then
985 //e_LogWriteln('g_Net_Wait_Event: skip message from non-transfer channel');
987 g_Net_Client_HandlePacket(ev
.packet
, g_Net_ClientLightMsgHandler
);
988 if (g_Res_received_map_start
< 0) then begin result
:= -666; exit
; end;
992 ett
:= getNewTimeoutEnd();
993 if (ev
.packet
.dataLength
< 1) then
995 e_LogWriteln('g_Net_Wait_Event: invalid server packet (no data)');
999 Ptr
:= ev
.packet
^.data
;
1000 rMsgId
:= Byte(Ptr
^);
1001 e_LogWritefln('received transfer packet with id %d (%u bytes)', [rMsgId
, ev
.packet
^.dataLength
]);
1002 if (rMsgId
= NTF_SERVER_FILE_INFO
) then
1004 if not msg
.Init(ev
.packet
^.data
+1, ev
.packet
^.dataLength
-1, True) then exit
;
1005 tf
.hash
:= msg
.ReadMD5();
1006 tf
.size
:= msg
.ReadLongInt();
1007 tf
.chunkSize
:= msg
.ReadLongInt();
1008 tf
.diskName
:= ExtractFileName(msg
.readString());
1009 if (tf
.size
< 0) or (tf
.chunkSize
<> FILE_CHUNK_SIZE
) or (length(tf
.diskName
) = 0) then
1011 e_LogWritefln('g_Net_RequestResFileInfo: invalid file info packet', []);
1015 e_LogWritefln('got file info for resource #%d: size=%d; name=%s', [resIndex
, tf
.size
, tf
.diskName
]);
1016 Result
:= 0; // success
1019 else if (rMsgId
= NTF_SERVER_ABORT
) then
1021 e_LogWriteln('g_Net_RequestResFileInfo: server aborted transfer');
1025 else if (rMsgId
= NTF_SERVER_MAP_INFO
) then
1027 e_LogWriteln('g_Net_RequestResFileInfo: waiting for map info reply, but got file info reply');
1033 e_LogWriteln('g_Net_RequestResFileInfo: invalid server packet type');
1039 ENET_EVENT_TYPE_DISCONNECT
:
1041 if (ev
.data
<= NET_DISC_MAX
) then
1042 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' ' + _lc
[TStrings_Locale(Cardinal(I_NET_DISC_NONE
) + ev
.data
)], True);
1048 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' unknown ENet event ' + IntToStr(Ord(ev
.kind
)), True);
1053 if (freePacket
) then begin freePacket
:= false; enet_packet_destroy(ev
.packet
); end;
1056 if g_Net_UserRequestExit() then
1058 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' user abort', True);
1064 if (freePacket
) then enet_packet_destroy(ev
.packet
);
1069 // call this to cancel file transfer requested by `g_Net_RequestResFileInfo()`
1070 function g_Net_AbortResTransfer (var tf
: TNetFileTransfer
): Boolean;
1073 e_LogWritefln('aborting file transfer...', []);
1076 trans_omsg
.Write(Byte(NTF_CLIENT_ABORT
));
1077 result
:= ftransSendClientMsg(trans_omsg
);
1078 if result
then enet_host_flush(NetHost
);
1082 // call this to start file transfer requested by `g_Net_RequestResFileInfo()`
1084 // returns `false` on error or user abort
1093 // 2 on server abort
1094 // for maps, first `tf.diskName` name will be map wad name, and `tf.hash`/`tf.size` will contain map info
1095 function g_Net_ReceiveResourceFile (resIndex
: LongInt; var tf
: TNetFileTransfer
; strm
: TStream
): Integer;
1101 freePacket
: Boolean = false;
1104 nextChunk
: Integer = 0;
1105 chunkTotal
: Integer;
1112 tf
.resumed
:= false;
1113 e_LogWritefln('file `%s`, size=%d (%d)', [tf
.diskName
, Integer(strm
.size
), tf
.size
], TMsgType
.Notify
);
1114 // check if we should resume downloading
1115 resumed
:= (strm
.size
> tf
.chunkSize
) and (strm
.size
< tf
.size
);
1118 trans_omsg
.Write(Byte(NTF_CLIENT_START
));
1119 if resumed
then chunk
:= strm
.size
div tf
.chunkSize
else chunk
:= 0;
1120 trans_omsg
.Write(LongInt(chunk
));
1121 if not ftransSendClientMsg(trans_omsg
) then begin result
:= -1; exit
; end;
1123 strm
.Seek(chunk
*tf
.chunkSize
, soFromBeginning
);
1124 chunkTotal
:= (tf
.size
+tf
.chunkSize
-1) div tf
.chunkSize
;
1125 e_LogWritefln('receiving file `%s` (%d chunks)', [tf
.diskName
, chunkTotal
], TMsgType
.Notify
);
1126 g_Game_SetLoadingText('downloading "'+ExtractFileName(tf
.diskName
)+'"', chunkTotal
, False);
1127 tf
.resumed
:= resumed
;
1129 if (chunk
> 0) then g_Game_StepLoading(chunk
);
1132 // wait for reply data
1133 FillChar(ev
, SizeOf(ev
), 0);
1135 GetMem(buf
, tf
.chunkSize
);
1137 ett
:= getNewTimeoutEnd();
1139 //stx := -GetTimerMS();
1140 status
:= enet_host_service(NetHost
, @ev
, 300);
1142 if (status < 0) then
1144 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' network error', True);
1149 if (status
<= 0) then
1151 // check for timeout
1155 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' timeout reached', True);
1164 ENET_EVENT_TYPE_RECEIVE
:
1167 if (ev
.channelID
<> NET_CHAN_DOWNLOAD_EX
) then
1169 //e_LogWritefln('g_Net_Wait_Event: skip message from non-transfer channel', []);
1170 freePacket
:= false;
1171 g_Net_Client_HandlePacket(ev
.packet
, g_Net_ClientLightMsgHandler
);
1172 if (g_Res_received_map_start
< 0) then begin result
:= -666; exit
; end;
1176 //stx := stx+GetTimerMS();
1177 //e_LogWritefln('g_Net_ReceiveResourceFile: stx=%d', [Integer(stx)]);
1178 //stx := -GetTimerMS();
1179 ett
:= getNewTimeoutEnd();
1180 if (ev
.packet
.dataLength
< 1) then
1182 e_LogWritefln('g_Net_ReceiveResourceFile: invalid server packet (no data)', []);
1186 Ptr
:= ev
.packet
^.data
;
1187 rMsgId
:= Byte(Ptr
^);
1188 if (rMsgId
= NTF_SERVER_DONE
) then
1190 e_LogWritefln('file transfer complete.', []);
1194 else if (rMsgId
= NTF_SERVER_CHUNK
) then
1196 if not msg
.Init(ev
.packet
^.data
+1, ev
.packet
^.dataLength
-1, True) then exit
;
1197 chunk
:= msg
.ReadLongInt();
1198 csize
:= msg
.ReadLongInt();
1199 if (chunk
<> nextChunk
) then
1201 e_LogWritefln('received chunk %d, but expected chunk %d', [chunk
, nextChunk
]);
1205 if (csize
< 0) or (csize
> tf
.chunkSize
) then
1207 e_LogWritefln('received chunk with size %d, but expected chunk size is %d', [csize
, tf
.chunkSize
]);
1211 //e_LogWritefln('got chunk #%d of #%d (csize=%d)', [chunk, (tf.size+tf.chunkSize-1) div tf.chunkSize, csize]);
1212 msg
.ReadData(buf
, csize
);
1213 strm
.WriteBuffer(buf
^, csize
);
1214 nextChunk
:= chunk
+1;
1215 g_Game_StepLoading();
1218 trans_omsg
.Write(Byte(NTF_CLIENT_ACK
));
1219 trans_omsg
.Write(LongInt(chunk
));
1220 if not ftransSendClientMsg(trans_omsg
) then begin result
:= -1; exit
; end;
1222 else if (rMsgId
= NTF_SERVER_ABORT
) then
1224 e_LogWritefln('g_Net_ReceiveResourceFile: server aborted transfer', []);
1230 e_LogWritefln('g_Net_ReceiveResourceFile: invalid server packet type', []);
1234 //stx := stx+GetTimerMS();
1235 //e_LogWritefln('g_Net_ReceiveResourceFile: process stx=%d', [Integer(stx)]);
1238 ENET_EVENT_TYPE_DISCONNECT
:
1240 if (ev
.data
<= NET_DISC_MAX
) then
1241 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' ' + _lc
[TStrings_Locale(Cardinal(I_NET_DISC_NONE
) + ev
.data
)], True);
1247 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' unknown ENet event ' + IntToStr(Ord(ev
.kind
)), True);
1252 if (freePacket
) then begin freePacket
:= false; enet_packet_destroy(ev
.packet
); end;
1255 if g_Net_UserRequestExit() then
1257 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' user abort', True);
1264 if (freePacket
) then enet_packet_destroy(ev
.packet
);
1269 //**************************************************************************
1273 //**************************************************************************
1275 function g_Net_FindSlot(): Integer;
1284 for I
:= Low(NetClients
) to High(NetClients
) do
1286 if NetClients
[I
].Used
then
1295 if C
>= NetMaxClients
then
1303 if (Length(NetClients
) >= NetMaxClients
) then
1307 SetLength(NetClients
, Length(NetClients
) + 1);
1308 N
:= High(NetClients
);
1314 NetClients
[N
].Used
:= True;
1315 NetClients
[N
].ID
:= N
;
1316 NetClients
[N
].RequestedFullUpdate
:= False;
1317 NetClients
[N
].WaitForFirstSpawn
:= False;
1318 NetClients
[N
].RCONAuth
:= False;
1319 NetClients
[N
].Voted
:= False;
1320 NetClients
[N
].Player
:= 0;
1321 clearNetClientTransfers(NetClients
[N
]); // just in case
1328 function g_Net_Init(): Boolean;
1337 NetBuf
[NET_UNRELIABLE
].Clear();
1338 NetBuf
[NET_RELIABLE
].Clear();
1339 //SetLength(NetClients, 0);
1340 clearNetClients(true); // clear array
1346 NetAddr
.port
:= 25666;
1347 SetLength(NetBannedHosts
, 0);
1348 path
:= BANLIST_FILENAME
;
1349 if e_FindResource(DataDirs
, path
) = true then
1356 if StrToIp(IPstr
, IP
) then
1360 g_Net_SaveBanList();
1363 //Result := (enet_initialize() = 0);
1364 Result
:= enet_init_success
;
1367 procedure g_Net_Flush();
1371 F
, Chan
: enet_uint32
;
1375 Chan
:= NET_CHAN_GAME
;
1377 if NetMode
= NET_SERVER
then
1378 for T
:= NET_UNRELIABLE
to NET_RELIABLE
do
1380 if NetBuf
[T
].CurSize
> 0 then
1382 P
:= enet_packet_create(NetBuf
[T
].Data
, NetBuf
[T
].CurSize
, F
);
1383 if not Assigned(P
) then continue
;
1384 enet_host_broadcast(NetHost
, Chan
, P
);
1388 for I
:= Low(NetClients
) to High(NetClients
) do
1390 if not NetClients
[I
].Used
then continue
;
1391 if NetClients
[I
].NetOut
[T
].CurSize
<= 0 then continue
;
1392 P
:= enet_packet_create(NetClients
[I
].NetOut
[T
].Data
, NetClients
[I
].NetOut
[T
].CurSize
, F
);
1393 if not Assigned(P
) then continue
;
1394 enet_peer_send(NetClients
[I
].Peer
, Chan
, P
);
1395 NetClients
[I
].NetOut
[T
].Clear();
1398 // next and last iteration is always RELIABLE
1399 F
:= LongWord(ENET_PACKET_FLAG_RELIABLE
);
1400 Chan
:= NET_CHAN_IMPORTANT
;
1402 else if NetMode
= NET_CLIENT
then
1403 for T
:= NET_UNRELIABLE
to NET_RELIABLE
do
1405 if NetBuf
[T
].CurSize
> 0 then
1407 P
:= enet_packet_create(NetBuf
[T
].Data
, NetBuf
[T
].CurSize
, F
);
1408 if not Assigned(P
) then continue
;
1409 enet_peer_send(NetPeer
, Chan
, P
);
1412 // next and last iteration is always RELIABLE
1413 F
:= LongWord(ENET_PACKET_FLAG_RELIABLE
);
1414 Chan
:= NET_CHAN_IMPORTANT
;
1418 procedure g_Net_Cleanup();
1422 NetBuf
[NET_UNRELIABLE
].Clear();
1423 NetBuf
[NET_RELIABLE
].Clear();
1425 //SetLength(NetClients, 0);
1426 clearNetClients(true); // clear array
1427 NetClientCount
:= 0;
1431 g_Net_Slist_ServerClosed();
1435 NetState
:= NET_STATE_NONE
;
1437 NetPongSock
:= ENET_SOCKET_NULL
;
1439 NetTimeToMaster
:= 0;
1440 NetTimeToUpdate
:= 0;
1441 NetTimeToReliable
:= 0;
1443 NetMode
:= NET_NONE
;
1445 if NetPortThread
<> NilThreadId
then
1446 WaitForThreadTerminate(NetPortThread
, 66666);
1448 NetPortThread
:= NilThreadId
;
1449 g_Net_UnforwardPorts();
1455 procedure g_Net_Free();
1459 //enet_deinitialize();
1460 NetInitDone
:= False;
1464 //**************************************************************************
1468 //**************************************************************************
1470 function ForwardThread(Param
: Pointer): PtrInt
;
1473 if not g_Net_ForwardPorts() then Result
:= -1;
1476 function g_Net_Host(IPAddr
: LongWord; Port
: enet_uint16
; MaxClients
: Cardinal = 16): Boolean;
1478 if NetMode
<> NET_NONE
then
1480 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_INGAME
]);
1487 g_Console_Add(_lc
[I_NET_MSG
] + Format(_lc
[I_NET_MSG_HOST
], [Port
]));
1488 if not NetInitDone
then
1490 if (not g_Net_Init()) then
1492 g_Console_Add(_lc
[I_NET_MSG_FERROR
] + _lc
[I_NET_ERR_ENET
]);
1497 NetInitDone
:= True;
1500 NetAddr
.host
:= IPAddr
;
1501 NetAddr
.port
:= Port
;
1503 if NetForwardPorts
then NetPortThread
:= BeginThread(ForwardThread
);
1505 NetHost
:= enet_host_create(@NetAddr
, NET_MAXCLIENTS
, NET_CHANS
, 0, 0);
1507 if (NetHost
= nil) then
1509 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + Format(_lc
[I_NET_ERR_HOST
], [Port
]));
1515 NetPongSock
:= enet_socket_create(ENET_SOCKET_TYPE_DATAGRAM
);
1516 if NetPongSock
<> ENET_SOCKET_NULL
then
1518 NetPongAddr
.host
:= IPAddr
;
1519 NetPongAddr
.port
:= NET_PING_PORT
;
1520 if enet_socket_bind(NetPongSock
, @NetPongAddr
) < 0 then
1522 enet_socket_destroy(NetPongSock
);
1523 NetPongSock
:= ENET_SOCKET_NULL
;
1526 enet_socket_set_option(NetPongSock
, ENET_SOCKOPT_NONBLOCK
, 1);
1529 NetMode
:= NET_SERVER
;
1531 NetBuf
[NET_UNRELIABLE
].Clear();
1532 NetBuf
[NET_RELIABLE
].Clear();
1538 procedure g_Net_Host_Die();
1542 if NetMode
<> NET_SERVER
then Exit
;
1544 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_HOST_DISCALL
]);
1545 for I
:= 0 to High(NetClients
) do
1546 if NetClients
[I
].Used
then
1547 enet_peer_disconnect(NetClients
[I
].Peer
, NET_DISC_DOWN
);
1549 while enet_host_service(NetHost
, @NetEvent
, 1000) > 0 do
1550 if NetEvent
.kind
= ENET_EVENT_TYPE_RECEIVE
then
1551 enet_packet_destroy(NetEvent
.packet
);
1553 for I
:= 0 to High(NetClients
) do
1554 if NetClients
[I
].Used
then
1556 FreeMemory(NetClients
[I
].Peer
^.data
);
1557 NetClients
[I
].Peer
^.data
:= nil;
1558 enet_peer_reset(NetClients
[I
].Peer
);
1559 NetClients
[I
].Peer
:= nil;
1560 NetClients
[I
].Used
:= False;
1561 NetClients
[I
].NetOut
[NET_UNRELIABLE
].Free();
1562 NetClients
[I
].NetOut
[NET_RELIABLE
].Free();
1565 clearNetClients(false); // don't clear array
1566 g_Net_Slist_ServerClosed();
1567 if NetPongSock
<> ENET_SOCKET_NULL
then
1568 enet_socket_destroy(NetPongSock
);
1570 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_HOST_DIE
]);
1571 enet_host_destroy(NetHost
);
1573 NetMode
:= NET_NONE
;
1576 e_WriteLog('NET: Server stopped', TMsgType
.Notify
);
1580 procedure g_Net_Host_Send(ID
: Integer; Reliable
: Boolean; Chan
: Byte = NET_CHAN_GAME
);
1587 T
:= NET_UNRELIABLE
;
1591 if ID
> High(NetClients
) then Exit
;
1592 if NetClients
[ID
].Peer
= nil then Exit
;
1594 NetClients
[ID
].NetOut
[T
].Write(Integer(NetOut
.CurSize
));
1595 NetClients
[ID
].NetOut
[T
].Write(NetOut
);
1600 NetBuf
[T
].Write(Integer(NetOut
.CurSize
));
1601 NetBuf
[T
].Write(NetOut
);
1604 if NetDump
then g_Net_DumpSendBuffer();
1608 procedure g_Net_Host_CheckPings();
1610 ClAddr
: ENetAddress
;
1614 Ping
: array [0..9] of Byte;
1617 if NetPongSock
= ENET_SOCKET_NULL
then Exit
;
1619 Buf
.data
:= Addr(Ping
[0]);
1620 Buf
.dataLength
:= 2+8;
1624 Len
:= enet_socket_receive(NetPongSock
, @ClAddr
, @Buf
, 1);
1625 if Len
< 0 then Exit
;
1627 if (Ping
[0] = Ord('D')) and (Ping
[1] = Ord('F')) then
1629 ClTime
:= Int64(Addr(Ping
[2])^);
1632 NetOut
.Write(Byte(Ord('D')));
1633 NetOut
.Write(Byte(Ord('F')));
1634 NetOut
.Write(NetPort
);
1635 NetOut
.Write(ClTime
);
1636 TMasterHost
.writeInfo(NetOut
);
1638 if gPlayer1
<> nil then Inc(NPl
);
1639 if gPlayer2
<> nil then Inc(NPl
);
1641 NetOut
.Write(gNumBots
);
1643 Buf
.data
:= NetOut
.Data
;
1644 Buf
.dataLength
:= NetOut
.CurSize
;
1645 enet_socket_send(NetPongSock
, @ClAddr
, @Buf
, 1);
1652 function g_Net_Host_Update(): enet_size_t
;
1663 if NetUseMaster
then g_Net_Slist_Pulse();
1664 g_Net_Host_CheckPings();
1666 while (enet_host_service(NetHost
, @NetEvent
, 0) > 0) do
1668 case (NetEvent
.kind
) of
1669 ENET_EVENT_TYPE_CONNECT
:
1671 IP
:= IpToStr(NetEvent
.Peer
^.address
.host
);
1672 Port
:= NetEvent
.Peer
^.address
.port
;
1673 g_Console_Add(_lc
[I_NET_MSG
] +
1674 Format(_lc
[I_NET_MSG_HOST_CONN
], [IP
, Port
]));
1676 if (NetEvent
.data
<> NET_PROTOCOL_VER
) then
1678 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_HOST_REJECT
] +
1679 _lc
[I_NET_DISC_PROTOCOL
]);
1680 NetEvent
.peer
^.data
:= GetMemory(SizeOf(Byte));
1681 Byte(NetEvent
.peer
^.data
^) := 255;
1682 enet_peer_disconnect(NetEvent
.peer
, NET_DISC_PROTOCOL
);
1683 enet_host_flush(NetHost
);
1687 ID
:= g_Net_FindSlot();
1691 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_HOST_REJECT
] +
1692 _lc
[I_NET_DISC_FULL
]);
1693 NetEvent
.Peer
^.data
:= GetMemory(SizeOf(Byte));
1694 Byte(NetEvent
.peer
^.data
^) := 255;
1695 enet_peer_disconnect(NetEvent
.peer
, NET_DISC_FULL
);
1696 enet_host_flush(NetHost
);
1700 NetClients
[ID
].Peer
:= NetEvent
.peer
;
1701 NetClients
[ID
].Peer
^.data
:= GetMemory(SizeOf(Byte));
1702 Byte(NetClients
[ID
].Peer
^.data
^) := ID
;
1703 NetClients
[ID
].State
:= NET_STATE_AUTH
;
1704 NetClients
[ID
].RCONAuth
:= False;
1705 NetClients
[ID
].NetOut
[NET_UNRELIABLE
].Alloc(NET_BUFSIZE
*2);
1706 NetClients
[ID
].NetOut
[NET_RELIABLE
].Alloc(NET_BUFSIZE
*2);
1707 clearNetClientTransfers(NetClients
[ID
]); // just in case
1709 enet_peer_timeout(NetEvent
.peer
, ENET_PEER_TIMEOUT_LIMIT
* 2, ENET_PEER_TIMEOUT_MINIMUM
* 2, ENET_PEER_TIMEOUT_MAXIMUM
* 2);
1711 Inc(NetClientCount
);
1712 g_Console_Add(_lc
[I_NET_MSG
] + Format(_lc
[I_NET_MSG_HOST_ADD
], [ID
]));
1715 ENET_EVENT_TYPE_RECEIVE
:
1717 //e_LogWritefln('RECEIVE: chan=%u', [NetEvent.channelID]);
1718 if (NetEvent
.channelID
= NET_CHAN_DOWNLOAD_EX
) then
1720 ProcessDownloadExPacket();
1724 ID
:= Byte(NetEvent
.peer
^.data
^);
1725 if ID
> High(NetClients
) then Exit
;
1726 TC
:= @NetClients
[ID
];
1728 if NetDump
then g_Net_DumpRecvBuffer(NetEvent
.packet
^.data
, NetEvent
.packet
^.dataLength
);
1729 g_Net_Host_HandlePacket(TC
, NetEvent
.packet
, g_Net_HostMsgHandler
);
1733 ENET_EVENT_TYPE_DISCONNECT
:
1735 ID
:= Byte(NetEvent
.peer
^.data
^);
1736 if ID
> High(NetClients
) then Exit
;
1737 clearNetClient(NetClients
[ID
]);
1738 TC
:= @NetClients
[ID
];
1739 if TC
= nil then Exit
;
1741 if not (TC
^.Used
) then Exit
;
1743 TP
:= g_Player_Get(TC
^.Player
);
1748 TP
.Kill(K_SIMPLEKILL
, 0, HIT_DISCON
);
1749 g_Console_Add(Format(_lc
[I_PLAYER_LEAVE
], [TP
.Name
]), True);
1750 e_WriteLog('NET: Client ' + TP
.Name
+ ' [' + IntToStr(ID
) + '] disconnected.', TMsgType
.Notify
);
1751 g_Player_Remove(TP
.UID
);
1755 TC
^.State
:= NET_STATE_NONE
;
1758 TC
^.RequestedFullUpdate
:= False;
1759 TC
^.WaitForFirstSpawn
:= False;
1760 TC
^.NetOut
[NET_UNRELIABLE
].Free();
1761 TC
^.NetOut
[NET_RELIABLE
].Free();
1763 FreeMemory(NetEvent
.peer
^.data
);
1764 NetEvent
.peer
^.data
:= nil;
1765 g_Console_Add(_lc
[I_NET_MSG
] + Format(_lc
[I_NET_MSG_HOST_DISC
], [ID
]));
1766 Dec(NetClientCount
);
1768 if NetUseMaster
then g_Net_Slist_ServerPlayerLeaves();
1775 //**************************************************************************
1779 //**************************************************************************
1781 procedure g_Net_Disconnect(Forced
: Boolean = False);
1783 if NetMode
<> NET_CLIENT
then Exit
;
1784 if (NetHost
= nil) or (NetPeer
= nil) then Exit
;
1788 enet_peer_disconnect(NetPeer
, NET_DISC_NONE
);
1790 while (enet_host_service(NetHost
, @NetEvent
, 1500) > 0) do
1792 if (NetEvent
.kind
= ENET_EVENT_TYPE_DISCONNECT
) then
1798 if (NetEvent
.kind
= ENET_EVENT_TYPE_RECEIVE
) then
1799 enet_packet_destroy(NetEvent
.packet
);
1802 if NetPeer
<> nil then
1804 enet_peer_reset(NetPeer
);
1810 e_WriteLog('NET: Kicked from server: ' + IntToStr(NetEvent
.data
), TMsgType
.Notify
);
1811 if (NetEvent
.data
<= NET_DISC_MAX
) then
1812 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_KICK
] +
1813 _lc
[TStrings_Locale(Cardinal(I_NET_DISC_NONE
) + NetEvent
.data
)], True);
1816 if NetHost
<> nil then
1818 enet_host_destroy(NetHost
);
1821 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_CLIENT_DISC
]);
1824 e_WriteLog('NET: Disconnected', TMsgType
.Notify
);
1827 procedure g_Net_Client_Send(Reliable
: Boolean; Chan
: Byte = NET_CHAN_GAME
);
1834 T
:= NET_UNRELIABLE
;
1837 NetBuf
[T
].Write(Integer(NetOut
.CurSize
));
1838 NetBuf
[T
].Write(NetOut
);
1840 if NetDump
then g_Net_DumpSendBuffer();
1842 g_Net_Flush(); // FIXME: for now, send immediately
1845 function g_Net_Client_Update(): enet_size_t
;
1848 while (enet_host_service(NetHost
, @NetEvent
, 0) > 0) do
1850 case NetEvent
.kind
of
1851 ENET_EVENT_TYPE_RECEIVE
:
1853 if (NetEvent
.channelID
= NET_CHAN_DOWNLOAD_EX
) then continue
; // ignore all download packets, they're processed by separate code
1854 if NetDump
then g_Net_DumpRecvBuffer(NetEvent
.packet
^.data
, NetEvent
.packet
^.dataLength
);
1855 g_Net_Client_HandlePacket(NetEvent
.packet
, g_Net_ClientMsgHandler
);
1858 ENET_EVENT_TYPE_DISCONNECT
:
1860 g_Net_Disconnect(True);
1868 function g_Net_Client_UpdateWhileLoading(): enet_size_t
;
1871 while (enet_host_service(NetHost
, @NetEvent
, 0) > 0) do
1873 case NetEvent
.kind
of
1874 ENET_EVENT_TYPE_RECEIVE
:
1876 if (NetEvent
.channelID
= NET_CHAN_DOWNLOAD_EX
) then continue
; // ignore all download packets, they're processed by separate code
1877 if NetDump
then g_Net_DumpRecvBuffer(NetEvent
.packet
^.data
, NetEvent
.packet
^.dataLength
);
1878 g_Net_Client_HandlePacket(NetEvent
.packet
, g_Net_ClientLightMsgHandler
);
1881 ENET_EVENT_TYPE_DISCONNECT
:
1883 g_Net_Disconnect(True);
1892 function g_Net_Connect(IP
: string; Port
: enet_uint16
): Boolean;
1895 TimeoutTime
, T
: Int64;
1897 if NetMode
<> NET_NONE
then
1899 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_ERR_INGAME
], True);
1906 g_Console_Add(_lc
[I_NET_MSG
] + Format(_lc
[I_NET_MSG_CLIENT_CONN
],
1908 if not NetInitDone
then
1910 if (not g_Net_Init()) then
1912 g_Console_Add(_lc
[I_NET_MSG_FERROR
] + _lc
[I_NET_ERR_ENET
], True);
1917 NetInitDone
:= True;
1920 NetHost
:= enet_host_create(nil, 1, NET_CHANS
, 0, 0);
1922 if (NetHost
= nil) then
1924 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CLIENT
], True);
1930 enet_address_set_host(@NetAddr
, PChar(Addr(IP
[1])));
1931 NetAddr
.port
:= Port
;
1933 NetPeer
:= enet_host_connect(NetHost
, @NetAddr
, NET_CHANS
, NET_PROTOCOL_VER
);
1935 if (NetPeer
= nil) then
1937 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CLIENT
], True);
1938 enet_host_destroy(NetHost
);
1944 // предупредить что ждем слишком долго через N секунд
1945 TimeoutTime
:= sys_GetTicks() + NET_CONNECT_TIMEOUT
;
1950 while (enet_host_service(NetHost
, @NetEvent
, 0) > 0) do
1952 if (NetEvent
.kind
= ENET_EVENT_TYPE_CONNECT
) then
1954 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_CLIENT_DONE
]);
1955 NetMode
:= NET_CLIENT
;
1957 enet_peer_timeout(NetPeer
, ENET_PEER_TIMEOUT_LIMIT
* 2, ENET_PEER_TIMEOUT_MINIMUM
* 2, ENET_PEER_TIMEOUT_MAXIMUM
* 2);
1959 NetClientPort
:= Port
;
1966 T
:= sys_GetTicks();
1967 if T
> TimeoutTime
then
1969 TimeoutTime
:= T
+ NET_CONNECT_TIMEOUT
* 100; // одного предупреждения хватит
1970 g_Console_Add(_lc
[I_NET_MSG_TIMEOUT_WARN
], True);
1971 g_Console_Add(Format(_lc
[I_NET_MSG_PORTS
], [Integer(Port
), Integer(NET_PING_PORT
)]), True);
1974 ProcessLoading(true);
1976 if e_KeyPressed(IK_SPACE
) or e_KeyPressed(IK_ESCAPE
) or e_KeyPressed(VK_ESCAPE
) or
1977 e_KeyPressed(JOY0_JUMP
) or e_KeyPressed(JOY1_JUMP
) or e_KeyPressed(JOY2_JUMP
) or e_KeyPressed(JOY3_JUMP
) then
1981 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_TIMEOUT
], True);
1982 g_Console_Add(Format(_lc
[I_NET_MSG_PORTS
], [Integer(Port
), Integer(NET_PING_PORT
)]), True);
1983 if NetPeer
<> nil then enet_peer_reset(NetPeer
);
1984 if NetHost
<> nil then
1986 enet_host_destroy(NetHost
);
1993 function IpToStr(IP
: LongWord): string;
1998 Result
:= IntToStr(PByte(Ptr
+ 0)^) + '.';
1999 Result
:= Result
+ IntToStr(PByte(Ptr
+ 1)^) + '.';
2000 Result
:= Result
+ IntToStr(PByte(Ptr
+ 2)^) + '.';
2001 Result
:= Result
+ IntToStr(PByte(Ptr
+ 3)^);
2004 function StrToIp(IPstr
: string; var IP
: LongWord): Boolean;
2008 Result
:= enet_address_set_host(@EAddr
, PChar(@IPstr
[1])) = 0;
2012 function g_Net_Client_ByName(Name
: string): pTNetClient
;
2018 for a
:= Low(NetClients
) to High(NetClients
) do
2019 if (NetClients
[a
].Used
) and (NetClients
[a
].State
= NET_STATE_GAME
) then
2021 pl
:= g_Player_Get(NetClients
[a
].Player
);
2022 if pl
= nil then continue
;
2023 if Copy(LowerCase(pl
.Name
), 1, Length(Name
)) <> LowerCase(Name
) then continue
;
2024 if NetClients
[a
].Peer
<> nil then
2026 Result
:= @NetClients
[a
];
2032 function g_Net_Client_ByPlayer(PID
: Word): pTNetClient
;
2037 for a
:= Low(NetClients
) to High(NetClients
) do
2038 if (NetClients
[a
].Used
) and (NetClients
[a
].State
= NET_STATE_GAME
) then
2039 if NetClients
[a
].Player
= PID
then
2041 Result
:= @NetClients
[a
];
2046 function g_Net_ClientName_ByID(ID
: Integer): string;
2052 if ID
= NET_EVERYONE
then
2054 for a
:= Low(NetClients
) to High(NetClients
) do
2055 if (NetClients
[a
].ID
= ID
) and (NetClients
[a
].Used
) and (NetClients
[a
].State
= NET_STATE_GAME
) then
2057 pl
:= g_Player_Get(NetClients
[a
].Player
);
2058 if pl
= nil then Exit
;
2063 procedure g_Net_SendData(Data
: AByte
; peer
: pENetPeer
; Reliable
: Boolean; Chan
: Byte = NET_CHAN_DOWNLOAD
);
2067 dataLength
: Cardinal;
2069 dataLength
:= Length(Data
);
2072 F
:= LongWord(ENET_PACKET_FLAG_RELIABLE
)
2076 if (peer
<> nil) then
2078 P
:= enet_packet_create(@Data
[0], dataLength
, F
);
2079 if not Assigned(P
) then Exit
;
2080 enet_peer_send(peer
, Chan
, P
);
2084 P
:= enet_packet_create(@Data
[0], dataLength
, F
);
2085 if not Assigned(P
) then Exit
;
2086 enet_host_broadcast(NetHost
, Chan
, P
);
2089 enet_host_flush(NetHost
);
2092 function g_Net_IsHostBanned(IP
: LongWord; Perm
: Boolean = False): Boolean;
2097 if NetBannedHosts
= nil then
2099 for I
:= 0 to High(NetBannedHosts
) do
2100 if (NetBannedHosts
[I
].IP
= IP
) and ((not Perm
) or (NetBannedHosts
[I
].Perm
)) then
2107 procedure g_Net_BanHost(IP
: LongWord; Perm
: Boolean = True); overload
;
2113 if g_Net_IsHostBanned(IP
, Perm
) then
2117 for I
:= Low(NetBannedHosts
) to High(NetBannedHosts
) do
2118 if NetBannedHosts
[I
].IP
= 0 then
2126 SetLength(NetBannedHosts
, Length(NetBannedHosts
) + 1);
2127 P
:= High(NetBannedHosts
);
2130 NetBannedHosts
[P
].IP
:= IP
;
2131 NetBannedHosts
[P
].Perm
:= Perm
;
2134 procedure g_Net_BanHost(IP
: string; Perm
: Boolean = True); overload
;
2139 b
:= StrToIp(IP
, a
);
2141 g_Net_BanHost(a
, Perm
);
2144 procedure g_Net_UnbanNonPermHosts();
2148 if NetBannedHosts
= nil then
2150 for I
:= Low(NetBannedHosts
) to High(NetBannedHosts
) do
2151 if (NetBannedHosts
[I
].IP
> 0) and not NetBannedHosts
[I
].Perm
then
2153 NetBannedHosts
[I
].IP
:= 0;
2154 NetBannedHosts
[I
].Perm
:= True;
2158 function g_Net_UnbanHost(IP
: string): Boolean; overload
;
2162 Result
:= StrToIp(IP
, a
);
2164 Result
:= g_Net_UnbanHost(a
);
2167 function g_Net_UnbanHost(IP
: LongWord): Boolean; overload
;
2174 if NetBannedHosts
= nil then
2176 for I
:= 0 to High(NetBannedHosts
) do
2177 if NetBannedHosts
[I
].IP
= IP
then
2179 NetBannedHosts
[I
].IP
:= 0;
2180 NetBannedHosts
[I
].Perm
:= True;
2182 // no break here to clear all bans of this host, perm and non-perm
2186 procedure g_Net_SaveBanList();
2192 path
:= e_GetWriteableDir(DataDirs
);
2195 path
:= e_CatPath(path
, BANLIST_FILENAME
);
2198 if NetBannedHosts
<> nil then
2199 for I
:= 0 to High(NetBannedHosts
) do
2200 if NetBannedHosts
[I
].Perm
and (NetBannedHosts
[I
].IP
> 0) then
2201 Writeln(F
, IpToStr(NetBannedHosts
[I
].IP
));
2206 procedure g_Net_DumpStart();
2208 if NetMode
= NET_SERVER
then
2209 NetDumpFile
:= e_CreateResource(LogDirs
, NETDUMP_FILENAME
+ '_server')
2211 NetDumpFile
:= e_CreateResource(LogDirs
, NETDUMP_FILENAME
+ '_client');
2214 procedure g_Net_DumpSendBuffer();
2216 writeInt(NetDumpFile
, gTime
);
2217 writeInt(NetDumpFile
, LongWord(NetOut
.CurSize
));
2218 writeInt(NetDumpFile
, Byte(1));
2219 NetDumpFile
.WriteBuffer(NetOut
.Data
^, NetOut
.CurSize
);
2222 procedure g_Net_DumpRecvBuffer(Buf
: penet_uint8
; Len
: LongWord);
2224 if (Buf
= nil) or (Len
= 0) then Exit
;
2225 writeInt(NetDumpFile
, gTime
);
2226 writeInt(NetDumpFile
, Len
);
2227 writeInt(NetDumpFile
, Byte(0));
2228 NetDumpFile
.WriteBuffer(Buf
^, Len
);
2231 procedure g_Net_DumpEnd();
2237 function g_Net_ForwardPorts(ForwardPongPort
: Boolean = True): Boolean;
2238 {$IFDEF USE_MINIUPNPC}
2243 LanAddr
: array [0..255] of Char;
2244 StrPort
: AnsiString;
2249 if NetPortForwarded
= NetPort
then
2255 NetPongForwarded
:= False;
2256 NetPortForwarded
:= 0;
2258 DevList
:= upnpDiscover(1000, nil, nil, 0, 0, 2, Addr(Err
));
2259 if DevList
= nil then
2261 conwritefln('port forwarding failed: upnpDiscover() failed: %d', [Err
]);
2265 I
:= UPNP_GetValidIGD(DevList
, @Urls
, @Data
, Addr(LanAddr
[0]), 256);
2269 conwriteln('port forwarding failed: could not find an IGD device on this LAN');
2270 FreeUPNPDevList(DevList
);
2271 FreeUPNPUrls(@Urls
);
2275 StrPort
:= IntToStr(NetPort
);
2276 I
:= UPNP_AddPortMapping(
2277 Urls
.controlURL
, Addr(data
.first
.servicetype
[1]),
2278 PChar(StrPort
), PChar(StrPort
), Addr(LanAddr
[0]), PChar('D2DF'),
2279 PChar('UDP'), nil, PChar('0')
2284 conwritefln('forwarding port %d failed: error %d', [NetPort
, I
]);
2285 FreeUPNPDevList(DevList
);
2286 FreeUPNPUrls(@Urls
);
2290 if ForwardPongPort
then
2292 StrPort
:= IntToStr(NET_PING_PORT
);
2293 I
:= UPNP_AddPortMapping(
2294 Urls
.controlURL
, Addr(data
.first
.servicetype
[1]),
2295 PChar(StrPort
), PChar(StrPort
), Addr(LanAddr
[0]), PChar('D2DF'),
2296 PChar('UDP'), nil, PChar('0')
2301 conwritefln('forwarding port %d failed: error %d', [NetPort
+ 1, I
]);
2302 NetPongForwarded
:= False;
2306 conwritefln('forwarded port %d successfully', [NetPort
+ 1]);
2307 NetPongForwarded
:= True;
2311 conwritefln('forwarded port %d successfully', [NetPort
]);
2312 NetIGDControl
:= AnsiString(Urls
.controlURL
);
2313 NetIGDService
:= data
.first
.servicetype
;
2314 NetPortForwarded
:= NetPort
;
2316 FreeUPNPDevList(DevList
);
2317 FreeUPNPUrls(@Urls
);
2326 procedure g_Net_UnforwardPorts();
2327 {$IFDEF USE_MINIUPNPC}
2330 StrPort
: AnsiString;
2332 if NetPortForwarded
= 0 then Exit
;
2334 conwriteln('unforwarding ports...');
2336 StrPort
:= IntToStr(NetPortForwarded
);
2337 I
:= UPNP_DeletePortMapping(
2338 PChar(NetIGDControl
), Addr(NetIGDService
[1]),
2339 PChar(StrPort
), PChar('UDP'), nil
2341 conwritefln(' port %d: %d', [NetPortForwarded
, I
]);
2343 if NetPongForwarded
then
2345 NetPongForwarded
:= False;
2346 StrPort
:= IntToStr(NetPortForwarded
+ 1);
2347 I
:= UPNP_DeletePortMapping(
2348 PChar(NetIGDControl
), Addr(NetIGDService
[1]),
2349 PChar(StrPort
), PChar('UDP'), nil
2351 conwritefln(' port %d: %d', [NetPortForwarded
+ 1, I
]);
2354 NetPortForwarded
:= 0;
2363 conRegVar('cl_downloadtimeout', @g_Net_DownloadTimeout
, 0.0, 1000000.0, '', 'timeout in seconds, 0 to disable it');
2364 SetLength(NetClients
, 0);
2365 g_Net_DownloadTimeout
:= 60;
2366 NetIn
.Alloc(NET_BUFSIZE
);
2367 NetOut
.Alloc(NET_BUFSIZE
);
2368 NetBuf
[NET_UNRELIABLE
].Alloc(NET_BUFSIZE
*2);
2369 NetBuf
[NET_RELIABLE
].Alloc(NET_BUFSIZE
*2);
2370 trans_omsg
.Alloc(NET_BUFSIZE
);
2374 NetBuf
[NET_UNRELIABLE
].Free();
2375 NetBuf
[NET_RELIABLE
].Free();