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
, utils
, ENet
, Classes
, md5
, MAPDEF
{$IFDEF USE_MINIUPNPC}, miniupnpc
;{$ELSE};{$ENDIF}
24 NET_PROTOCOL_VER
= 185;
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';
76 TNetMapResourceInfo
= record
77 wadName
: AnsiString; // wad file name, without a path
78 size
: Integer; // wad file size (-1: size and hash are not known)
79 hash
: TMD5Digest
; // wad hash
82 TNetMapResourceInfoArray
= array of TNetMapResourceInfo
;
84 TNetFileTransfer
= record
88 size
: Integer; // file size in bytes
90 lastSentChunk
: Integer;
91 lastAckChunk
: Integer;
92 lastAckTime
: Int64; // msecs; if not "in progress", we're waiting for the first ack
94 diskBuffer
: PChar; // of `chunkSize` bytes
104 RequestedFullUpdate
: Boolean;
105 WaitForFirstSpawn
: Boolean; // set to `true` in server, used to spawn a player on first full state request
108 Transfer
: TNetFileTransfer
; // only one transfer may be active
109 NetOut
: array [0..1] of TMsg
;
115 pTNetClient
= ^TNetClient
;
117 AByte
= array of Byte;
120 NetInitDone
: Boolean = False;
121 NetMode
: Byte = NET_NONE
;
122 NetDump
: Boolean = False;
124 NetServerName
: string = 'Unnamed Server';
125 NetPassword
: string = '';
126 NetPort
: Word = 25666;
128 NetAllowRCON
: Boolean = False;
129 NetRCONPassword
: string = '';
131 NetTimeToUpdate
: Cardinal = 0;
132 NetTimeToReliable
: Cardinal = 0;
133 NetTimeToMaster
: Cardinal = 0;
135 NetHost
: pENetHost
= nil;
136 NetPeer
: pENetPeer
= nil;
138 NetAddr
: ENetAddress
;
140 NetPongAddr
: ENetAddress
;
141 NetPongSock
: ENetSocket
= ENET_SOCKET_NULL
;
143 NetUseMaster
: Boolean = True;
144 NetMasterList
: string = 'mpms.doom2d.org:25665, deadsoftware.ru:25665';
146 NetClientIP
: string = '127.0.0.1';
147 NetClientPort
: Word = 25666;
150 NetBuf
: array [0..1] of TMsg
;
152 NetClients
: array of TNetClient
;
153 NetClientCount
: Byte = 0;
154 NetMaxClients
: Byte = 255;
155 NetBannedHosts
: array of TBanRecord
;
157 NetState
: Integer = NET_STATE_NONE
;
159 NetMyID
: Integer = -1;
160 NetPlrUID1
: Integer = -1;
161 NetPlrUID2
: Integer = -1;
163 NetInterpLevel
: Integer = 1;
164 NetUpdateRate
: Cardinal = 0; // as soon as possible
165 NetRelupdRate
: Cardinal = 18; // around two times a second
166 NetMasterRate
: Cardinal = 60000;
168 NetForcePlayerUpdate
: Boolean = False;
169 NetPredictSelf
: Boolean = True;
170 NetForwardPorts
: Boolean = False;
172 NetGotEverything
: Boolean = False;
173 NetGotKeys
: Boolean = False;
175 NetDeafLevel
: Integer = 0;
177 {$IFDEF USE_MINIUPNPC}
178 NetPortForwarded
: Word = 0;
179 NetPongForwarded
: Boolean = False;
180 NetIGDControl
: AnsiString;
181 NetIGDService
: TURLStr
;
184 NetPortThread
: TThreadID
= NilThreadId
;
186 NetDumpFile
: TStream
;
188 g_Res_received_map_start
: Integer = 0; // set if we received "map change" event
191 function g_Net_Init(): Boolean;
192 procedure g_Net_Cleanup();
193 procedure g_Net_Free();
194 procedure g_Net_Flush();
196 function g_Net_Host(IPAddr
: LongWord; Port
: enet_uint16
; MaxClients
: Cardinal = 16): Boolean;
197 procedure g_Net_Host_Die();
198 procedure g_Net_Host_Send(ID
: Integer; Reliable
: Boolean; Chan
: Byte = NET_CHAN_GAME
);
199 function g_Net_Host_Update(): enet_size_t
;
201 function g_Net_Connect(IP
: string; Port
: enet_uint16
): Boolean;
202 procedure g_Net_Disconnect(Forced
: Boolean = False);
203 procedure g_Net_Client_Send(Reliable
: Boolean; Chan
: Byte = NET_CHAN_GAME
);
204 function g_Net_Client_Update(): enet_size_t
;
205 function g_Net_Client_UpdateWhileLoading(): enet_size_t
;
207 function g_Net_Client_ByName(Name
: string): pTNetClient
;
208 function g_Net_Client_ByPlayer(PID
: Word): pTNetClient
;
209 function g_Net_ClientName_ByID(ID
: Integer): string;
211 procedure g_Net_SendData(Data
: AByte
; peer
: pENetPeer
; Reliable
: Boolean; Chan
: Byte = NET_CHAN_DOWNLOAD
);
212 //function g_Net_Wait_Event(msgId: Word): TMemoryStream;
213 //function g_Net_Wait_FileInfo (var tf: TNetFileTransfer; asMap: Boolean; out resList: TStringList): Integer;
215 function IpToStr(IP
: LongWord): string;
216 function StrToIp(IPstr
: string; var IP
: LongWord): Boolean;
218 function g_Net_IsHostBanned(IP
: LongWord; Perm
: Boolean = False): Boolean;
219 procedure g_Net_BanHost(IP
: LongWord; Perm
: Boolean = True); overload
;
220 procedure g_Net_BanHost(IP
: string; Perm
: Boolean = True); overload
;
221 function g_Net_UnbanHost(IP
: string): Boolean; overload
;
222 function g_Net_UnbanHost(IP
: LongWord): Boolean; overload
;
223 procedure g_Net_UnbanNonPermHosts();
224 procedure g_Net_SaveBanList();
226 procedure g_Net_DumpStart();
227 procedure g_Net_DumpSendBuffer();
228 procedure g_Net_DumpRecvBuffer(Buf
: penet_uint8
; Len
: LongWord);
229 procedure g_Net_DumpEnd();
231 function g_Net_ForwardPorts(ForwardPongPort
: Boolean = True): Boolean;
232 procedure g_Net_UnforwardPorts();
234 function g_Net_UserRequestExit
: Boolean;
236 function g_Net_Wait_MapInfo (var tf
: TNetFileTransfer
; var resList
: TNetMapResourceInfoArray
): Integer;
237 function g_Net_RequestResFileInfo (resIndex
: LongInt; out tf
: TNetFileTransfer
): Integer;
238 function g_Net_AbortResTransfer (var tf
: TNetFileTransfer
): Boolean;
239 function g_Net_ReceiveResourceFile (resIndex
: LongInt; var tf
: TNetFileTransfer
; strm
: TStream
): Integer;
241 function g_Net_IsNetworkAvailable (): Boolean;
242 procedure g_Net_InitLowLevel ();
243 procedure g_Net_DeinitLowLevel ();
245 procedure NetServerCVars(P
: SSArray
);
250 // *enet_host_service()*
251 // fuck! https://www.mail-archive.com/enet-discuss@cubik.org/msg00852.html
252 // tl;dr: on shitdows, we can get -1 sometimes, and it is *NOT* a failure.
253 // thank you, enet. let's ignore failures altogether then.
257 e_input
, e_res
, g_options
,
258 g_nethandler
, g_netmsg
, g_netmaster
, g_player
, g_window
, g_console
,
259 g_game
, g_language
, g_weapons
, ctypes
, g_system
, g_map
;
262 FILE_CHUNK_SIZE
= 8192;
265 enet_init_success
: Boolean = false;
266 g_Net_DownloadTimeout
: Single;
270 function g_Net_IsNetworkAvailable (): Boolean;
272 result
:= enet_init_success
;
275 procedure g_Net_InitLowLevel ();
278 v
:= enet_linked_version();
279 e_LogWritefln('ENet Version: %s.%s.%s', [ENET_VERSION_GET_MAJOR(v
), ENET_VERSION_GET_MINOR(v
), ENET_VERSION_GET_PATCH(v
)]);
280 if enet_init_success
then raise Exception
.Create('wuta?!');
281 enet_init_success
:= (enet_initialize() = 0);
284 procedure g_Net_DeinitLowLevel ();
286 if enet_init_success
then
289 enet_init_success
:= false;
294 //**************************************************************************
298 //**************************************************************************
300 procedure clearNetClientTransfers (var nc
: TNetClient
);
302 nc
.Transfer
.stream
.Free
;
303 nc
.Transfer
.diskName
:= ''; // just in case
304 if (nc
.Transfer
.diskBuffer
<> nil) then FreeMem(nc
.Transfer
.diskBuffer
);
305 nc
.Transfer
.stream
:= nil;
306 nc
.Transfer
.diskBuffer
:= nil;
310 procedure clearNetClient (var nc
: TNetClient
);
312 clearNetClientTransfers(nc
);
316 procedure clearNetClients (clearArray
: Boolean);
320 for f
:= Low(NetClients
) to High(NetClients
) do clearNetClient(NetClients
[f
]);
321 if (clearArray
) then SetLength(NetClients
, 0);
325 function g_Net_UserRequestExit (): Boolean;
327 Result
:= {e_KeyPressed(IK_SPACE) or}
328 e_KeyPressed(IK_ESCAPE
) or
329 e_KeyPressed(VK_ESCAPE
) or
330 e_KeyPressed(JOY0_JUMP
) or
331 e_KeyPressed(JOY1_JUMP
) or
332 e_KeyPressed(JOY2_JUMP
) or
333 e_KeyPressed(JOY3_JUMP
)
337 //**************************************************************************
339 // file transfer declaraions and host packet processor
341 //**************************************************************************
344 // server packet type
345 NTF_SERVER_DONE
= 10; // done with this file
346 NTF_SERVER_FILE_INFO
= 11; // sent after client request
347 NTF_SERVER_CHUNK
= 12; // next chunk; chunk number follows
348 NTF_SERVER_ABORT
= 13; // server abort
349 NTF_SERVER_MAP_INFO
= 14;
351 // client packet type
352 NTF_CLIENT_MAP_REQUEST
= 100; // map file request; also, returns list of additional wads to download
353 NTF_CLIENT_FILE_REQUEST
= 101; // resource file request (by index)
354 NTF_CLIENT_ABORT
= 102; // do not send requested file, or abort current transfer
355 NTF_CLIENT_START
= 103; // start transfer; client may resume download by sending non-zero starting chunk
356 NTF_CLIENT_ACK
= 104; // chunk ack; chunk number follows
359 // disconnect client due to some file transfer error
360 procedure killClientByFT (var nc
: TNetClient
);
362 e_LogWritefln('disconnected client #%d due to file transfer error', [nc
.ID
], TMsgType
.Warning
);
363 enet_peer_disconnect(nc
.Peer
, NET_DISC_FILE_TIMEOUT
);
364 clearNetClientTransfers(nc
);
365 g_Net_Slist_ServerPlayerLeaves();
369 // send file transfer message from server to client
370 function ftransSendServerMsg (var nc
: TNetClient
; var m
: TMsg
): Boolean;
375 if (m
.CurSize
< 1) then exit
;
376 pkt
:= enet_packet_create(m
.Data
, m
.CurSize
, ENET_PACKET_FLAG_RELIABLE
);
377 if not Assigned(pkt
) then begin killClientByFT(nc
); exit
; end;
378 if (enet_peer_send(nc
.Peer
, NET_CHAN_DOWNLOAD_EX
, pkt
) <> 0) then begin killClientByFT(nc
); exit
; end;
383 // send file transfer message from client to server
384 function ftransSendClientMsg (var m
: TMsg
): Boolean;
389 if (m
.CurSize
< 1) then exit
;
390 pkt
:= enet_packet_create(m
.Data
, m
.CurSize
, ENET_PACKET_FLAG_RELIABLE
);
391 if not Assigned(pkt
) then exit
;
392 if (enet_peer_send(NetPeer
, NET_CHAN_DOWNLOAD_EX
, pkt
) <> 0) then exit
;
398 procedure ProcessChunkSend (var nc
: TNetClient
);
400 tf
: ^TNetFileTransfer
;
406 if (tf
.stream
= nil) then exit
;
408 // arbitrary timeout number
409 if (ct
-tf
.lastAckTime
>= 5000) then
414 // check if we need to send something
415 if (not tf
.inProgress
) then exit
; // waiting for the initial ack
416 // ok, we're sending chunks
417 if (tf
.lastAckChunk
<> tf
.lastSentChunk
) then exit
;
418 Inc(tf
.lastSentChunk
);
419 // do it one chunk at a time; client ack will advance our chunk counter
420 chunks
:= (tf
.size
+tf
.chunkSize
-1) div tf
.chunkSize
;
422 if (tf
.lastSentChunk
> chunks
) then
429 if (tf
.lastSentChunk
= chunks
) then
431 // we're done with this file
432 e_LogWritefln('download: client #%d, DONE sending chunks #%d/#%d', [nc
.ID
, tf
.lastSentChunk
, chunks
]);
433 trans_omsg
.Write(Byte(NTF_SERVER_DONE
));
434 clearNetClientTransfers(nc
);
439 trans_omsg
.Write(Byte(NTF_SERVER_CHUNK
));
440 trans_omsg
.Write(LongInt(tf
.lastSentChunk
));
442 rd
:= tf
.size
-(tf
.lastSentChunk
*tf
.chunkSize
);
443 if (rd
> tf
.chunkSize
) then rd
:= tf
.chunkSize
;
444 trans_omsg
.Write(LongInt(rd
));
445 //e_LogWritefln('download: client #%d, sending chunk #%d/#%d (%d bytes)', [nc.ID, tf.lastSentChunk, chunks, rd]);
446 //FIXME: check for errors here
448 tf
.stream
.Seek(tf
.lastSentChunk
*tf
.chunkSize
, soFromBeginning
);
449 tf
.stream
.ReadBuffer(tf
.diskBuffer
^, rd
);
450 trans_omsg
.WriteData(tf
.diskBuffer
, rd
);
457 ftransSendServerMsg(nc
, trans_omsg
);
461 // server file transfer packet processor
462 // received packet is in `NetEvent`
463 procedure ProcessDownloadExPacket ();
470 tf
: ^TNetFileTransfer
;
480 // find client index by peer
481 for f
:= Low(NetClients
) to High(NetClients
) do
483 if (not NetClients
[f
].Used
) then continue
;
484 if (NetClients
[f
].Peer
= NetEvent
.peer
) then
490 //e_LogWritefln('RECEIVE: dlpacket; client=%d (datalen=%u)', [nid, NetEvent.packet^.dataLength]);
492 if (nid
< 0) then exit
; // wtf?!
493 nc
:= @NetClients
[nid
];
495 if (NetEvent
.packet
^.dataLength
= 0) then
501 tf
:= @NetClients
[nid
].Transfer
;
502 tf
.lastAckTime
:= GetTimerMS();
504 cmd
:= Byte(NetEvent
.packet
^.data
^);
505 //e_LogWritefln('RECEIVE: nid=%d; cmd=%u', [nid, cmd]);
507 NTF_CLIENT_FILE_REQUEST
: // file request
509 if (tf
.stream
<> nil) then
514 if (NetEvent
.packet
^.dataLength
< 2) then
519 // new transfer request; build packet
520 if not msg
.Init(NetEvent
.packet
^.data
+1, NetEvent
.packet
^.dataLength
-1, True) then
525 // get resource index
526 ridx
:= msg
.ReadLongInt();
527 if (ridx
< -1) or (ridx
>= length(gExternalResources
)) then
529 e_LogWritefln('Invalid resource index %d', [ridx
], TMsgType
.Warning
);
533 if (ridx
< 0) then fname
:= gGameSettings
.WAD
else fname
:= gExternalResources
[ridx
].diskName
;
534 if (length(fname
) = 0) then
536 e_WriteLog('Invalid filename: '+fname
, TMsgType
.Warning
);
540 tf
.diskName
:= findDiskWad(fname
);
541 if (length(tf
.diskName
) = 0) then
543 e_LogWritefln('NETWORK: file "%s" not found!', [fname
], TMsgType
.Fatal
);
548 //tf.hash := MD5File(tf.diskName);
549 if (ridx
< 0) then tf
.hash
:= gWADHash
else tf
.hash
:= gExternalResources
[ridx
].hash
;
550 // create file stream
551 tf
.diskName
:= findDiskWad(fname
);
553 tf
.stream
:= openDiskFileRO(tf
.diskName
);
557 if (tf
.stream
= nil) then
559 e_WriteLog(Format('NETWORK: file "%s" not found!', [fname
]), TMsgType
.Fatal
);
563 e_LogWritefln('client #%d requested resource #%d (file is `%s` : `%s`)', [nc
.ID
, ridx
, fname
, tf
.diskName
]);
564 tf
.size
:= tf
.stream
.size
;
565 tf
.chunkSize
:= FILE_CHUNK_SIZE
; // arbitrary
566 tf
.lastSentChunk
:= -1;
567 tf
.lastAckChunk
:= -1;
568 tf
.lastAckTime
:= GetTimerMS();
569 tf
.inProgress
:= False; // waiting for the first ACK or for the cancel
570 GetMem(tf
.diskBuffer
, tf
.chunkSize
);
571 // sent file info message
573 trans_omsg
.Write(Byte(NTF_SERVER_FILE_INFO
));
574 trans_omsg
.Write(tf
.hash
);
575 trans_omsg
.Write(tf
.size
);
576 trans_omsg
.Write(tf
.chunkSize
);
577 trans_omsg
.Write(ExtractFileName(fname
));
578 if not ftransSendServerMsg(nc
^, trans_omsg
) then exit
;
580 NTF_CLIENT_ABORT
: // do not send requested file, or abort current transfer
582 e_LogWritefln('client #%d aborted file transfer', [nc
.ID
]);
583 clearNetClientTransfers(nc
^);
585 NTF_CLIENT_START
: // start transfer; client may resume download by sending non-zero starting chunk
587 if not Assigned(tf
.stream
) then
592 if (tf
.lastSentChunk
<> -1) or (tf
.lastAckChunk
<> -1) or (tf
.inProgress
) then
594 // double ack, get lost
598 if (NetEvent
.packet
^.dataLength
< 2) then
604 if not msg
.Init(NetEvent
.packet
^.data
+1, NetEvent
.packet
^.dataLength
-1, True) then
609 chunk
:= msg
.ReadLongInt();
610 if (chunk
< 0) or (chunk
> (tf
.size
+tf
.chunkSize
-1) div tf
.chunkSize
) then
615 e_LogWritefln('client #%d started file transfer from chunk %d', [nc
.ID
, chunk
]);
616 // start sending chunks
617 tf
.inProgress
:= True;
618 tf
.lastSentChunk
:= chunk
-1;
619 tf
.lastAckChunk
:= chunk
-1;
620 ProcessChunkSend(nc
^);
622 NTF_CLIENT_ACK
: // chunk ack; chunk number follows
624 if not Assigned(tf
.stream
) then
629 if (tf
.lastSentChunk
< 0) or (not tf
.inProgress
) then
631 // double ack, get lost
635 if (NetEvent
.packet
^.dataLength
< 2) then
641 if not msg
.Init(NetEvent
.packet
^.data
+1, NetEvent
.packet
^.dataLength
-1, True) then
646 chunk
:= msg
.ReadLongInt();
647 if (chunk
< 0) or (chunk
> (tf
.size
+tf
.chunkSize
-1) div tf
.chunkSize
) then
652 // do it this way, so client may seek, or request retransfers for some reason
653 tf
.lastAckChunk
:= chunk
;
654 tf
.lastSentChunk
:= chunk
;
655 //e_LogWritefln('client #%d acked file transfer chunk %d', [nc.ID, chunk]);
656 ProcessChunkSend(nc
^);
658 NTF_CLIENT_MAP_REQUEST
:
660 e_LogWritefln('client #%d requested map info', [nc
.ID
]);
662 dfn
:= findDiskWad(gGameSettings
.WAD
);
663 if (dfn
= '') then dfn
:= '!wad_not_found!.wad'; //FIXME
664 //md5 := MD5File(dfn);
666 if (not GetDiskFileInfo(dfn
, fi
)) then
668 e_LogWritefln('client #%d requested map info, but i cannot get file info', [nc
.ID
]);
674 st := openDiskFileRO(dfn);
675 if not assigned(st) then exit; //wtf?!
680 trans_omsg
.Write(Byte(NTF_SERVER_MAP_INFO
));
682 trans_omsg
.Write(ExtractFileName(gGameSettings
.WAD
));
684 trans_omsg
.Write(md5
);
686 trans_omsg
.Write(size
);
687 // number of external resources for map
688 trans_omsg
.Write(LongInt(length(gExternalResources
)));
689 // external resource names
690 for f
:= 0 to High(gExternalResources
) do
693 //trans_omsg.Write(ExtractFileName(gExternalResources[f])); // GameDir+'/wads/'+ResList.Strings[i]
695 trans_omsg
.Write('!');
696 trans_omsg
.Write(LongInt(gExternalResources
[f
].size
));
697 trans_omsg
.Write(gExternalResources
[f
].hash
);
698 trans_omsg
.Write(ExtractFileName(gExternalResources
[f
].diskName
));
701 if not ftransSendServerMsg(nc
^, trans_omsg
) then exit
;
712 //**************************************************************************
714 // file transfer crap (both client and server)
716 //**************************************************************************
718 function getNewTimeoutEnd (): Int64;
720 result
:= GetTimerMS();
721 if (g_Net_DownloadTimeout
<= 0) then
723 result
:= result
+1000*60*3; // 3 minutes
727 result
:= result
+trunc(g_Net_DownloadTimeout
*1000);
732 // send map request to server, and wait for "map info" server reply
734 // returns `false` on error or user abort
736 // diskName: map wad file name (without a path)
737 // hash: map wad hash
738 // size: map wad size
739 // chunkSize: set too
740 // resList: list of resource wads
746 // for maps, first `tf.diskName` name will be map wad name, and `tf.hash`/`tf.size` will contain map info
747 function g_Net_Wait_MapInfo (var tf
: TNetFileTransfer
; var resList
: TNetMapResourceInfoArray
): Integer;
753 freePacket
: Boolean = false;
758 ri
: ^TNetMapResourceInfo
;
760 SetLength(resList
, 0);
764 trans_omsg
.Write(Byte(NTF_CLIENT_MAP_REQUEST
));
765 if not ftransSendClientMsg(trans_omsg
) then begin result
:= -1; exit
; end;
767 FillChar(ev
, SizeOf(ev
), 0);
770 ett
:= getNewTimeoutEnd();
772 status
:= enet_host_service(NetHost
, @ev
, 300);
776 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' network error', True);
781 if (status
<= 0) then
787 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' timeout reached', True);
796 ENET_EVENT_TYPE_RECEIVE
:
799 if (ev
.channelID
<> NET_CHAN_DOWNLOAD_EX
) then
801 //e_LogWritefln('g_Net_Wait_MapInfo: skip message from non-transfer channel', []);
803 g_Net_Client_HandlePacket(ev
.packet
, g_Net_ClientLightMsgHandler
);
804 if (g_Res_received_map_start
< 0) then begin result
:= -666; exit
; end;
808 ett
:= getNewTimeoutEnd();
809 if (ev
.packet
.dataLength
< 1) then
811 e_LogWritefln('g_Net_Wait_MapInfo: invalid server packet (no data)', []);
815 Ptr
:= ev
.packet
^.data
;
816 rMsgId
:= Byte(Ptr
^);
817 e_LogWritefln('g_Net_Wait_MapInfo: got message %u from server (dataLength=%u)', [rMsgId
, ev
.packet
^.dataLength
]);
818 if (rMsgId
= NTF_SERVER_FILE_INFO
) then
820 e_LogWritefln('g_Net_Wait_MapInfo: waiting for map info reply, but got file info reply', []);
824 else if (rMsgId
= NTF_SERVER_ABORT
) then
826 e_LogWritefln('g_Net_Wait_MapInfo: server aborted transfer', []);
830 else if (rMsgId
= NTF_SERVER_MAP_INFO
) then
832 e_LogWritefln('g_Net_Wait_MapInfo: creating map info packet...', []);
833 if not msg
.Init(ev
.packet
^.data
+1, ev
.packet
^.dataLength
-1, True) then exit
;
834 e_LogWritefln('g_Net_Wait_MapInfo: parsing map info packet (rd=%d; max=%d)...', [msg
.ReadCount
, msg
.MaxSize
]);
835 SetLength(resList
, 0); // just in case
837 tf
.diskName
:= msg
.ReadString();
838 e_LogWritefln('g_Net_Wait_MapInfo: map wad is `%s`', [tf
.diskName
]);
840 tf
.hash
:= msg
.ReadMD5();
842 tf
.size
:= msg
.ReadLongInt();
843 e_LogWritefln('g_Net_Wait_MapInfo: map wad size is %d', [tf
.size
]);
844 // number of external resources for map
845 rc
:= msg
.ReadLongInt();
846 if (rc
< 0) or (rc
> 1024) then
848 e_LogWritefln('g_Net_Wait_Event: invalid number of map external resources (%d)', [rc
]);
852 e_LogWritefln('g_Net_Wait_MapInfo: map external resource count is %d', [rc
]);
853 SetLength(resList
, rc
);
854 // external resource names
855 for f
:= 0 to rc
-1 do
858 s
:= msg
.ReadString();
859 if (length(s
) = 0) then begin result
:= -1; exit
; end;
863 ri
.size
:= msg
.ReadLongInt();
864 ri
.hash
:= msg
.ReadMD5();
865 ri
.wadName
:= ExtractFileName(msg
.ReadString());
866 if (length(ri
.wadName
) = 0) or (ri
.size
< 0) then begin result
:= -1; exit
; end;
870 // old-style packet, only name
871 ri
.wadName
:= ExtractFileName(s
);
872 if (length(ri
.wadName
) = 0) then begin result
:= -1; exit
; end;
873 ri
.size
:= -1; // unknown
876 e_LogWritefln('g_Net_Wait_MapInfo: got map info', []);
877 Result
:= 0; // success
882 e_LogWritefln('g_Net_Wait_Event: invalid server packet type', []);
888 ENET_EVENT_TYPE_DISCONNECT
:
890 if (ev
.data
<= NET_DISC_MAX
) then
891 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' ' + _lc
[TStrings_Locale(Cardinal(I_NET_DISC_NONE
) + ev
.data
)], True);
897 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' unknown ENet event ' + IntToStr(Ord(ev
.kind
)), True);
902 if (freePacket
) then begin freePacket
:= false; enet_packet_destroy(ev
.packet
); end;
905 if g_Net_UserRequestExit() then
907 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' user abort', True);
913 if (freePacket
) then enet_packet_destroy(ev
.packet
);
918 // send file request to server, and wait for server reply
920 // returns `false` on error or user abort
922 // diskName (actually, base name)
931 // for maps, first `tf.diskName` name will be map wad name, and `tf.hash`/`tf.size` will contain map info
932 function g_Net_RequestResFileInfo (resIndex
: LongInt; out tf
: TNetFileTransfer
): Integer;
938 freePacket
: Boolean = false;
944 trans_omsg
.Write(Byte(NTF_CLIENT_FILE_REQUEST
));
945 trans_omsg
.Write(resIndex
);
946 if not ftransSendClientMsg(trans_omsg
) then begin result
:= -1; exit
; end;
948 FillChar(ev
, SizeOf(ev
), 0);
951 ett
:= getNewTimeoutEnd();
953 status
:= enet_host_service(NetHost
, @ev
, 300);
957 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' network error', True);
962 if (status
<= 0) then
968 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' timeout reached', True);
977 ENET_EVENT_TYPE_RECEIVE
:
980 if (ev
.channelID
<> NET_CHAN_DOWNLOAD_EX
) then
982 //e_LogWriteln('g_Net_Wait_Event: skip message from non-transfer channel');
984 g_Net_Client_HandlePacket(ev
.packet
, g_Net_ClientLightMsgHandler
);
985 if (g_Res_received_map_start
< 0) then begin result
:= -666; exit
; end;
989 ett
:= getNewTimeoutEnd();
990 if (ev
.packet
.dataLength
< 1) then
992 e_LogWriteln('g_Net_Wait_Event: invalid server packet (no data)');
996 Ptr
:= ev
.packet
^.data
;
997 rMsgId
:= Byte(Ptr
^);
998 e_LogWritefln('received transfer packet with id %d (%u bytes)', [rMsgId
, ev
.packet
^.dataLength
]);
999 if (rMsgId
= NTF_SERVER_FILE_INFO
) then
1001 if not msg
.Init(ev
.packet
^.data
+1, ev
.packet
^.dataLength
-1, True) then exit
;
1002 tf
.hash
:= msg
.ReadMD5();
1003 tf
.size
:= msg
.ReadLongInt();
1004 tf
.chunkSize
:= msg
.ReadLongInt();
1005 tf
.diskName
:= ExtractFileName(msg
.readString());
1006 if (tf
.size
< 0) or (tf
.chunkSize
<> FILE_CHUNK_SIZE
) or (length(tf
.diskName
) = 0) then
1008 e_LogWritefln('g_Net_RequestResFileInfo: invalid file info packet', []);
1012 e_LogWritefln('got file info for resource #%d: size=%d; name=%s', [resIndex
, tf
.size
, tf
.diskName
]);
1013 Result
:= 0; // success
1016 else if (rMsgId
= NTF_SERVER_ABORT
) then
1018 e_LogWriteln('g_Net_RequestResFileInfo: server aborted transfer');
1022 else if (rMsgId
= NTF_SERVER_MAP_INFO
) then
1024 e_LogWriteln('g_Net_RequestResFileInfo: waiting for map info reply, but got file info reply');
1030 e_LogWriteln('g_Net_RequestResFileInfo: invalid server packet type');
1036 ENET_EVENT_TYPE_DISCONNECT
:
1038 if (ev
.data
<= NET_DISC_MAX
) then
1039 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' ' + _lc
[TStrings_Locale(Cardinal(I_NET_DISC_NONE
) + ev
.data
)], True);
1045 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' unknown ENet event ' + IntToStr(Ord(ev
.kind
)), True);
1050 if (freePacket
) then begin freePacket
:= false; enet_packet_destroy(ev
.packet
); end;
1053 if g_Net_UserRequestExit() then
1055 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' user abort', True);
1061 if (freePacket
) then enet_packet_destroy(ev
.packet
);
1066 // call this to cancel file transfer requested by `g_Net_RequestResFileInfo()`
1067 function g_Net_AbortResTransfer (var tf
: TNetFileTransfer
): Boolean;
1070 e_LogWritefln('aborting file transfer...', []);
1073 trans_omsg
.Write(Byte(NTF_CLIENT_ABORT
));
1074 result
:= ftransSendClientMsg(trans_omsg
);
1075 if result
then enet_host_flush(NetHost
);
1079 // call this to start file transfer requested by `g_Net_RequestResFileInfo()`
1081 // returns `false` on error or user abort
1090 // 2 on server abort
1091 // for maps, first `tf.diskName` name will be map wad name, and `tf.hash`/`tf.size` will contain map info
1092 function g_Net_ReceiveResourceFile (resIndex
: LongInt; var tf
: TNetFileTransfer
; strm
: TStream
): Integer;
1098 freePacket
: Boolean = false;
1101 nextChunk
: Integer = 0;
1102 chunkTotal
: Integer;
1109 tf
.resumed
:= false;
1110 e_LogWritefln('file `%s`, size=%d (%d)', [tf
.diskName
, Integer(strm
.size
), tf
.size
], TMsgType
.Notify
);
1111 // check if we should resume downloading
1112 resumed
:= (strm
.size
> tf
.chunkSize
) and (strm
.size
< tf
.size
);
1115 trans_omsg
.Write(Byte(NTF_CLIENT_START
));
1116 if resumed
then chunk
:= strm
.size
div tf
.chunkSize
else chunk
:= 0;
1117 trans_omsg
.Write(LongInt(chunk
));
1118 if not ftransSendClientMsg(trans_omsg
) then begin result
:= -1; exit
; end;
1120 strm
.Seek(chunk
*tf
.chunkSize
, soFromBeginning
);
1121 chunkTotal
:= (tf
.size
+tf
.chunkSize
-1) div tf
.chunkSize
;
1122 e_LogWritefln('receiving file `%s` (%d chunks)', [tf
.diskName
, chunkTotal
], TMsgType
.Notify
);
1123 g_Game_SetLoadingText('downloading "'+ExtractFileName(tf
.diskName
)+'"', chunkTotal
, False);
1124 tf
.resumed
:= resumed
;
1126 if (chunk
> 0) then g_Game_StepLoading(chunk
);
1129 // wait for reply data
1130 FillChar(ev
, SizeOf(ev
), 0);
1132 GetMem(buf
, tf
.chunkSize
);
1134 ett
:= getNewTimeoutEnd();
1136 //stx := -GetTimerMS();
1137 status
:= enet_host_service(NetHost
, @ev
, 300);
1139 if (status < 0) then
1141 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' network error', True);
1146 if (status
<= 0) then
1148 // check for timeout
1152 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' timeout reached', True);
1161 ENET_EVENT_TYPE_RECEIVE
:
1164 if (ev
.channelID
<> NET_CHAN_DOWNLOAD_EX
) then
1166 //e_LogWritefln('g_Net_Wait_Event: skip message from non-transfer channel', []);
1167 freePacket
:= false;
1168 g_Net_Client_HandlePacket(ev
.packet
, g_Net_ClientLightMsgHandler
);
1169 if (g_Res_received_map_start
< 0) then begin result
:= -666; exit
; end;
1173 //stx := stx+GetTimerMS();
1174 //e_LogWritefln('g_Net_ReceiveResourceFile: stx=%d', [Integer(stx)]);
1175 //stx := -GetTimerMS();
1176 ett
:= getNewTimeoutEnd();
1177 if (ev
.packet
.dataLength
< 1) then
1179 e_LogWritefln('g_Net_ReceiveResourceFile: invalid server packet (no data)', []);
1183 Ptr
:= ev
.packet
^.data
;
1184 rMsgId
:= Byte(Ptr
^);
1185 if (rMsgId
= NTF_SERVER_DONE
) then
1187 e_LogWritefln('file transfer complete.', []);
1191 else if (rMsgId
= NTF_SERVER_CHUNK
) then
1193 if not msg
.Init(ev
.packet
^.data
+1, ev
.packet
^.dataLength
-1, True) then exit
;
1194 chunk
:= msg
.ReadLongInt();
1195 csize
:= msg
.ReadLongInt();
1196 if (chunk
<> nextChunk
) then
1198 e_LogWritefln('received chunk %d, but expected chunk %d', [chunk
, nextChunk
]);
1202 if (csize
< 0) or (csize
> tf
.chunkSize
) then
1204 e_LogWritefln('received chunk with size %d, but expected chunk size is %d', [csize
, tf
.chunkSize
]);
1208 //e_LogWritefln('got chunk #%d of #%d (csize=%d)', [chunk, (tf.size+tf.chunkSize-1) div tf.chunkSize, csize]);
1209 msg
.ReadData(buf
, csize
);
1210 strm
.WriteBuffer(buf
^, csize
);
1211 nextChunk
:= chunk
+1;
1212 g_Game_StepLoading();
1215 trans_omsg
.Write(Byte(NTF_CLIENT_ACK
));
1216 trans_omsg
.Write(LongInt(chunk
));
1217 if not ftransSendClientMsg(trans_omsg
) then begin result
:= -1; exit
; end;
1219 else if (rMsgId
= NTF_SERVER_ABORT
) then
1221 e_LogWritefln('g_Net_ReceiveResourceFile: server aborted transfer', []);
1227 e_LogWritefln('g_Net_ReceiveResourceFile: invalid server packet type', []);
1231 //stx := stx+GetTimerMS();
1232 //e_LogWritefln('g_Net_ReceiveResourceFile: process stx=%d', [Integer(stx)]);
1235 ENET_EVENT_TYPE_DISCONNECT
:
1237 if (ev
.data
<= NET_DISC_MAX
) then
1238 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' ' + _lc
[TStrings_Locale(Cardinal(I_NET_DISC_NONE
) + ev
.data
)], True);
1244 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' unknown ENet event ' + IntToStr(Ord(ev
.kind
)), True);
1249 if (freePacket
) then begin freePacket
:= false; enet_packet_destroy(ev
.packet
); end;
1252 if g_Net_UserRequestExit() then
1254 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' user abort', True);
1261 if (freePacket
) then enet_packet_destroy(ev
.packet
);
1266 //**************************************************************************
1270 //**************************************************************************
1272 function g_Net_FindSlot(): Integer;
1281 for I
:= Low(NetClients
) to High(NetClients
) do
1283 if NetClients
[I
].Used
then
1292 if C
>= NetMaxClients
then
1300 if (Length(NetClients
) >= NetMaxClients
) then
1304 SetLength(NetClients
, Length(NetClients
) + 1);
1305 N
:= High(NetClients
);
1311 NetClients
[N
].Used
:= True;
1312 NetClients
[N
].ID
:= N
;
1313 NetClients
[N
].RequestedFullUpdate
:= False;
1314 NetClients
[N
].WaitForFirstSpawn
:= False;
1315 NetClients
[N
].RCONAuth
:= False;
1316 NetClients
[N
].Voted
:= False;
1317 NetClients
[N
].Player
:= 0;
1318 clearNetClientTransfers(NetClients
[N
]); // just in case
1325 function g_Net_Init(): Boolean;
1334 NetBuf
[NET_UNRELIABLE
].Clear();
1335 NetBuf
[NET_RELIABLE
].Clear();
1336 //SetLength(NetClients, 0);
1337 clearNetClients(true); // clear array
1343 NetAddr
.port
:= 25666;
1344 SetLength(NetBannedHosts
, 0);
1345 path
:= BANLIST_FILENAME
;
1346 if e_FindResource(DataDirs
, path
) = true then
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 NetHost
:= enet_host_create(@NetAddr
, NET_MAXCLIENTS
, NET_CHANS
, 0, 0);
1502 if (NetHost
= nil) then
1504 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + Format(_lc
[I_NET_ERR_HOST
], [Port
]));
1510 if NetForwardPorts
then NetPortThread
:= BeginThread(ForwardThread
);
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
) or (NetHost
= nil) 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(NetHost
.address
.port
);
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 (NetHost
<> nil) and (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
:= GetTickCount64() + 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
:= GetTickCount64();
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();
2189 path
:= e_GetWriteableDir(DataDirs
);
2192 path
:= e_CatPath(path
, BANLIST_FILENAME
);
2195 if NetBannedHosts
<> nil then
2196 for I
:= 0 to High(NetBannedHosts
) do
2197 if NetBannedHosts
[I
].Perm
and (NetBannedHosts
[I
].IP
> 0) then
2198 Writeln(F
, IpToStr(NetBannedHosts
[I
].IP
));
2203 procedure g_Net_DumpStart();
2205 if NetMode
= NET_SERVER
then
2206 NetDumpFile
:= e_CreateResource(LogDirs
, NETDUMP_FILENAME
+ '_server')
2208 NetDumpFile
:= e_CreateResource(LogDirs
, NETDUMP_FILENAME
+ '_client');
2211 procedure g_Net_DumpSendBuffer();
2213 writeInt(NetDumpFile
, gTime
);
2214 writeInt(NetDumpFile
, LongWord(NetOut
.CurSize
));
2215 writeInt(NetDumpFile
, Byte(1));
2216 NetDumpFile
.WriteBuffer(NetOut
.Data
^, NetOut
.CurSize
);
2219 procedure g_Net_DumpRecvBuffer(Buf
: penet_uint8
; Len
: LongWord);
2221 if (Buf
= nil) or (Len
= 0) then Exit
;
2222 writeInt(NetDumpFile
, gTime
);
2223 writeInt(NetDumpFile
, Len
);
2224 writeInt(NetDumpFile
, Byte(0));
2225 NetDumpFile
.WriteBuffer(Buf
^, Len
);
2228 procedure g_Net_DumpEnd();
2234 function g_Net_ForwardPorts(ForwardPongPort
: Boolean = True): Boolean;
2235 {$IFDEF USE_MINIUPNPC}
2240 LanAddr
: array [0..255] of Char;
2241 StrPort
: AnsiString;
2246 if NetHost
= nil then
2249 if NetPortForwarded
= NetHost
.address
.port
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(NetHost
.address
.port
);
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', [NetHost
.address
.port
, 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', [NET_PING_PORT
, I
]);
2302 NetPongForwarded
:= False;
2306 conwritefln('forwarded port %d successfully', [NET_PING_PORT
]);
2307 NetPongForwarded
:= True;
2311 conwritefln('forwarded port %d successfully', [NetHost
.address
.port
]);
2312 NetIGDControl
:= AnsiString(Urls
.controlURL
);
2313 NetIGDService
:= data
.first
.servicetype
;
2314 NetPortForwarded
:= NetHost
.address
.port
;
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(NET_PING_PORT
);
2347 I
:= UPNP_DeletePortMapping(
2348 PChar(NetIGDControl
), Addr(NetIGDService
[1]),
2349 PChar(StrPort
), PChar('UDP'), nil
2351 conwritefln(' port %d: %d', [NET_PING_PORT
, I
]);
2354 NetPortForwarded
:= 0;
2361 procedure NetServerCVars(P
: SSArray
);
2366 cmd
:= LowerCase(P
[0]);
2370 if (Length(P
) > 1) and (Length(P
[1]) > 0) then
2372 NetServerName
:= P
[1];
2373 if Length(NetServerName
) > 64 then
2374 SetLength(NetServerName
, 64);
2375 g_Net_Slist_ServerRenamed();
2377 g_Console_Add(cmd
+ ' "' + NetServerName
+ '"');
2381 if (Length(P
) > 1) and (Length(P
[1]) > 0) then
2383 NetPassword
:= P
[1];
2384 if Length(NetPassword
) > 24 then
2385 SetLength(NetPassword
, 24);
2386 g_Net_Slist_ServerRenamed();
2388 g_Console_Add(cmd
+ ' "' + AnsiLowerCase(NetPassword
) + '"');
2392 if (Length(P
) > 1) then
2394 NetMaxClients
:= nclamp(StrToIntDef(P
[1], NetMaxClients
), 1, NET_MAXCLIENTS
);
2395 if g_Game_IsServer
and g_Game_IsNet
then
2398 for a
:= 0 to High(NetClients
) do
2400 if NetClients
[a
].Used
then
2403 if b
> NetMaxClients
then
2405 s
:= g_Player_Get(NetClients
[a
].Player
).Name
;
2406 enet_peer_disconnect(NetClients
[a
].Peer
, NET_DISC_FULL
);
2407 g_Console_Add(Format(_lc
[I_PLAYER_KICK
], [s
]));
2408 MH_SEND_GameEvent(NET_EV_PLAYER_KICK
, 0, s
);
2412 g_Net_Slist_ServerRenamed();
2415 g_Console_Add(cmd
+ ' ' + IntToStr(NetMaxClients
));
2419 if (Length(P
) > 1) then
2421 NetUseMaster
:= StrToIntDef(P
[1], Byte(NetUseMaster
)) <> 0;
2422 if NetUseMaster
then g_Net_Slist_Public() else g_Net_Slist_Private();
2424 g_Console_Add(cmd
+ ' ' + IntToStr(Byte(NetUseMaster
)));
2428 if (Length(P
) > 1) then
2430 if not g_Game_IsNet
then
2431 NetPort
:= nclamp(StrToIntDef(P
[1], NetPort
), 0, $FFFF)
2433 g_Console_Add(_lc
[I_MSG_NOT_NETGAME
]);
2435 g_Console_Add(cmd
+ ' ' + IntToStr(Ord(NetUseMaster
)));
2441 conRegVar('cl_downloadtimeout', @g_Net_DownloadTimeout
, 0.0, 1000000.0, '', 'timeout in seconds, 0 to disable it');
2442 conRegVar('cl_predictself', @NetPredictSelf
, '', 'predict local player');
2443 conRegVar('cl_forceplayerupdate', @NetForcePlayerUpdate
, '', 'update net players on NET_MSG_PLRPOS');
2444 conRegVar('cl_interp', @NetInterpLevel
, '', 'net player interpolation steps');
2445 conRegVar('cl_last_ip', @NetClientIP
, '', 'address of the last you have connected to');
2446 conRegVar('cl_last_port', @NetClientPort
, '', 'port of the last server you have connected to');
2447 conRegVar('cl_deafen', @NetDeafLevel
, '', 'filter server messages (0-3)');
2449 conRegVar('sv_forwardports', @NetForwardPorts
, '', 'forward server port using miniupnpc (requires server restart)');
2450 conRegVar('sv_rcon', @NetAllowRCON
, '', 'enable remote console');
2451 conRegVar('sv_rcon_password', @NetRCONPassword
, '', 'remote console password');
2452 conRegVar('sv_update_interval', @NetUpdateRate
, '', 'unreliable update interval');
2453 conRegVar('sv_reliable_interval', @NetRelupdRate
, '', 'reliable update interval');
2454 conRegVar('sv_master_interval', @NetMasterRate
, '', 'master server update interval');
2456 conRegVar('net_master_list', @NetMasterList
, '', 'list of master servers');
2458 SetLength(NetClients
, 0);
2459 g_Net_DownloadTimeout
:= 60;
2460 NetIn
.Alloc(NET_BUFSIZE
);
2461 NetOut
.Alloc(NET_BUFSIZE
);
2462 NetBuf
[NET_UNRELIABLE
].Alloc(NET_BUFSIZE
*2);
2463 NetBuf
[NET_RELIABLE
].Alloc(NET_BUFSIZE
*2);
2464 trans_omsg
.Alloc(NET_BUFSIZE
);
2468 NetBuf
[NET_UNRELIABLE
].Free();
2469 NetBuf
[NET_RELIABLE
].Free();