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
= 188;
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
111 Transfer
: TNetFileTransfer
; // only one transfer may be active
112 NetOut
: array [0..1] of TMsg
;
118 pTNetClient
= ^TNetClient
;
120 AByte
= array of Byte;
123 NetInitDone
: Boolean = False;
124 NetMode
: Byte = NET_NONE
;
125 NetDump
: Boolean = False;
127 NetServerName
: string = 'Unnamed Server';
128 NetPassword
: string = '';
129 NetPort
: Word = 25666;
131 NetAllowRCON
: Boolean = False;
132 NetRCONPassword
: string = '';
134 NetTimeToUpdate
: Cardinal = 0;
135 NetTimeToReliable
: Cardinal = 0;
136 NetTimeToMaster
: Cardinal = 0;
138 NetHost
: pENetHost
= nil;
139 NetPeer
: pENetPeer
= nil;
141 NetAddr
: ENetAddress
;
143 NetPongAddr
: ENetAddress
;
144 NetPongSock
: ENetSocket
= ENET_SOCKET_NULL
;
146 NetUseMaster
: Boolean = True;
147 NetMasterList
: string = 'mpms.doom2d.org:25665, deadsoftware.ru:25665';
149 NetClientIP
: string = '127.0.0.1';
150 NetClientPort
: Word = 25666;
153 NetBuf
: array [0..1] of TMsg
;
155 NetClients
: array of TNetClient
;
156 NetClientCount
: Byte = 0;
157 NetMaxClients
: Byte = 255;
158 NetBannedHosts
: array of TBanRecord
;
160 NetAutoBanLimit
: Integer = 5;
161 NetAutoBanPerm
: Boolean = True;
162 NetAutoBanWarn
: Boolean = False;
163 NetAutoBanForTimeout
: Boolean = False;
165 NetAuthTimeout
: Integer = 30 * 1000;
166 NetPacketTimeout
: Integer = 60 * 1000;
168 NetState
: Integer = NET_STATE_NONE
;
170 NetMyID
: Integer = -1;
171 NetPlrUID1
: Integer = -1;
172 NetPlrUID2
: Integer = -1;
174 NetInterpLevel
: Integer = 1;
175 NetUpdateRate
: Cardinal = 0; // as soon as possible
176 NetRelupdRate
: Cardinal = 18; // around two times a second
177 NetMasterRate
: Cardinal = 60000;
179 NetForcePlayerUpdate
: Boolean = False;
180 NetPredictSelf
: Boolean = True;
181 NetForwardPorts
: Boolean = False;
183 NetGotEverything
: Boolean = False;
184 NetGotKeys
: Boolean = False;
186 NetDeafLevel
: Integer = 0;
188 {$IFDEF USE_MINIUPNPC}
189 NetPortForwarded
: Word = 0;
190 NetPongForwarded
: Boolean = False;
191 NetIGDControl
: AnsiString;
192 NetIGDService
: TURLStr
;
195 NetPortThread
: TThreadID
= NilThreadId
;
197 NetDumpFile
: TStream
;
199 g_Res_received_map_start
: Integer = 0; // set if we received "map change" event
202 function g_Net_Init(): Boolean;
203 procedure g_Net_Cleanup();
204 procedure g_Net_Free();
205 procedure g_Net_Flush();
207 function g_Net_Host(IPAddr
: LongWord; Port
: enet_uint16
; MaxClients
: Cardinal = 16): Boolean;
208 procedure g_Net_Host_Die();
209 procedure g_Net_Host_Send(ID
: Integer; Reliable
: Boolean; Chan
: Byte = NET_CHAN_GAME
);
210 procedure g_Net_Host_Update();
212 function g_Net_Connect(IP
: string; Port
: enet_uint16
): Boolean;
213 procedure g_Net_Disconnect(Forced
: Boolean = False);
214 procedure g_Net_Client_Send(Reliable
: Boolean; Chan
: Byte = NET_CHAN_GAME
);
215 procedure g_Net_Client_Update();
216 procedure g_Net_Client_UpdateWhileLoading();
218 function g_Net_Client_ByName(Name
: string): pTNetClient
;
219 function g_Net_Client_ByPlayer(PID
: Word): pTNetClient
;
220 function g_Net_ClientName_ByID(ID
: Integer): string;
222 procedure g_Net_SendData(Data
: AByte
; peer
: pENetPeer
; Reliable
: Boolean; Chan
: Byte = NET_CHAN_DOWNLOAD
);
223 //function g_Net_Wait_Event(msgId: Word): TMemoryStream;
224 //function g_Net_Wait_FileInfo (var tf: TNetFileTransfer; asMap: Boolean; out resList: TStringList): Integer;
226 function IpToStr(IP
: LongWord): string;
227 function StrToIp(IPstr
: string; var IP
: LongWord): Boolean;
229 function g_Net_IsHostBanned(IP
: LongWord; Perm
: Boolean = False): Boolean;
230 procedure g_Net_BanHost(IP
: LongWord; Perm
: Boolean = True); overload
;
231 procedure g_Net_BanHost(IP
: string; Perm
: Boolean = True); overload
;
232 function g_Net_UnbanHost(IP
: string): Boolean; overload
;
233 function g_Net_UnbanHost(IP
: LongWord): Boolean; overload
;
234 procedure g_Net_UnbanNonPermHosts();
235 procedure g_Net_SaveBanList();
237 procedure g_Net_Penalize(C
: pTNetClient
; Reason
: string);
239 procedure g_Net_DumpStart();
240 procedure g_Net_DumpSendBuffer();
241 procedure g_Net_DumpRecvBuffer(Buf
: penet_uint8
; Len
: LongWord);
242 procedure g_Net_DumpEnd();
244 function g_Net_ForwardPorts(ForwardPongPort
: Boolean = True): Boolean;
245 procedure g_Net_UnforwardPorts();
247 function g_Net_UserRequestExit
: Boolean;
249 function g_Net_Wait_MapInfo (var tf
: TNetFileTransfer
; var resList
: TNetMapResourceInfoArray
): Integer;
250 function g_Net_RequestResFileInfo (resIndex
: LongInt; out tf
: TNetFileTransfer
): Integer;
251 function g_Net_AbortResTransfer (var tf
: TNetFileTransfer
): Boolean;
252 function g_Net_ReceiveResourceFile (resIndex
: LongInt; var tf
: TNetFileTransfer
; strm
: TStream
): Integer;
254 function g_Net_IsNetworkAvailable (): Boolean;
255 procedure g_Net_InitLowLevel ();
256 procedure g_Net_DeinitLowLevel ();
258 procedure NetServerCVars(P
: SSArray
);
263 // *enet_host_service()*
264 // fuck! https://www.mail-archive.com/enet-discuss@cubik.org/msg00852.html
265 // tl;dr: on shitdows, we can get -1 sometimes, and it is *NOT* a failure.
266 // thank you, enet. let's ignore failures altogether then.
271 g_nethandler
, g_netmsg
, g_netmaster
, g_player
, g_window
, g_console
,
272 g_main
, g_game
, g_language
, g_weapons
, ctypes
, g_system
, g_map
;
275 FILE_CHUNK_SIZE
= 8192;
278 enet_init_success
: Boolean = false;
279 g_Net_DownloadTimeout
: Single;
283 function g_Net_IsNetworkAvailable (): Boolean;
285 result
:= enet_init_success
;
288 procedure g_Net_InitLowLevel ();
291 v
:= enet_linked_version();
292 e_LogWritefln('ENet Version: %s.%s.%s', [ENET_VERSION_GET_MAJOR(v
), ENET_VERSION_GET_MINOR(v
), ENET_VERSION_GET_PATCH(v
)]);
293 if enet_init_success
then raise Exception
.Create('wuta?!');
294 enet_init_success
:= (enet_initialize() = 0);
297 procedure g_Net_DeinitLowLevel ();
299 if enet_init_success
then
302 enet_init_success
:= false;
307 //**************************************************************************
311 //**************************************************************************
313 procedure clearNetClientTransfers (var nc
: TNetClient
);
315 nc
.Transfer
.stream
.Free
;
316 nc
.Transfer
.diskName
:= ''; // just in case
317 if (nc
.Transfer
.diskBuffer
<> nil) then FreeMem(nc
.Transfer
.diskBuffer
);
318 nc
.Transfer
.stream
:= nil;
319 nc
.Transfer
.diskBuffer
:= nil;
323 procedure clearNetClient (var nc
: TNetClient
);
325 clearNetClientTransfers(nc
);
329 procedure clearNetClients (clearArray
: Boolean);
333 for f
:= Low(NetClients
) to High(NetClients
) do clearNetClient(NetClients
[f
]);
334 if (clearArray
) then SetLength(NetClients
, 0);
338 function g_Net_UserRequestExit (): Boolean;
340 Result
:= {e_KeyPressed(IK_SPACE) or}
341 e_KeyPressed(IK_ESCAPE
) or
342 e_KeyPressed(VK_ESCAPE
) or
343 e_KeyPressed(JOY0_JUMP
) or
344 e_KeyPressed(JOY1_JUMP
) or
345 e_KeyPressed(JOY2_JUMP
) or
346 e_KeyPressed(JOY3_JUMP
)
349 //**************************************************************************
351 // file transfer declaraions and host packet processor
353 //**************************************************************************
356 // server packet type
357 NTF_SERVER_DONE
= 10; // done with this file
358 NTF_SERVER_FILE_INFO
= 11; // sent after client request
359 NTF_SERVER_CHUNK
= 12; // next chunk; chunk number follows
360 NTF_SERVER_ABORT
= 13; // server abort
361 NTF_SERVER_MAP_INFO
= 14;
363 // client packet type
364 NTF_CLIENT_MAP_REQUEST
= 100; // map file request; also, returns list of additional wads to download
365 NTF_CLIENT_FILE_REQUEST
= 101; // resource file request (by index)
366 NTF_CLIENT_ABORT
= 102; // do not send requested file, or abort current transfer
367 NTF_CLIENT_START
= 103; // start transfer; client may resume download by sending non-zero starting chunk
368 NTF_CLIENT_ACK
= 104; // chunk ack; chunk number follows
371 // disconnect client due to some file transfer error
372 procedure killClientByFT (var nc
: TNetClient
);
374 e_LogWritefln('disconnected client #%d due to file transfer error', [nc
.ID
], TMsgType
.Warning
);
375 enet_peer_disconnect(nc
.Peer
, NET_DISC_FILE_TIMEOUT
);
376 clearNetClientTransfers(nc
);
377 g_Net_Slist_ServerPlayerLeaves();
381 // send file transfer message from server to client
382 function ftransSendServerMsg (var nc
: TNetClient
; var m
: TMsg
): Boolean;
387 if (m
.CurSize
< 1) then exit
;
388 pkt
:= enet_packet_create(m
.Data
, m
.CurSize
, ENET_PACKET_FLAG_RELIABLE
);
389 if not Assigned(pkt
) then begin killClientByFT(nc
); exit
; end;
390 if (enet_peer_send(nc
.Peer
, NET_CHAN_DOWNLOAD_EX
, pkt
) <> 0) then begin killClientByFT(nc
); exit
; end;
395 // send file transfer message from client to server
396 function ftransSendClientMsg (var m
: TMsg
): Boolean;
401 if (m
.CurSize
< 1) then exit
;
402 pkt
:= enet_packet_create(m
.Data
, m
.CurSize
, ENET_PACKET_FLAG_RELIABLE
);
403 if not Assigned(pkt
) then exit
;
404 if (enet_peer_send(NetPeer
, NET_CHAN_DOWNLOAD_EX
, pkt
) <> 0) then exit
;
410 procedure ProcessChunkSend (var nc
: TNetClient
);
412 tf
: ^TNetFileTransfer
;
418 if (tf
.stream
= nil) then exit
;
420 // arbitrary timeout number
421 if (ct
-tf
.lastAckTime
>= 5000) then
426 // check if we need to send something
427 if (not tf
.inProgress
) then exit
; // waiting for the initial ack
428 // ok, we're sending chunks
429 if (tf
.lastAckChunk
<> tf
.lastSentChunk
) then exit
;
430 Inc(tf
.lastSentChunk
);
431 // do it one chunk at a time; client ack will advance our chunk counter
432 chunks
:= (tf
.size
+tf
.chunkSize
-1) div tf
.chunkSize
;
434 if (tf
.lastSentChunk
> chunks
) then
441 if (tf
.lastSentChunk
= chunks
) then
443 // we're done with this file
444 e_LogWritefln('download: client #%d, DONE sending chunks #%d/#%d', [nc
.ID
, tf
.lastSentChunk
, chunks
]);
445 trans_omsg
.Write(Byte(NTF_SERVER_DONE
));
446 clearNetClientTransfers(nc
);
451 trans_omsg
.Write(Byte(NTF_SERVER_CHUNK
));
452 trans_omsg
.Write(LongInt(tf
.lastSentChunk
));
454 rd
:= tf
.size
-(tf
.lastSentChunk
*tf
.chunkSize
);
455 if (rd
> tf
.chunkSize
) then rd
:= tf
.chunkSize
;
456 trans_omsg
.Write(LongInt(rd
));
457 //e_LogWritefln('download: client #%d, sending chunk #%d/#%d (%d bytes)', [nc.ID, tf.lastSentChunk, chunks, rd]);
458 //FIXME: check for errors here
460 tf
.stream
.Seek(tf
.lastSentChunk
*tf
.chunkSize
, soFromBeginning
);
461 tf
.stream
.ReadBuffer(tf
.diskBuffer
^, rd
);
462 trans_omsg
.WriteData(tf
.diskBuffer
, rd
);
469 ftransSendServerMsg(nc
, trans_omsg
);
473 // server file transfer packet processor
474 // received packet is in `NetEvent`
475 procedure ProcessDownloadExPacket ();
482 tf
: ^TNetFileTransfer
;
492 // find client index by peer
493 for f
:= Low(NetClients
) to High(NetClients
) do
495 if (not NetClients
[f
].Used
) then continue
;
496 if (NetClients
[f
].Peer
= NetEvent
.peer
) then
502 //e_LogWritefln('RECEIVE: dlpacket; client=%d (datalen=%u)', [nid, NetEvent.packet^.dataLength]);
504 if (nid
< 0) then exit
; // wtf?!
505 nc
:= @NetClients
[nid
];
507 if (NetEvent
.packet
^.dataLength
= 0) then
513 // don't time out clients during a file transfer
514 if (NetAuthTimeout
> 0) then
515 nc
^.AuthTime
:= gTime
+ NetAuthTimeout
;
516 if (NetPacketTimeout
> 0) then
517 nc
^.MsgTime
:= gTime
+ NetPacketTimeout
;
519 tf
:= @NetClients
[nid
].Transfer
;
520 tf
.lastAckTime
:= GetTimerMS();
522 cmd
:= Byte(NetEvent
.packet
^.data
^);
523 //e_LogWritefln('RECEIVE: nid=%d; cmd=%u', [nid, cmd]);
525 NTF_CLIENT_FILE_REQUEST
: // file request
527 if (tf
.stream
<> nil) then
532 if (NetEvent
.packet
^.dataLength
< 2) then
537 // new transfer request; build packet
538 if not msg
.Init(NetEvent
.packet
^.data
+1, NetEvent
.packet
^.dataLength
-1, True) then
543 // get resource index
544 ridx
:= msg
.ReadLongInt();
545 if (ridx
< -1) or (ridx
>= length(gExternalResources
)) then
547 e_LogWritefln('Invalid resource index %d', [ridx
], TMsgType
.Warning
);
551 if (ridx
< 0) then fname
:= gGameSettings
.WAD
else fname
:= gExternalResources
[ridx
].diskName
;
552 if (length(fname
) = 0) then
554 e_WriteLog('Invalid filename: '+fname
, TMsgType
.Warning
);
558 tf
.diskName
:= findDiskWad(fname
);
559 if (length(tf
.diskName
) = 0) then
561 e_LogWritefln('NETWORK: file "%s" not found!', [fname
], TMsgType
.Fatal
);
566 //tf.hash := MD5File(tf.diskName);
567 if (ridx
< 0) then tf
.hash
:= gWADHash
else tf
.hash
:= gExternalResources
[ridx
].hash
;
568 // create file stream
569 tf
.diskName
:= findDiskWad(fname
);
571 tf
.stream
:= openDiskFileRO(tf
.diskName
);
575 if (tf
.stream
= nil) then
577 e_WriteLog(Format('NETWORK: file "%s" not found!', [fname
]), TMsgType
.Fatal
);
581 e_LogWritefln('client #%d requested resource #%d (file is `%s` : `%s`)', [nc
.ID
, ridx
, fname
, tf
.diskName
]);
582 tf
.size
:= tf
.stream
.size
;
583 tf
.chunkSize
:= FILE_CHUNK_SIZE
; // arbitrary
584 tf
.lastSentChunk
:= -1;
585 tf
.lastAckChunk
:= -1;
586 tf
.lastAckTime
:= GetTimerMS();
587 tf
.inProgress
:= False; // waiting for the first ACK or for the cancel
588 GetMem(tf
.diskBuffer
, tf
.chunkSize
);
589 // sent file info message
591 trans_omsg
.Write(Byte(NTF_SERVER_FILE_INFO
));
592 trans_omsg
.Write(tf
.hash
);
593 trans_omsg
.Write(tf
.size
);
594 trans_omsg
.Write(tf
.chunkSize
);
595 trans_omsg
.Write(ExtractFileName(fname
));
596 if not ftransSendServerMsg(nc
^, trans_omsg
) then exit
;
598 NTF_CLIENT_ABORT
: // do not send requested file, or abort current transfer
600 e_LogWritefln('client #%d aborted file transfer', [nc
.ID
]);
601 clearNetClientTransfers(nc
^);
603 NTF_CLIENT_START
: // start transfer; client may resume download by sending non-zero starting chunk
605 if not Assigned(tf
.stream
) then
610 if (tf
.lastSentChunk
<> -1) or (tf
.lastAckChunk
<> -1) or (tf
.inProgress
) then
612 // double ack, get lost
616 if (NetEvent
.packet
^.dataLength
< 2) then
622 if not msg
.Init(NetEvent
.packet
^.data
+1, NetEvent
.packet
^.dataLength
-1, True) then
627 chunk
:= msg
.ReadLongInt();
628 if (chunk
< 0) or (chunk
> (tf
.size
+tf
.chunkSize
-1) div tf
.chunkSize
) then
633 e_LogWritefln('client #%d started file transfer from chunk %d', [nc
.ID
, chunk
]);
634 // start sending chunks
635 tf
.inProgress
:= True;
636 tf
.lastSentChunk
:= chunk
-1;
637 tf
.lastAckChunk
:= chunk
-1;
638 ProcessChunkSend(nc
^);
640 NTF_CLIENT_ACK
: // chunk ack; chunk number follows
642 if not Assigned(tf
.stream
) then
647 if (tf
.lastSentChunk
< 0) or (not tf
.inProgress
) then
649 // double ack, get lost
653 if (NetEvent
.packet
^.dataLength
< 2) then
659 if not msg
.Init(NetEvent
.packet
^.data
+1, NetEvent
.packet
^.dataLength
-1, True) then
664 chunk
:= msg
.ReadLongInt();
665 if (chunk
< 0) or (chunk
> (tf
.size
+tf
.chunkSize
-1) div tf
.chunkSize
) then
670 // do it this way, so client may seek, or request retransfers for some reason
671 tf
.lastAckChunk
:= chunk
;
672 tf
.lastSentChunk
:= chunk
;
673 //e_LogWritefln('client #%d acked file transfer chunk %d', [nc.ID, chunk]);
674 ProcessChunkSend(nc
^);
676 NTF_CLIENT_MAP_REQUEST
:
678 e_LogWritefln('client #%d requested map info', [nc
.ID
]);
680 dfn
:= findDiskWad(gGameSettings
.WAD
);
681 if (dfn
= '') then dfn
:= '!wad_not_found!.wad'; //FIXME
682 //md5 := MD5File(dfn);
684 if (not GetDiskFileInfo(dfn
, fi
)) then
686 e_LogWritefln('client #%d requested map info, but i cannot get file info', [nc
.ID
]);
692 st := openDiskFileRO(dfn);
693 if not assigned(st) then exit; //wtf?!
698 trans_omsg
.Write(Byte(NTF_SERVER_MAP_INFO
));
700 trans_omsg
.Write(ExtractFileName(gGameSettings
.WAD
));
702 trans_omsg
.Write(md5
);
704 trans_omsg
.Write(size
);
705 // number of external resources for map
706 trans_omsg
.Write(LongInt(length(gExternalResources
)));
707 // external resource names
708 for f
:= 0 to High(gExternalResources
) do
711 //trans_omsg.Write(ExtractFileName(gExternalResources[f])); // GameDir+'/wads/'+ResList.Strings[i]
713 trans_omsg
.Write('!');
714 trans_omsg
.Write(LongInt(gExternalResources
[f
].size
));
715 trans_omsg
.Write(gExternalResources
[f
].hash
);
716 trans_omsg
.Write(ExtractFileName(gExternalResources
[f
].diskName
));
719 if not ftransSendServerMsg(nc
^, trans_omsg
) then exit
;
730 //**************************************************************************
732 // file transfer crap (both client and server)
734 //**************************************************************************
736 function getNewTimeoutEnd (): Int64;
738 result
:= GetTimerMS();
739 if (g_Net_DownloadTimeout
<= 0) then
741 result
:= result
+1000*60*3; // 3 minutes
745 result
:= result
+trunc(g_Net_DownloadTimeout
*1000);
750 // send map request to server, and wait for "map info" server reply
752 // returns `false` on error or user abort
754 // diskName: map wad file name (without a path)
755 // hash: map wad hash
756 // size: map wad size
757 // chunkSize: set too
758 // resList: list of resource wads
764 // for maps, first `tf.diskName` name will be map wad name, and `tf.hash`/`tf.size` will contain map info
765 function g_Net_Wait_MapInfo (var tf
: TNetFileTransfer
; var resList
: TNetMapResourceInfoArray
): Integer;
771 freePacket
: Boolean = false;
776 ri
: ^TNetMapResourceInfo
;
778 SetLength(resList
, 0);
782 trans_omsg
.Write(Byte(NTF_CLIENT_MAP_REQUEST
));
783 if not ftransSendClientMsg(trans_omsg
) then begin result
:= -1; exit
; end;
785 FillChar(ev
, SizeOf(ev
), 0);
788 ett
:= getNewTimeoutEnd();
790 status
:= enet_host_service(NetHost
, @ev
, 300);
794 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' network error', True);
799 if (status
<= 0) then
805 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' timeout reached', True);
814 ENET_EVENT_TYPE_RECEIVE
:
817 if (ev
.channelID
<> NET_CHAN_DOWNLOAD_EX
) then
819 //e_LogWritefln('g_Net_Wait_MapInfo: skip message from non-transfer channel', []);
821 g_Net_Client_HandlePacket(ev
.packet
, g_Net_ClientLightMsgHandler
);
822 if (g_Res_received_map_start
< 0) then begin result
:= -666; exit
; end;
826 ett
:= getNewTimeoutEnd();
827 if (ev
.packet
.dataLength
< 1) then
829 e_LogWritefln('g_Net_Wait_MapInfo: invalid server packet (no data)', []);
833 Ptr
:= ev
.packet
^.data
;
834 rMsgId
:= Byte(Ptr
^);
835 e_LogWritefln('g_Net_Wait_MapInfo: got message %u from server (dataLength=%u)', [rMsgId
, ev
.packet
^.dataLength
]);
836 if (rMsgId
= NTF_SERVER_FILE_INFO
) then
838 e_LogWritefln('g_Net_Wait_MapInfo: waiting for map info reply, but got file info reply', []);
842 else if (rMsgId
= NTF_SERVER_ABORT
) then
844 e_LogWritefln('g_Net_Wait_MapInfo: server aborted transfer', []);
848 else if (rMsgId
= NTF_SERVER_MAP_INFO
) then
850 e_LogWritefln('g_Net_Wait_MapInfo: creating map info packet...', []);
851 if not msg
.Init(ev
.packet
^.data
+1, ev
.packet
^.dataLength
-1, True) then exit
;
852 e_LogWritefln('g_Net_Wait_MapInfo: parsing map info packet (rd=%d; max=%d)...', [msg
.ReadCount
, msg
.MaxSize
]);
853 SetLength(resList
, 0); // just in case
855 tf
.diskName
:= msg
.ReadString();
856 e_LogWritefln('g_Net_Wait_MapInfo: map wad is `%s`', [tf
.diskName
]);
858 tf
.hash
:= msg
.ReadMD5();
860 tf
.size
:= msg
.ReadLongInt();
861 e_LogWritefln('g_Net_Wait_MapInfo: map wad size is %d', [tf
.size
]);
862 // number of external resources for map
863 rc
:= msg
.ReadLongInt();
864 if (rc
< 0) or (rc
> 1024) then
866 e_LogWritefln('g_Net_Wait_Event: invalid number of map external resources (%d)', [rc
]);
870 e_LogWritefln('g_Net_Wait_MapInfo: map external resource count is %d', [rc
]);
871 SetLength(resList
, rc
);
872 // external resource names
873 for f
:= 0 to rc
-1 do
876 s
:= msg
.ReadString();
877 if (length(s
) = 0) then begin result
:= -1; exit
; end;
881 ri
.size
:= msg
.ReadLongInt();
882 ri
.hash
:= msg
.ReadMD5();
883 ri
.wadName
:= ExtractFileName(msg
.ReadString());
884 if (length(ri
.wadName
) = 0) or (ri
.size
< 0) then begin result
:= -1; exit
; end;
888 // old-style packet, only name
889 ri
.wadName
:= ExtractFileName(s
);
890 if (length(ri
.wadName
) = 0) then begin result
:= -1; exit
; end;
891 ri
.size
:= -1; // unknown
894 e_LogWritefln('g_Net_Wait_MapInfo: got map info', []);
895 Result
:= 0; // success
900 e_LogWritefln('g_Net_Wait_Event: invalid server packet type', []);
906 ENET_EVENT_TYPE_DISCONNECT
:
908 if (ev
.data
<= NET_DISC_MAX
) then
909 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' ' + _lc
[TStrings_Locale(Cardinal(I_NET_DISC_NONE
) + ev
.data
)], True);
915 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' unknown ENet event ' + IntToStr(Ord(ev
.kind
)), True);
920 if (freePacket
) then begin freePacket
:= false; enet_packet_destroy(ev
.packet
); end;
923 if g_Net_UserRequestExit() then
925 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' user abort', True);
931 if (freePacket
) then enet_packet_destroy(ev
.packet
);
936 // send file request to server, and wait for server reply
938 // returns `false` on error or user abort
940 // diskName (actually, base name)
949 // for maps, first `tf.diskName` name will be map wad name, and `tf.hash`/`tf.size` will contain map info
950 function g_Net_RequestResFileInfo (resIndex
: LongInt; out tf
: TNetFileTransfer
): Integer;
956 freePacket
: Boolean = false;
962 trans_omsg
.Write(Byte(NTF_CLIENT_FILE_REQUEST
));
963 trans_omsg
.Write(resIndex
);
964 if not ftransSendClientMsg(trans_omsg
) then begin result
:= -1; exit
; end;
966 FillChar(ev
, SizeOf(ev
), 0);
969 ett
:= getNewTimeoutEnd();
971 status
:= enet_host_service(NetHost
, @ev
, 300);
975 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' network error', True);
980 if (status
<= 0) then
986 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' timeout reached', True);
995 ENET_EVENT_TYPE_RECEIVE
:
998 if (ev
.channelID
<> NET_CHAN_DOWNLOAD_EX
) then
1000 //e_LogWriteln('g_Net_Wait_Event: skip message from non-transfer channel');
1001 freePacket
:= false;
1002 g_Net_Client_HandlePacket(ev
.packet
, g_Net_ClientLightMsgHandler
);
1003 if (g_Res_received_map_start
< 0) then begin result
:= -666; exit
; end;
1007 ett
:= getNewTimeoutEnd();
1008 if (ev
.packet
.dataLength
< 1) then
1010 e_LogWriteln('g_Net_Wait_Event: invalid server packet (no data)');
1014 Ptr
:= ev
.packet
^.data
;
1015 rMsgId
:= Byte(Ptr
^);
1016 e_LogWritefln('received transfer packet with id %d (%u bytes)', [rMsgId
, ev
.packet
^.dataLength
]);
1017 if (rMsgId
= NTF_SERVER_FILE_INFO
) then
1019 if not msg
.Init(ev
.packet
^.data
+1, ev
.packet
^.dataLength
-1, True) then exit
;
1020 tf
.hash
:= msg
.ReadMD5();
1021 tf
.size
:= msg
.ReadLongInt();
1022 tf
.chunkSize
:= msg
.ReadLongInt();
1023 tf
.diskName
:= ExtractFileName(msg
.readString());
1024 if (tf
.size
< 0) or (tf
.chunkSize
<> FILE_CHUNK_SIZE
) or (length(tf
.diskName
) = 0) then
1026 e_LogWritefln('g_Net_RequestResFileInfo: invalid file info packet', []);
1030 e_LogWritefln('got file info for resource #%d: size=%d; name=%s', [resIndex
, tf
.size
, tf
.diskName
]);
1031 Result
:= 0; // success
1034 else if (rMsgId
= NTF_SERVER_ABORT
) then
1036 e_LogWriteln('g_Net_RequestResFileInfo: server aborted transfer');
1040 else if (rMsgId
= NTF_SERVER_MAP_INFO
) then
1042 e_LogWriteln('g_Net_RequestResFileInfo: waiting for map info reply, but got file info reply');
1048 e_LogWriteln('g_Net_RequestResFileInfo: invalid server packet type');
1054 ENET_EVENT_TYPE_DISCONNECT
:
1056 if (ev
.data
<= NET_DISC_MAX
) then
1057 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' ' + _lc
[TStrings_Locale(Cardinal(I_NET_DISC_NONE
) + ev
.data
)], True);
1063 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' unknown ENet event ' + IntToStr(Ord(ev
.kind
)), True);
1068 if (freePacket
) then begin freePacket
:= false; enet_packet_destroy(ev
.packet
); end;
1071 if g_Net_UserRequestExit() then
1073 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' user abort', True);
1079 if (freePacket
) then enet_packet_destroy(ev
.packet
);
1084 // call this to cancel file transfer requested by `g_Net_RequestResFileInfo()`
1085 function g_Net_AbortResTransfer (var tf
: TNetFileTransfer
): Boolean;
1088 e_LogWritefln('aborting file transfer...', []);
1091 trans_omsg
.Write(Byte(NTF_CLIENT_ABORT
));
1092 result
:= ftransSendClientMsg(trans_omsg
);
1093 if result
then enet_host_flush(NetHost
);
1097 // call this to start file transfer requested by `g_Net_RequestResFileInfo()`
1099 // returns `false` on error or user abort
1108 // 2 on server abort
1109 // for maps, first `tf.diskName` name will be map wad name, and `tf.hash`/`tf.size` will contain map info
1110 function g_Net_ReceiveResourceFile (resIndex
: LongInt; var tf
: TNetFileTransfer
; strm
: TStream
): Integer;
1116 freePacket
: Boolean = false;
1119 nextChunk
: Integer = 0;
1120 chunkTotal
: Integer;
1127 tf
.resumed
:= false;
1128 e_LogWritefln('file `%s`, size=%d (%d)', [tf
.diskName
, Integer(strm
.size
), tf
.size
], TMsgType
.Notify
);
1129 // check if we should resume downloading
1130 resumed
:= (strm
.size
> tf
.chunkSize
) and (strm
.size
< tf
.size
);
1133 trans_omsg
.Write(Byte(NTF_CLIENT_START
));
1134 if resumed
then chunk
:= strm
.size
div tf
.chunkSize
else chunk
:= 0;
1135 trans_omsg
.Write(LongInt(chunk
));
1136 if not ftransSendClientMsg(trans_omsg
) then begin result
:= -1; exit
; end;
1138 strm
.Seek(chunk
*tf
.chunkSize
, soFromBeginning
);
1139 chunkTotal
:= (tf
.size
+tf
.chunkSize
-1) div tf
.chunkSize
;
1140 e_LogWritefln('receiving file `%s` (%d chunks)', [tf
.diskName
, chunkTotal
], TMsgType
.Notify
);
1141 g_Game_SetLoadingText('downloading "'+ExtractFileName(tf
.diskName
)+'"', chunkTotal
, False);
1142 tf
.resumed
:= resumed
;
1144 if (chunk
> 0) then g_Game_StepLoading(chunk
);
1147 // wait for reply data
1148 FillChar(ev
, SizeOf(ev
), 0);
1150 GetMem(buf
, tf
.chunkSize
);
1152 ett
:= getNewTimeoutEnd();
1154 //stx := -GetTimerMS();
1155 status
:= enet_host_service(NetHost
, @ev
, 300);
1157 if (status < 0) then
1159 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' network error', True);
1164 if (status
<= 0) then
1166 // check for timeout
1170 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' timeout reached', True);
1179 ENET_EVENT_TYPE_RECEIVE
:
1182 if (ev
.channelID
<> NET_CHAN_DOWNLOAD_EX
) then
1184 //e_LogWritefln('g_Net_Wait_Event: skip message from non-transfer channel', []);
1185 freePacket
:= false;
1186 g_Net_Client_HandlePacket(ev
.packet
, g_Net_ClientLightMsgHandler
);
1187 if (g_Res_received_map_start
< 0) then begin result
:= -666; exit
; end;
1191 //stx := stx+GetTimerMS();
1192 //e_LogWritefln('g_Net_ReceiveResourceFile: stx=%d', [Integer(stx)]);
1193 //stx := -GetTimerMS();
1194 ett
:= getNewTimeoutEnd();
1195 if (ev
.packet
.dataLength
< 1) then
1197 e_LogWritefln('g_Net_ReceiveResourceFile: invalid server packet (no data)', []);
1201 Ptr
:= ev
.packet
^.data
;
1202 rMsgId
:= Byte(Ptr
^);
1203 if (rMsgId
= NTF_SERVER_DONE
) then
1205 e_LogWritefln('file transfer complete.', []);
1209 else if (rMsgId
= NTF_SERVER_CHUNK
) then
1211 if not msg
.Init(ev
.packet
^.data
+1, ev
.packet
^.dataLength
-1, True) then exit
;
1212 chunk
:= msg
.ReadLongInt();
1213 csize
:= msg
.ReadLongInt();
1214 if (chunk
<> nextChunk
) then
1216 e_LogWritefln('received chunk %d, but expected chunk %d', [chunk
, nextChunk
]);
1220 if (csize
< 0) or (csize
> tf
.chunkSize
) then
1222 e_LogWritefln('received chunk with size %d, but expected chunk size is %d', [csize
, tf
.chunkSize
]);
1226 //e_LogWritefln('got chunk #%d of #%d (csize=%d)', [chunk, (tf.size+tf.chunkSize-1) div tf.chunkSize, csize]);
1227 msg
.ReadData(buf
, csize
);
1228 strm
.WriteBuffer(buf
^, csize
);
1229 nextChunk
:= chunk
+1;
1230 g_Game_StepLoading();
1233 trans_omsg
.Write(Byte(NTF_CLIENT_ACK
));
1234 trans_omsg
.Write(LongInt(chunk
));
1235 if not ftransSendClientMsg(trans_omsg
) then begin result
:= -1; exit
; end;
1237 else if (rMsgId
= NTF_SERVER_ABORT
) then
1239 e_LogWritefln('g_Net_ReceiveResourceFile: server aborted transfer', []);
1245 e_LogWritefln('g_Net_ReceiveResourceFile: invalid server packet type', []);
1249 //stx := stx+GetTimerMS();
1250 //e_LogWritefln('g_Net_ReceiveResourceFile: process stx=%d', [Integer(stx)]);
1253 ENET_EVENT_TYPE_DISCONNECT
:
1255 if (ev
.data
<= NET_DISC_MAX
) then
1256 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' ' + _lc
[TStrings_Locale(Cardinal(I_NET_DISC_NONE
) + ev
.data
)], True);
1262 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' unknown ENet event ' + IntToStr(Ord(ev
.kind
)), True);
1267 if (freePacket
) then begin freePacket
:= false; enet_packet_destroy(ev
.packet
); end;
1270 if g_Net_UserRequestExit() then
1272 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' user abort', True);
1279 if (freePacket
) then enet_packet_destroy(ev
.packet
);
1284 //**************************************************************************
1288 //**************************************************************************
1290 function g_Net_FindSlot(): Integer;
1299 for I
:= Low(NetClients
) to High(NetClients
) do
1301 if NetClients
[I
].Used
then
1310 if C
>= NetMaxClients
then
1318 if (Length(NetClients
) >= NetMaxClients
) then
1322 SetLength(NetClients
, Length(NetClients
) + 1);
1323 N
:= High(NetClients
);
1329 NetClients
[N
].Used
:= True;
1330 NetClients
[N
].ID
:= N
;
1331 NetClients
[N
].RequestedFullUpdate
:= False;
1332 NetClients
[N
].WaitForFirstSpawn
:= False;
1333 NetClients
[N
].RCONAuth
:= False;
1334 NetClients
[N
].Voted
:= False;
1335 NetClients
[N
].Player
:= 0;
1336 clearNetClientTransfers(NetClients
[N
]); // just in case
1343 function g_Net_Init(): Boolean;
1352 NetBuf
[NET_UNRELIABLE
].Clear();
1353 NetBuf
[NET_RELIABLE
].Clear();
1354 //SetLength(NetClients, 0);
1355 clearNetClients(true); // clear array
1361 NetAddr
.port
:= 25666;
1362 SetLength(NetBannedHosts
, 0);
1363 path
:= BANLIST_FILENAME
;
1364 if e_FindResource(DataDirs
, path
) = true then
1371 if StrToIp(IPstr
, IP
) then
1375 g_Net_SaveBanList();
1378 //Result := (enet_initialize() = 0);
1379 Result
:= enet_init_success
;
1382 procedure g_Net_Flush();
1386 F
, Chan
: enet_uint32
;
1390 Chan
:= NET_CHAN_GAME
;
1392 if NetMode
= NET_SERVER
then
1393 for T
:= NET_UNRELIABLE
to NET_RELIABLE
do
1395 if NetBuf
[T
].CurSize
> 0 then
1397 P
:= enet_packet_create(NetBuf
[T
].Data
, NetBuf
[T
].CurSize
, F
);
1398 if not Assigned(P
) then continue
;
1399 enet_host_broadcast(NetHost
, Chan
, P
);
1403 for I
:= Low(NetClients
) to High(NetClients
) do
1405 if not NetClients
[I
].Used
then continue
;
1406 if NetClients
[I
].NetOut
[T
].CurSize
<= 0 then continue
;
1407 P
:= enet_packet_create(NetClients
[I
].NetOut
[T
].Data
, NetClients
[I
].NetOut
[T
].CurSize
, F
);
1408 if not Assigned(P
) then continue
;
1409 enet_peer_send(NetClients
[I
].Peer
, Chan
, P
);
1410 NetClients
[I
].NetOut
[T
].Clear();
1413 // next and last iteration is always RELIABLE
1414 F
:= LongWord(ENET_PACKET_FLAG_RELIABLE
);
1415 Chan
:= NET_CHAN_IMPORTANT
;
1417 else if NetMode
= NET_CLIENT
then
1418 for T
:= NET_UNRELIABLE
to NET_RELIABLE
do
1420 if NetBuf
[T
].CurSize
> 0 then
1422 P
:= enet_packet_create(NetBuf
[T
].Data
, NetBuf
[T
].CurSize
, F
);
1423 if not Assigned(P
) then continue
;
1424 enet_peer_send(NetPeer
, Chan
, P
);
1427 // next and last iteration is always RELIABLE
1428 F
:= LongWord(ENET_PACKET_FLAG_RELIABLE
);
1429 Chan
:= NET_CHAN_IMPORTANT
;
1433 procedure g_Net_Cleanup();
1437 NetBuf
[NET_UNRELIABLE
].Clear();
1438 NetBuf
[NET_RELIABLE
].Clear();
1440 //SetLength(NetClients, 0);
1441 clearNetClients(true); // clear array
1442 NetClientCount
:= 0;
1446 g_Net_Slist_ServerClosed();
1450 NetState
:= NET_STATE_NONE
;
1452 NetPongSock
:= ENET_SOCKET_NULL
;
1454 NetTimeToMaster
:= 0;
1455 NetTimeToUpdate
:= 0;
1456 NetTimeToReliable
:= 0;
1458 NetMode
:= NET_NONE
;
1460 if NetPortThread
<> NilThreadId
then
1461 WaitForThreadTerminate(NetPortThread
, 66666);
1463 NetPortThread
:= NilThreadId
;
1464 g_Net_UnforwardPorts();
1470 procedure g_Net_Free();
1474 //enet_deinitialize();
1475 NetInitDone
:= False;
1479 //**************************************************************************
1483 //**************************************************************************
1485 function ForwardThread(Param
: Pointer): PtrInt
;
1488 if not g_Net_ForwardPorts() then Result
:= -1;
1491 function g_Net_Host(IPAddr
: LongWord; Port
: enet_uint16
; MaxClients
: Cardinal = 16): Boolean;
1493 if NetMode
<> NET_NONE
then
1495 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_INGAME
]);
1502 g_Console_Add(_lc
[I_NET_MSG
] + Format(_lc
[I_NET_MSG_HOST
], [Port
]));
1503 if not NetInitDone
then
1505 if (not g_Net_Init()) then
1507 g_Console_Add(_lc
[I_NET_MSG_FERROR
] + _lc
[I_NET_ERR_ENET
]);
1512 NetInitDone
:= True;
1515 NetAddr
.host
:= IPAddr
;
1516 NetAddr
.port
:= Port
;
1518 NetHost
:= enet_host_create(@NetAddr
, NET_MAXCLIENTS
, NET_CHANS
, 0, 0);
1520 if (NetHost
= nil) then
1522 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + Format(_lc
[I_NET_ERR_HOST
], [Port
]));
1528 if NetForwardPorts
then NetPortThread
:= BeginThread(ForwardThread
);
1530 NetPongSock
:= enet_socket_create(ENET_SOCKET_TYPE_DATAGRAM
);
1531 if NetPongSock
<> ENET_SOCKET_NULL
then
1533 NetPongAddr
.host
:= IPAddr
;
1534 NetPongAddr
.port
:= NET_PING_PORT
;
1535 if enet_socket_bind(NetPongSock
, @NetPongAddr
) < 0 then
1537 enet_socket_destroy(NetPongSock
);
1538 NetPongSock
:= ENET_SOCKET_NULL
;
1541 enet_socket_set_option(NetPongSock
, ENET_SOCKOPT_NONBLOCK
, 1);
1544 NetMode
:= NET_SERVER
;
1546 NetBuf
[NET_UNRELIABLE
].Clear();
1547 NetBuf
[NET_RELIABLE
].Clear();
1553 procedure g_Net_Host_Die();
1557 if NetMode
<> NET_SERVER
then Exit
;
1559 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_HOST_DISCALL
]);
1560 for I
:= 0 to High(NetClients
) do
1561 if NetClients
[I
].Used
then
1562 enet_peer_disconnect(NetClients
[I
].Peer
, NET_DISC_DOWN
);
1564 while enet_host_service(NetHost
, @NetEvent
, 1000) > 0 do
1565 if NetEvent
.kind
= ENET_EVENT_TYPE_RECEIVE
then
1566 enet_packet_destroy(NetEvent
.packet
);
1568 for I
:= 0 to High(NetClients
) do
1569 if NetClients
[I
].Used
then
1571 FreeMemory(NetClients
[I
].Peer
^.data
);
1572 NetClients
[I
].Peer
^.data
:= nil;
1573 enet_peer_reset(NetClients
[I
].Peer
);
1574 NetClients
[I
].Peer
:= nil;
1575 NetClients
[I
].Used
:= False;
1576 NetClients
[I
].Player
:= 0;
1577 NetClients
[I
].Crimes
:= 0;
1578 NetClients
[I
].AuthTime
:= 0;
1579 NetClients
[I
].MsgTime
:= 0;
1580 NetClients
[I
].NetOut
[NET_UNRELIABLE
].Free();
1581 NetClients
[I
].NetOut
[NET_RELIABLE
].Free();
1584 clearNetClients(false); // don't clear array
1585 g_Net_Slist_ServerClosed();
1586 if NetPongSock
<> ENET_SOCKET_NULL
then
1587 enet_socket_destroy(NetPongSock
);
1589 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_HOST_DIE
]);
1590 enet_host_destroy(NetHost
);
1592 NetMode
:= NET_NONE
;
1595 e_WriteLog('NET: Server stopped', TMsgType
.Notify
);
1599 procedure g_Net_Host_Send(ID
: Integer; Reliable
: Boolean; Chan
: Byte = NET_CHAN_GAME
);
1606 T
:= NET_UNRELIABLE
;
1610 if ID
> High(NetClients
) then Exit
;
1611 if NetClients
[ID
].Peer
= nil then Exit
;
1613 NetClients
[ID
].NetOut
[T
].Write(Integer(NetOut
.CurSize
));
1614 NetClients
[ID
].NetOut
[T
].Write(NetOut
);
1619 NetBuf
[T
].Write(Integer(NetOut
.CurSize
));
1620 NetBuf
[T
].Write(NetOut
);
1623 if NetDump
then g_Net_DumpSendBuffer();
1627 procedure g_Net_Host_Disconnect_Client(ID
: Integer; Force
: Boolean = False);
1632 TC
:= @NetClients
[ID
];
1633 if (TC
= nil) then Exit
;
1634 clearNetClient(NetClients
[ID
]);
1635 if not (TC
^.Used
) then Exit
;
1637 TP
:= g_Player_Get(TC
^.Player
);
1642 TP
.Kill(K_SIMPLEKILL
, 0, HIT_DISCON
);
1643 g_Console_Add(Format(_lc
[I_PLAYER_LEAVE
], [TP
.Name
]), True);
1644 e_WriteLog('NET: Client ' + TP
.Name
+ ' [' + IntToStr(TC
^.ID
) + '] disconnected.', TMsgType
.Notify
);
1645 g_Player_Remove(TP
.UID
);
1648 if (TC
^.Peer
^.data
<> nil) then
1650 FreeMemory(TC
^.Peer
^.data
);
1651 TC
^.Peer
^.data
:= nil;
1655 enet_peer_reset(TC
^.Peer
);
1658 TC
^.State
:= NET_STATE_NONE
;
1664 TC
^.RequestedFullUpdate
:= False;
1665 TC
^.WaitForFirstSpawn
:= False;
1666 TC
^.NetOut
[NET_UNRELIABLE
].Free();
1667 TC
^.NetOut
[NET_RELIABLE
].Free();
1669 g_Console_Add(_lc
[I_NET_MSG
] + Format(_lc
[I_NET_MSG_HOST_DISC
], [ID
]));
1670 Dec(NetClientCount
);
1672 if NetUseMaster
then g_Net_Slist_ServerPlayerLeaves();
1675 procedure g_Net_Host_CheckPings();
1677 ClAddr
: ENetAddress
;
1681 Ping
: array [0..9] of Byte;
1684 if (NetPongSock
= ENET_SOCKET_NULL
) or (NetHost
= nil) then Exit
;
1686 Buf
.data
:= Addr(Ping
[0]);
1687 Buf
.dataLength
:= 2+8;
1691 Len
:= enet_socket_receive(NetPongSock
, @ClAddr
, @Buf
, 1);
1692 if Len
< 0 then Exit
;
1694 if (Ping
[0] = Ord('D')) and (Ping
[1] = Ord('F')) then
1696 ClTime
:= Int64(Addr(Ping
[2])^);
1699 NetOut
.Write(Byte(Ord('D')));
1700 NetOut
.Write(Byte(Ord('F')));
1701 NetOut
.Write(NetHost
.address
.port
);
1702 NetOut
.Write(ClTime
);
1703 TMasterHost
.writeInfo(NetOut
);
1705 if gPlayer1
<> nil then Inc(NPl
);
1706 if gPlayer2
<> nil then Inc(NPl
);
1708 NetOut
.Write(gNumBots
);
1710 Buf
.data
:= NetOut
.Data
;
1711 Buf
.dataLength
:= NetOut
.CurSize
;
1712 enet_socket_send(NetPongSock
, @ClAddr
, @Buf
, 1);
1718 procedure g_Net_Host_CheckTimeouts();
1722 for ID
:= Low(NetClients
) to High(NetClients
) do
1724 with NetClients
[ID
] do
1726 if (Peer
= nil) or (State
= NET_STATE_NONE
) then continue
;
1727 if (State
= NET_STATE_AUTH
) and (AuthTime
> 0) and (AuthTime
<= gTime
) then
1729 g_Net_Penalize(@NetClients
[ID
], 'auth taking too long');
1730 AuthTime
:= gTime
+ 1000; // do it every second to give them a chance
1732 else if (State
= NET_STATE_GAME
) and (MsgTime
> 0) and (MsgTime
<= gTime
) then
1734 // client hasn't sent packets in a while; either ban em or kick em
1735 if (NetAutoBanForTimeout
) then
1737 g_Net_Penalize(@NetClients
[ID
], 'message timeout');
1738 MsgTime
:= gTime
+ (NetPacketTimeout
div 2) + 500; // wait less for the next check
1742 e_LogWritefln('NET: client #%u (cid #%u) timed out', [ID
, Player
]);
1743 g_Net_Host_Disconnect_Client(ID
, True);
1751 procedure g_Net_Host_Update();
1760 if NetUseMaster
then g_Net_Slist_Pulse();
1761 g_Net_Host_CheckPings();
1762 g_Net_Host_CheckTimeouts();
1764 while (enet_host_service(NetHost
, @NetEvent
, 0) > 0) do
1766 case (NetEvent
.kind
) of
1767 ENET_EVENT_TYPE_CONNECT
:
1769 IP
:= IpToStr(NetEvent
.Peer
^.address
.host
);
1770 Port
:= NetEvent
.Peer
^.address
.port
;
1771 g_Console_Add(_lc
[I_NET_MSG
] +
1772 Format(_lc
[I_NET_MSG_HOST_CONN
], [IP
, Port
]));
1773 e_WriteLog('NET: Connection request from ' + IP
+ '.', TMsgType
.Notify
);
1775 if (NetEvent
.data
<> NET_PROTOCOL_VER
) then
1777 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_HOST_REJECT
] +
1778 _lc
[I_NET_DISC_PROTOCOL
]);
1779 e_WriteLog('NET: Connection request from ' + IP
+ ' rejected: version mismatch',
1781 NetEvent
.peer
^.data
:= GetMemory(SizeOf(Byte));
1782 Byte(NetEvent
.peer
^.data
^) := 255;
1783 enet_peer_disconnect(NetEvent
.peer
, NET_DISC_PROTOCOL
);
1784 enet_host_flush(NetHost
);
1788 if g_Net_IsHostBanned(NetEvent
.Peer
^.address
.host
) then
1790 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_HOST_REJECT
] +
1791 _lc
[I_NET_DISC_BAN
]);
1792 e_WriteLog('NET: Connection request from ' + IP
+ ' rejected: banned',
1794 NetEvent
.peer
^.data
:= GetMemory(SizeOf(Byte));
1795 Byte(NetEvent
.peer
^.data
^) := 255;
1796 enet_peer_disconnect(NetEvent
.Peer
, NET_DISC_BAN
);
1797 enet_host_flush(NetHost
);
1801 ID
:= g_Net_FindSlot();
1805 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_HOST_REJECT
] +
1806 _lc
[I_NET_DISC_FULL
]);
1807 e_WriteLog('NET: Connection request from ' + IP
+ ' rejected: server full',
1809 NetEvent
.Peer
^.data
:= GetMemory(SizeOf(Byte));
1810 Byte(NetEvent
.peer
^.data
^) := 255;
1811 enet_peer_disconnect(NetEvent
.peer
, NET_DISC_FULL
);
1812 enet_host_flush(NetHost
);
1816 NetClients
[ID
].Peer
:= NetEvent
.peer
;
1817 NetClients
[ID
].Peer
^.data
:= GetMemory(SizeOf(Byte));
1818 Byte(NetClients
[ID
].Peer
^.data
^) := ID
;
1819 NetClients
[ID
].State
:= NET_STATE_AUTH
;
1820 NetClients
[ID
].Player
:= 0;
1821 NetClients
[ID
].Crimes
:= 0;
1822 NetClients
[ID
].RCONAuth
:= False;
1823 NetClients
[ID
].NetOut
[NET_UNRELIABLE
].Alloc(NET_BUFSIZE
*2);
1824 NetClients
[ID
].NetOut
[NET_RELIABLE
].Alloc(NET_BUFSIZE
*2);
1825 if (NetAuthTimeout
> 0) then
1826 NetClients
[ID
].AuthTime
:= gTime
+ NetAuthTimeout
1828 NetClients
[ID
].AuthTime
:= 0;
1829 if (NetPacketTimeout
> 0) then
1830 NetClients
[ID
].MsgTime
:= gTime
+ NetPacketTimeout
1832 NetClients
[ID
].MsgTime
:= 0;
1833 clearNetClientTransfers(NetClients
[ID
]); // just in case
1835 enet_peer_timeout(NetEvent
.peer
, ENET_PEER_TIMEOUT_LIMIT
* 2, ENET_PEER_TIMEOUT_MINIMUM
* 2, ENET_PEER_TIMEOUT_MAXIMUM
* 2);
1837 Inc(NetClientCount
);
1838 g_Console_Add(_lc
[I_NET_MSG
] + Format(_lc
[I_NET_MSG_HOST_ADD
], [ID
]));
1841 ENET_EVENT_TYPE_RECEIVE
:
1843 //e_LogWritefln('RECEIVE: chan=%u', [NetEvent.channelID]);
1844 if (NetEvent
.channelID
= NET_CHAN_DOWNLOAD_EX
) then
1846 ProcessDownloadExPacket();
1850 ID
:= Byte(NetEvent
.peer
^.data
^);
1851 if ID
> High(NetClients
) then Exit
;
1852 TC
:= @NetClients
[ID
];
1854 if (NetPacketTimeout
> 0) then
1855 TC
^.MsgTime
:= gTime
+ NetPacketTimeout
;
1857 if NetDump
then g_Net_DumpRecvBuffer(NetEvent
.packet
^.data
, NetEvent
.packet
^.dataLength
);
1858 g_Net_Host_HandlePacket(TC
, NetEvent
.packet
, g_Net_HostMsgHandler
);
1862 ENET_EVENT_TYPE_DISCONNECT
:
1864 ID
:= Byte(NetEvent
.peer
^.data
^);
1865 if ID
> High(NetClients
) then Exit
;
1866 g_Net_Host_Disconnect_Client(ID
);
1873 //**************************************************************************
1877 //**************************************************************************
1879 procedure g_Net_Disconnect(Forced
: Boolean = False);
1881 if NetMode
<> NET_CLIENT
then Exit
;
1882 if (NetHost
= nil) or (NetPeer
= nil) then Exit
;
1886 enet_peer_disconnect(NetPeer
, NET_DISC_NONE
);
1888 while (enet_host_service(NetHost
, @NetEvent
, 1500) > 0) do
1890 if (NetEvent
.kind
= ENET_EVENT_TYPE_DISCONNECT
) then
1896 if (NetEvent
.kind
= ENET_EVENT_TYPE_RECEIVE
) then
1897 enet_packet_destroy(NetEvent
.packet
);
1900 if NetPeer
<> nil then
1902 enet_peer_reset(NetPeer
);
1908 e_WriteLog('NET: Kicked from server: ' + IntToStr(NetEvent
.data
), TMsgType
.Notify
);
1909 if (NetEvent
.data
<= NET_DISC_MAX
) then
1910 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_KICK
] +
1911 _lc
[TStrings_Locale(Cardinal(I_NET_DISC_NONE
) + NetEvent
.data
)], True);
1914 if NetHost
<> nil then
1916 enet_host_destroy(NetHost
);
1919 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_CLIENT_DISC
]);
1922 e_WriteLog('NET: Disconnected', TMsgType
.Notify
);
1925 procedure g_Net_Client_Send(Reliable
: Boolean; Chan
: Byte = NET_CHAN_GAME
);
1932 T
:= NET_UNRELIABLE
;
1935 NetBuf
[T
].Write(Integer(NetOut
.CurSize
));
1936 NetBuf
[T
].Write(NetOut
);
1938 if NetDump
then g_Net_DumpSendBuffer();
1940 g_Net_Flush(); // FIXME: for now, send immediately
1943 procedure g_Net_Client_Update();
1945 while (NetHost
<> nil) and (enet_host_service(NetHost
, @NetEvent
, 0) > 0) do
1947 case NetEvent
.kind
of
1948 ENET_EVENT_TYPE_RECEIVE
:
1950 if (NetEvent
.channelID
= NET_CHAN_DOWNLOAD_EX
) then continue
; // ignore all download packets, they're processed by separate code
1951 if NetDump
then g_Net_DumpRecvBuffer(NetEvent
.packet
^.data
, NetEvent
.packet
^.dataLength
);
1952 g_Net_Client_HandlePacket(NetEvent
.packet
, g_Net_ClientMsgHandler
);
1955 ENET_EVENT_TYPE_DISCONNECT
:
1957 g_Net_Disconnect(True);
1964 procedure g_Net_Client_UpdateWhileLoading();
1966 while (enet_host_service(NetHost
, @NetEvent
, 0) > 0) do
1968 case NetEvent
.kind
of
1969 ENET_EVENT_TYPE_RECEIVE
:
1971 if (NetEvent
.channelID
= NET_CHAN_DOWNLOAD_EX
) then continue
; // ignore all download packets, they're processed by separate code
1972 if NetDump
then g_Net_DumpRecvBuffer(NetEvent
.packet
^.data
, NetEvent
.packet
^.dataLength
);
1973 g_Net_Client_HandlePacket(NetEvent
.packet
, g_Net_ClientLightMsgHandler
);
1976 ENET_EVENT_TYPE_DISCONNECT
:
1978 g_Net_Disconnect(True);
1986 function g_Net_Connect(IP
: string; Port
: enet_uint16
): Boolean;
1989 TimeoutTime
, T
: Int64;
1991 if NetMode
<> NET_NONE
then
1993 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_ERR_INGAME
], True);
2000 g_Console_Add(_lc
[I_NET_MSG
] + Format(_lc
[I_NET_MSG_CLIENT_CONN
],
2002 if not NetInitDone
then
2004 if (not g_Net_Init()) then
2006 g_Console_Add(_lc
[I_NET_MSG_FERROR
] + _lc
[I_NET_ERR_ENET
], True);
2011 NetInitDone
:= True;
2014 NetHost
:= enet_host_create(nil, 1, NET_CHANS
, 0, 0);
2016 if (NetHost
= nil) then
2018 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CLIENT
], True);
2024 enet_address_set_host(@NetAddr
, PChar(Addr(IP
[1])));
2025 NetAddr
.port
:= Port
;
2027 NetPeer
:= enet_host_connect(NetHost
, @NetAddr
, NET_CHANS
, NET_PROTOCOL_VER
);
2029 if (NetPeer
= nil) then
2031 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CLIENT
], True);
2032 enet_host_destroy(NetHost
);
2038 // предупредить что ждем слишком долго через N секунд
2039 TimeoutTime
:= sys_GetTicks() + NET_CONNECT_TIMEOUT
;
2044 while (enet_host_service(NetHost
, @NetEvent
, 0) > 0) do
2046 if (NetEvent
.kind
= ENET_EVENT_TYPE_CONNECT
) then
2048 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_CLIENT_DONE
]);
2049 NetMode
:= NET_CLIENT
;
2051 enet_peer_timeout(NetPeer
, ENET_PEER_TIMEOUT_LIMIT
* 2, ENET_PEER_TIMEOUT_MINIMUM
* 2, ENET_PEER_TIMEOUT_MAXIMUM
* 2);
2053 NetClientPort
:= Port
;
2060 T
:= sys_GetTicks();
2061 if T
> TimeoutTime
then
2063 TimeoutTime
:= T
+ NET_CONNECT_TIMEOUT
* 100; // одного предупреждения хватит
2064 g_Console_Add(_lc
[I_NET_MSG_TIMEOUT_WARN
], True);
2065 g_Console_Add(Format(_lc
[I_NET_MSG_PORTS
], [Integer(Port
), Integer(NET_PING_PORT
)]), True);
2068 ProcessLoading(true);
2070 if e_KeyPressed(IK_SPACE
) or e_KeyPressed(IK_ESCAPE
) or e_KeyPressed(VK_ESCAPE
) or
2071 e_KeyPressed(JOY0_JUMP
) or e_KeyPressed(JOY1_JUMP
) or e_KeyPressed(JOY2_JUMP
) or e_KeyPressed(JOY3_JUMP
) then
2075 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_TIMEOUT
], True);
2076 g_Console_Add(Format(_lc
[I_NET_MSG_PORTS
], [Integer(Port
), Integer(NET_PING_PORT
)]), True);
2077 if NetPeer
<> nil then enet_peer_reset(NetPeer
);
2078 if NetHost
<> nil then
2080 enet_host_destroy(NetHost
);
2087 function IpToStr(IP
: LongWord): string;
2092 Result
:= IntToStr(PByte(Ptr
+ 0)^) + '.';
2093 Result
:= Result
+ IntToStr(PByte(Ptr
+ 1)^) + '.';
2094 Result
:= Result
+ IntToStr(PByte(Ptr
+ 2)^) + '.';
2095 Result
:= Result
+ IntToStr(PByte(Ptr
+ 3)^);
2098 function StrToIp(IPstr
: string; var IP
: LongWord): Boolean;
2102 Result
:= enet_address_set_host(@EAddr
, PChar(@IPstr
[1])) = 0;
2106 function g_Net_Client_ByName(Name
: string): pTNetClient
;
2112 for a
:= Low(NetClients
) to High(NetClients
) do
2113 if (NetClients
[a
].Used
) and (NetClients
[a
].State
= NET_STATE_GAME
) then
2115 pl
:= g_Player_Get(NetClients
[a
].Player
);
2116 if pl
= nil then continue
;
2117 if Copy(LowerCase(pl
.Name
), 1, Length(Name
)) <> LowerCase(Name
) then continue
;
2118 if NetClients
[a
].Peer
<> nil then
2120 Result
:= @NetClients
[a
];
2126 function g_Net_Client_ByPlayer(PID
: Word): pTNetClient
;
2131 for a
:= Low(NetClients
) to High(NetClients
) do
2132 if (NetClients
[a
].Used
) and (NetClients
[a
].State
= NET_STATE_GAME
) then
2133 if NetClients
[a
].Player
= PID
then
2135 Result
:= @NetClients
[a
];
2140 function g_Net_ClientName_ByID(ID
: Integer): string;
2146 if ID
= NET_EVERYONE
then
2148 for a
:= Low(NetClients
) to High(NetClients
) do
2149 if (NetClients
[a
].ID
= ID
) and (NetClients
[a
].Used
) and (NetClients
[a
].State
= NET_STATE_GAME
) then
2151 pl
:= g_Player_Get(NetClients
[a
].Player
);
2152 if pl
= nil then Exit
;
2157 procedure g_Net_SendData(Data
: AByte
; peer
: pENetPeer
; Reliable
: Boolean; Chan
: Byte = NET_CHAN_DOWNLOAD
);
2161 dataLength
: Cardinal;
2163 dataLength
:= Length(Data
);
2166 F
:= LongWord(ENET_PACKET_FLAG_RELIABLE
)
2170 if (peer
<> nil) then
2172 P
:= enet_packet_create(@Data
[0], dataLength
, F
);
2173 if not Assigned(P
) then Exit
;
2174 enet_peer_send(peer
, Chan
, P
);
2178 P
:= enet_packet_create(@Data
[0], dataLength
, F
);
2179 if not Assigned(P
) then Exit
;
2180 enet_host_broadcast(NetHost
, Chan
, P
);
2183 enet_host_flush(NetHost
);
2186 function g_Net_IsHostBanned(IP
: LongWord; Perm
: Boolean = False): Boolean;
2191 if NetBannedHosts
= nil then
2193 for I
:= 0 to High(NetBannedHosts
) do
2194 if (NetBannedHosts
[I
].IP
= IP
) and ((not Perm
) or (NetBannedHosts
[I
].Perm
)) then
2201 procedure g_Net_BanHost(IP
: LongWord; Perm
: Boolean = True); overload
;
2207 if g_Net_IsHostBanned(IP
, Perm
) then
2211 for I
:= Low(NetBannedHosts
) to High(NetBannedHosts
) do
2212 if NetBannedHosts
[I
].IP
= 0 then
2220 SetLength(NetBannedHosts
, Length(NetBannedHosts
) + 1);
2221 P
:= High(NetBannedHosts
);
2224 NetBannedHosts
[P
].IP
:= IP
;
2225 NetBannedHosts
[P
].Perm
:= Perm
;
2228 procedure g_Net_BanHost(IP
: string; Perm
: Boolean = True); overload
;
2233 b
:= StrToIp(IP
, a
);
2235 g_Net_BanHost(a
, Perm
);
2238 procedure g_Net_UnbanNonPermHosts();
2242 if NetBannedHosts
= nil then
2244 for I
:= Low(NetBannedHosts
) to High(NetBannedHosts
) do
2245 if (NetBannedHosts
[I
].IP
> 0) and not NetBannedHosts
[I
].Perm
then
2247 NetBannedHosts
[I
].IP
:= 0;
2248 NetBannedHosts
[I
].Perm
:= True;
2252 function g_Net_UnbanHost(IP
: string): Boolean; overload
;
2256 Result
:= StrToIp(IP
, a
);
2258 Result
:= g_Net_UnbanHost(a
);
2261 function g_Net_UnbanHost(IP
: LongWord): Boolean; overload
;
2268 if NetBannedHosts
= nil then
2270 for I
:= 0 to High(NetBannedHosts
) do
2271 if NetBannedHosts
[I
].IP
= IP
then
2273 NetBannedHosts
[I
].IP
:= 0;
2274 NetBannedHosts
[I
].Perm
:= True;
2276 // no break here to clear all bans of this host, perm and non-perm
2280 procedure g_Net_SaveBanList();
2286 path
:= e_GetWriteableDir(DataDirs
);
2289 path
:= e_CatPath(path
, BANLIST_FILENAME
);
2292 if NetBannedHosts
<> nil then
2293 for I
:= 0 to High(NetBannedHosts
) do
2294 if NetBannedHosts
[I
].Perm
and (NetBannedHosts
[I
].IP
> 0) then
2295 Writeln(F
, IpToStr(NetBannedHosts
[I
].IP
));
2300 procedure g_Net_Penalize(C
: pTNetClient
; Reason
: string);
2304 e_LogWritefln('NET: client #%u (cid #%u) triggered a penalty (%d/%d): %s',
2305 [C
^.ID
, C
^.Player
, C
^.Crimes
+ 1, NetAutoBanLimit
, Reason
]);
2307 if (NetAutoBanLimit
<= 0) then Exit
;
2309 if (C
^.Crimes
>= NetAutoBanLimit
) then
2311 // we have tried asking nicely before, now it is time to die
2312 e_LogWritefln('NET: client #%u (cid #%u) force kicked',
2313 [C
^.ID
, C
^.Player
]);
2314 g_Net_Host_Disconnect_Client(C
^.ID
, True);
2320 if (NetAutoBanWarn
) then
2321 MH_SEND_Chat('You have been warned by the server: ' + Reason
, NET_CHAT_SYSTEM
, C
^.ID
);
2323 if (C
^.Crimes
>= NetAutoBanLimit
) then
2325 s
:= '#' + IntToStr(C
^.ID
); // can't be arsed
2326 g_Net_BanHost(C
^.Peer
^.address
.host
, NetAutoBanPerm
);
2327 enet_peer_disconnect(C
^.Peer
, NET_DISC_BAN
);
2328 g_Console_Add(Format(_lc
[I_PLAYER_BAN
], [s
]));
2329 MH_SEND_GameEvent(NET_EV_PLAYER_BAN
, 0, s
);
2330 g_Net_Slist_ServerPlayerLeaves();
2334 procedure g_Net_DumpStart();
2336 if NetMode
= NET_SERVER
then
2337 NetDumpFile
:= e_CreateResource(LogDirs
, NETDUMP_FILENAME
+ '_server')
2339 NetDumpFile
:= e_CreateResource(LogDirs
, NETDUMP_FILENAME
+ '_client');
2342 procedure g_Net_DumpSendBuffer();
2344 writeInt(NetDumpFile
, gTime
);
2345 writeInt(NetDumpFile
, LongWord(NetOut
.CurSize
));
2346 writeInt(NetDumpFile
, Byte(1));
2347 NetDumpFile
.WriteBuffer(NetOut
.Data
^, NetOut
.CurSize
);
2350 procedure g_Net_DumpRecvBuffer(Buf
: penet_uint8
; Len
: LongWord);
2352 if (Buf
= nil) or (Len
= 0) then Exit
;
2353 writeInt(NetDumpFile
, gTime
);
2354 writeInt(NetDumpFile
, Len
);
2355 writeInt(NetDumpFile
, Byte(0));
2356 NetDumpFile
.WriteBuffer(Buf
^, Len
);
2359 procedure g_Net_DumpEnd();
2365 function g_Net_ForwardPorts(ForwardPongPort
: Boolean = True): Boolean;
2366 {$IFDEF USE_MINIUPNPC}
2371 LanAddr
: array [0..255] of Char;
2372 StrPort
: AnsiString;
2377 if NetHost
= nil then
2380 if NetPortForwarded
= NetHost
.address
.port
then
2386 NetPongForwarded
:= False;
2387 NetPortForwarded
:= 0;
2389 DevList
:= upnpDiscover(1000, nil, nil, 0, 0, 2, Addr(Err
));
2390 if DevList
= nil then
2392 conwritefln('port forwarding failed: upnpDiscover() failed: %d', [Err
]);
2396 I
:= UPNP_GetValidIGD(DevList
, @Urls
, @Data
, Addr(LanAddr
[0]), 256);
2400 conwriteln('port forwarding failed: could not find an IGD device on this LAN');
2401 FreeUPNPDevList(DevList
);
2402 FreeUPNPUrls(@Urls
);
2406 StrPort
:= IntToStr(NetHost
.address
.port
);
2407 I
:= UPNP_AddPortMapping(
2408 Urls
.controlURL
, Addr(data
.first
.servicetype
[1]),
2409 PChar(StrPort
), PChar(StrPort
), Addr(LanAddr
[0]), PChar('D2DF'),
2410 PChar('UDP'), nil, PChar('0')
2415 conwritefln('forwarding port %d failed: error %d', [NetHost
.address
.port
, I
]);
2416 FreeUPNPDevList(DevList
);
2417 FreeUPNPUrls(@Urls
);
2421 if ForwardPongPort
then
2423 StrPort
:= IntToStr(NET_PING_PORT
);
2424 I
:= UPNP_AddPortMapping(
2425 Urls
.controlURL
, Addr(data
.first
.servicetype
[1]),
2426 PChar(StrPort
), PChar(StrPort
), Addr(LanAddr
[0]), PChar('D2DF'),
2427 PChar('UDP'), nil, PChar('0')
2432 conwritefln('forwarding port %d failed: error %d', [NET_PING_PORT
, I
]);
2433 NetPongForwarded
:= False;
2437 conwritefln('forwarded port %d successfully', [NET_PING_PORT
]);
2438 NetPongForwarded
:= True;
2442 conwritefln('forwarded port %d successfully', [NetHost
.address
.port
]);
2443 NetIGDControl
:= AnsiString(Urls
.controlURL
);
2444 NetIGDService
:= data
.first
.servicetype
;
2445 NetPortForwarded
:= NetHost
.address
.port
;
2447 FreeUPNPDevList(DevList
);
2448 FreeUPNPUrls(@Urls
);
2457 procedure g_Net_UnforwardPorts();
2458 {$IFDEF USE_MINIUPNPC}
2461 StrPort
: AnsiString;
2463 if NetPortForwarded
= 0 then Exit
;
2465 conwriteln('unforwarding ports...');
2467 StrPort
:= IntToStr(NetPortForwarded
);
2468 I
:= UPNP_DeletePortMapping(
2469 PChar(NetIGDControl
), Addr(NetIGDService
[1]),
2470 PChar(StrPort
), PChar('UDP'), nil
2472 conwritefln(' port %d: %d', [NetPortForwarded
, I
]);
2474 if NetPongForwarded
then
2476 NetPongForwarded
:= False;
2477 StrPort
:= IntToStr(NET_PING_PORT
);
2478 I
:= UPNP_DeletePortMapping(
2479 PChar(NetIGDControl
), Addr(NetIGDService
[1]),
2480 PChar(StrPort
), PChar('UDP'), nil
2482 conwritefln(' port %d: %d', [NET_PING_PORT
, I
]);
2485 NetPortForwarded
:= 0;
2492 procedure NetServerCVars(P
: SSArray
);
2497 cmd
:= LowerCase(P
[0]);
2501 if (Length(P
) > 1) and (Length(P
[1]) > 0) then
2503 NetServerName
:= P
[1];
2504 if Length(NetServerName
) > 64 then
2505 SetLength(NetServerName
, 64);
2506 g_Net_Slist_ServerRenamed();
2508 g_Console_Add(cmd
+ ' "' + NetServerName
+ '"');
2512 if (Length(P
) > 1) and (Length(P
[1]) > 0) then
2514 NetPassword
:= P
[1];
2515 if Length(NetPassword
) > 24 then
2516 SetLength(NetPassword
, 24);
2517 g_Net_Slist_ServerRenamed();
2519 g_Console_Add(cmd
+ ' "' + AnsiLowerCase(NetPassword
) + '"');
2523 if (Length(P
) > 1) then
2525 NetMaxClients
:= nclamp(StrToIntDef(P
[1], NetMaxClients
), 1, NET_MAXCLIENTS
);
2526 if g_Game_IsServer
and g_Game_IsNet
then
2529 for a
:= 0 to High(NetClients
) do
2531 if NetClients
[a
].Used
then
2534 if b
> NetMaxClients
then
2536 s
:= g_Player_Get(NetClients
[a
].Player
).Name
;
2537 enet_peer_disconnect(NetClients
[a
].Peer
, NET_DISC_FULL
);
2538 g_Console_Add(Format(_lc
[I_PLAYER_KICK
], [s
]));
2539 MH_SEND_GameEvent(NET_EV_PLAYER_KICK
, 0, s
);
2543 g_Net_Slist_ServerRenamed();
2546 g_Console_Add(cmd
+ ' ' + IntToStr(NetMaxClients
));
2550 if (Length(P
) > 1) then
2552 NetUseMaster
:= StrToIntDef(P
[1], Byte(NetUseMaster
)) <> 0;
2553 if NetUseMaster
then g_Net_Slist_Public() else g_Net_Slist_Private();
2555 g_Console_Add(cmd
+ ' ' + IntToStr(Byte(NetUseMaster
)));
2559 if (Length(P
) > 1) then
2561 if not g_Game_IsNet
then
2562 NetPort
:= nclamp(StrToIntDef(P
[1], NetPort
), 0, $FFFF)
2564 g_Console_Add(_lc
[I_MSG_NOT_NETGAME
]);
2566 g_Console_Add(cmd
+ ' ' + IntToStr(Ord(NetUseMaster
)));
2572 conRegVar('cl_downloadtimeout', @g_Net_DownloadTimeout
, 0.0, 1000000.0, '', 'timeout in seconds, 0 to disable it');
2573 conRegVar('cl_predictself', @NetPredictSelf
, '', 'predict local player');
2574 conRegVar('cl_forceplayerupdate', @NetForcePlayerUpdate
, '', 'update net players on NET_MSG_PLRPOS');
2575 conRegVar('cl_interp', @NetInterpLevel
, '', 'net player interpolation steps');
2576 conRegVar('cl_last_ip', @NetClientIP
, '', 'address of the last you have connected to');
2577 conRegVar('cl_last_port', @NetClientPort
, '', 'port of the last server you have connected to');
2578 conRegVar('cl_deafen', @NetDeafLevel
, '', 'filter server messages (0-3)');
2580 conRegVar('sv_forwardports', @NetForwardPorts
, '', 'forward server port using miniupnpc (requires server restart)');
2581 conRegVar('sv_rcon', @NetAllowRCON
, '', 'enable remote console');
2582 conRegVar('sv_rcon_password', @NetRCONPassword
, '', 'remote console password');
2583 conRegVar('sv_update_interval', @NetUpdateRate
, '', 'unreliable update interval');
2584 conRegVar('sv_reliable_interval', @NetRelupdRate
, '', 'reliable update interval');
2585 conRegVar('sv_master_interval', @NetMasterRate
, '', 'master server update interval');
2587 conRegVar('sv_autoban_threshold', @NetAutoBanLimit
, '', 'max crimes before autoban (0 = no autoban)');
2588 conRegVar('sv_autoban_permanent', @NetAutoBanPerm
, '', 'whether autobans are permanent');
2589 conRegVar('sv_autoban_warn', @NetAutoBanWarn
, '', 'send warnings to the client when he triggers penalties');
2590 conRegVar('sv_autoban_packet_timeout', @NetAutoBanForTimeout
, '', 'autoban for packet timeouts');
2592 conRegVar('sv_auth_timeout', @NetAuthTimeout
, '', 'number of msec in which connecting clients must complete auth (0 = unlimited)');
2593 conRegVar('sv_packet_timeout', @NetPacketTimeout
, '', 'number of msec the client must idle to be kicked (0 = unlimited)');
2595 conRegVar('net_master_list', @NetMasterList
, '', 'list of master servers');
2597 SetLength(NetClients
, 0);
2598 g_Net_DownloadTimeout
:= 60;
2599 NetIn
.Alloc(NET_BUFSIZE
);
2600 NetOut
.Alloc(NET_BUFSIZE
);
2601 NetBuf
[NET_UNRELIABLE
].Alloc(NET_BUFSIZE
*2);
2602 NetBuf
[NET_RELIABLE
].Alloc(NET_BUFSIZE
*2);
2603 trans_omsg
.Alloc(NET_BUFSIZE
);
2607 NetBuf
[NET_UNRELIABLE
].Free();
2608 NetBuf
[NET_RELIABLE
].Free();