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
106 FullUpdateSent
: Boolean;
112 Transfer
: TNetFileTransfer
; // only one transfer may be active
113 NetOut
: array [0..1] of TMsg
;
119 pTNetClient
= ^TNetClient
;
121 AByte
= array of Byte;
124 NetInitDone
: Boolean = False;
125 NetMode
: Byte = NET_NONE
;
126 NetDump
: Boolean = False;
128 NetServerName
: string = 'Unnamed Server';
129 NetPassword
: string = '';
130 NetPort
: Word = 25666;
132 NetAllowRCON
: Boolean = False;
133 NetRCONPassword
: string = '';
135 NetTimeToUpdate
: Cardinal = 0;
136 NetTimeToReliable
: Cardinal = 0;
137 NetTimeToMaster
: Cardinal = 0;
139 NetHost
: pENetHost
= nil;
140 NetPeer
: pENetPeer
= nil;
142 NetAddr
: ENetAddress
;
144 NetPongAddr
: ENetAddress
;
145 NetPongSock
: ENetSocket
= ENET_SOCKET_NULL
;
147 NetUseMaster
: Boolean = True;
148 NetMasterList
: string = 'mpms.doom2d.org:25665, deadsoftware.ru:25665';
150 NetClientIP
: string = '127.0.0.1';
151 NetClientPort
: Word = 25666;
154 NetBuf
: array [0..1] of TMsg
;
156 NetClients
: array of TNetClient
;
157 NetClientCount
: Byte = 0;
158 NetMaxClients
: Byte = 255;
159 NetBannedHosts
: array of TBanRecord
;
161 NetAutoBanLimit
: Integer = 5;
162 NetAutoBanPerm
: Boolean = True;
163 NetAutoBanWarn
: Boolean = False;
164 NetAutoBanForTimeout
: Boolean = False;
166 NetAuthTimeout
: Integer = 30 * 1000;
167 NetPacketTimeout
: Integer = 60 * 1000;
169 NetState
: Integer = NET_STATE_NONE
;
171 NetMyID
: Integer = -1;
172 NetPlrUID1
: Integer = -1;
173 NetPlrUID2
: Integer = -1;
175 NetInterpLevel
: Integer = 1;
176 NetUpdateRate
: Cardinal = 0; // as soon as possible
177 NetRelupdRate
: Cardinal = 18; // around two times a second
178 NetMasterRate
: Cardinal = 60000;
180 NetForcePlayerUpdate
: Boolean = False;
181 NetPredictSelf
: Boolean = True;
182 NetForwardPorts
: Boolean = False;
184 NetGotEverything
: Boolean = False;
185 NetGotKeys
: Boolean = False;
187 NetDeafLevel
: Integer = 0;
189 {$IFDEF USE_MINIUPNPC}
190 NetPortForwarded
: Word = 0;
191 NetPongForwarded
: Boolean = False;
192 NetIGDControl
: AnsiString;
193 NetIGDService
: TURLStr
;
196 NetPortThread
: TThreadID
= NilThreadId
;
198 NetDumpFile
: TStream
;
200 g_Res_received_map_start
: Integer = 0; // set if we received "map change" event
203 function g_Net_Init(): Boolean;
204 procedure g_Net_Cleanup();
205 procedure g_Net_Free();
206 procedure g_Net_Flush();
208 function g_Net_Host(IPAddr
: LongWord; Port
: enet_uint16
; MaxClients
: Cardinal = 16): Boolean;
209 procedure g_Net_Host_Die();
210 procedure g_Net_Host_Send(ID
: Integer; Reliable
: Boolean; Chan
: Byte = NET_CHAN_GAME
);
211 procedure g_Net_Host_Update();
212 procedure g_Net_Host_Kick(ID
: Integer; Reason
: enet_uint32
);
214 function g_Net_Connect(IP
: string; Port
: enet_uint16
): Boolean;
215 procedure g_Net_Disconnect(Forced
: Boolean = False);
216 procedure g_Net_Client_Send(Reliable
: Boolean; Chan
: Byte = NET_CHAN_GAME
);
217 procedure g_Net_Client_Update();
219 function g_Net_Client_ByName(Name
: string): pTNetClient
;
220 function g_Net_Client_ByPlayer(PID
: Word): pTNetClient
;
221 function g_Net_ClientName_ByID(ID
: Integer): string;
223 procedure g_Net_SendData(Data
: AByte
; peer
: pENetPeer
; Reliable
: Boolean; Chan
: Byte = NET_CHAN_DOWNLOAD
);
224 //function g_Net_Wait_Event(msgId: Word): TMemoryStream;
225 //function g_Net_Wait_FileInfo (var tf: TNetFileTransfer; asMap: Boolean; out resList: TStringList): Integer;
227 function IpToStr(IP
: LongWord): string;
228 function StrToIp(IPstr
: string; var IP
: LongWord): Boolean;
230 function g_Net_IsHostBanned(IP
: LongWord; Perm
: Boolean = False): Boolean;
231 procedure g_Net_BanHost(IP
: LongWord; Perm
: Boolean = True); overload
;
232 procedure g_Net_BanHost(IP
: string; Perm
: Boolean = True); overload
;
233 function g_Net_UnbanHost(IP
: string): Boolean; overload
;
234 function g_Net_UnbanHost(IP
: LongWord): Boolean; overload
;
235 procedure g_Net_UnbanNonPermHosts();
236 procedure g_Net_SaveBanList();
238 procedure g_Net_Penalize(C
: pTNetClient
; Reason
: string);
240 procedure g_Net_DumpStart();
241 procedure g_Net_DumpSendBuffer();
242 procedure g_Net_DumpRecvBuffer(Buf
: penet_uint8
; Len
: LongWord);
243 procedure g_Net_DumpEnd();
245 function g_Net_ForwardPorts(ForwardPongPort
: Boolean = True): Boolean;
246 procedure g_Net_UnforwardPorts();
248 function g_Net_UserRequestExit
: Boolean;
250 function g_Net_Wait_MapInfo (var tf
: TNetFileTransfer
; var resList
: TNetMapResourceInfoArray
): Integer;
251 function g_Net_RequestResFileInfo (resIndex
: LongInt; out tf
: TNetFileTransfer
): Integer;
252 function g_Net_AbortResTransfer (var tf
: TNetFileTransfer
): Boolean;
253 function g_Net_ReceiveResourceFile (resIndex
: LongInt; var tf
: TNetFileTransfer
; strm
: TStream
): Integer;
255 function g_Net_IsNetworkAvailable (): Boolean;
256 procedure g_Net_InitLowLevel ();
257 procedure g_Net_DeinitLowLevel ();
259 procedure NetServerCVars(P
: SSArray
);
264 // *enet_host_service()*
265 // fuck! https://www.mail-archive.com/enet-discuss@cubik.org/msg00852.html
266 // tl;dr: on shitdows, we can get -1 sometimes, and it is *NOT* a failure.
267 // thank you, enet. let's ignore failures altogether then.
272 g_nethandler
, g_netmsg
, g_netmaster
, g_player
, g_window
, g_console
,
273 g_main
, g_game
, g_language
, g_weapons
, ctypes
, g_system
, g_map
;
276 FILE_CHUNK_SIZE
= 8192;
279 enet_init_success
: Boolean = false;
280 g_Net_DownloadTimeout
: Single;
284 function g_Net_IsNetworkAvailable (): Boolean;
286 result
:= enet_init_success
;
289 procedure g_Net_InitLowLevel ();
292 v
:= enet_linked_version();
293 e_LogWritefln('ENet Version: %s.%s.%s', [ENET_VERSION_GET_MAJOR(v
), ENET_VERSION_GET_MINOR(v
), ENET_VERSION_GET_PATCH(v
)]);
294 if enet_init_success
then raise Exception
.Create('wuta?!');
295 enet_init_success
:= (enet_initialize() = 0);
298 procedure g_Net_DeinitLowLevel ();
300 if enet_init_success
then
303 enet_init_success
:= false;
308 //**************************************************************************
312 //**************************************************************************
314 procedure clearNetClientTransfers (var nc
: TNetClient
);
316 nc
.Transfer
.stream
.Free
;
317 nc
.Transfer
.diskName
:= ''; // just in case
318 if (nc
.Transfer
.diskBuffer
<> nil) then FreeMem(nc
.Transfer
.diskBuffer
);
319 nc
.Transfer
.stream
:= nil;
320 nc
.Transfer
.diskBuffer
:= nil;
324 procedure clearNetClient (var nc
: TNetClient
);
326 clearNetClientTransfers(nc
);
330 procedure clearNetClients (clearArray
: Boolean);
334 for f
:= Low(NetClients
) to High(NetClients
) do clearNetClient(NetClients
[f
]);
335 if (clearArray
) then SetLength(NetClients
, 0);
339 function g_Net_UserRequestExit (): Boolean;
341 Result
:= {e_KeyPressed(IK_SPACE) or}
342 e_KeyPressed(IK_ESCAPE
) or
343 e_KeyPressed(VK_ESCAPE
) or
344 e_KeyPressed(JOY0_JUMP
) or
345 e_KeyPressed(JOY1_JUMP
) or
346 e_KeyPressed(JOY2_JUMP
) or
347 e_KeyPressed(JOY3_JUMP
)
350 //**************************************************************************
352 // file transfer declaraions and host packet processor
354 //**************************************************************************
357 // server packet type
358 NTF_SERVER_DONE
= 10; // done with this file
359 NTF_SERVER_FILE_INFO
= 11; // sent after client request
360 NTF_SERVER_CHUNK
= 12; // next chunk; chunk number follows
361 NTF_SERVER_ABORT
= 13; // server abort
362 NTF_SERVER_MAP_INFO
= 14;
364 // client packet type
365 NTF_CLIENT_MAP_REQUEST
= 100; // map file request; also, returns list of additional wads to download
366 NTF_CLIENT_FILE_REQUEST
= 101; // resource file request (by index)
367 NTF_CLIENT_ABORT
= 102; // do not send requested file, or abort current transfer
368 NTF_CLIENT_START
= 103; // start transfer; client may resume download by sending non-zero starting chunk
369 NTF_CLIENT_ACK
= 104; // chunk ack; chunk number follows
372 // disconnect client due to some file transfer error
373 procedure killClientByFT (var nc
: TNetClient
);
375 e_LogWritefln('disconnected client #%d due to file transfer error', [nc
.ID
], TMsgType
.Warning
);
376 g_Net_Host_Kick(nc
.ID
, NET_DISC_FILE_TIMEOUT
);
377 clearNetClientTransfers(nc
);
378 g_Net_Slist_ServerPlayerLeaves();
382 // send file transfer message from server to client
383 function ftransSendServerMsg (var nc
: TNetClient
; var m
: TMsg
): Boolean;
388 if (m
.CurSize
< 1) then exit
;
389 pkt
:= enet_packet_create(m
.Data
, m
.CurSize
, ENET_PACKET_FLAG_RELIABLE
);
390 if not Assigned(pkt
) then begin killClientByFT(nc
); exit
; end;
391 if (enet_peer_send(nc
.Peer
, NET_CHAN_DOWNLOAD_EX
, pkt
) <> 0) then begin killClientByFT(nc
); exit
; end;
396 // send file transfer message from client to server
397 function ftransSendClientMsg (var m
: TMsg
): Boolean;
402 if (m
.CurSize
< 1) then exit
;
403 pkt
:= enet_packet_create(m
.Data
, m
.CurSize
, ENET_PACKET_FLAG_RELIABLE
);
404 if not Assigned(pkt
) then exit
;
405 if (enet_peer_send(NetPeer
, NET_CHAN_DOWNLOAD_EX
, pkt
) <> 0) then exit
;
411 procedure ProcessChunkSend (var nc
: TNetClient
);
413 tf
: ^TNetFileTransfer
;
419 if (tf
.stream
= nil) then exit
;
421 // arbitrary timeout number
422 if (ct
-tf
.lastAckTime
>= 5000) then
427 // check if we need to send something
428 if (not tf
.inProgress
) then exit
; // waiting for the initial ack
429 // ok, we're sending chunks
430 if (tf
.lastAckChunk
<> tf
.lastSentChunk
) then exit
;
431 Inc(tf
.lastSentChunk
);
432 // do it one chunk at a time; client ack will advance our chunk counter
433 chunks
:= (tf
.size
+tf
.chunkSize
-1) div tf
.chunkSize
;
435 if (tf
.lastSentChunk
> chunks
) then
442 if (tf
.lastSentChunk
= chunks
) then
444 // we're done with this file
445 e_LogWritefln('download: client #%d, DONE sending chunks #%d/#%d', [nc
.ID
, tf
.lastSentChunk
, chunks
]);
446 trans_omsg
.Write(Byte(NTF_SERVER_DONE
));
447 clearNetClientTransfers(nc
);
452 trans_omsg
.Write(Byte(NTF_SERVER_CHUNK
));
453 trans_omsg
.Write(LongInt(tf
.lastSentChunk
));
455 rd
:= tf
.size
-(tf
.lastSentChunk
*tf
.chunkSize
);
456 if (rd
> tf
.chunkSize
) then rd
:= tf
.chunkSize
;
457 trans_omsg
.Write(LongInt(rd
));
458 //e_LogWritefln('download: client #%d, sending chunk #%d/#%d (%d bytes)', [nc.ID, tf.lastSentChunk, chunks, rd]);
459 //FIXME: check for errors here
461 tf
.stream
.Seek(tf
.lastSentChunk
*tf
.chunkSize
, soFromBeginning
);
462 tf
.stream
.ReadBuffer(tf
.diskBuffer
^, rd
);
463 trans_omsg
.WriteData(tf
.diskBuffer
, rd
);
470 ftransSendServerMsg(nc
, trans_omsg
);
474 // server file transfer packet processor
475 // received packet is in `NetEvent`
476 procedure ProcessDownloadExPacket ();
483 tf
: ^TNetFileTransfer
;
493 // find client index by peer
494 for f
:= Low(NetClients
) to High(NetClients
) do
496 if (not NetClients
[f
].Used
) then continue
;
497 if (NetClients
[f
].Peer
= NetEvent
.peer
) then
503 //e_LogWritefln('RECEIVE: dlpacket; client=%d (datalen=%u)', [nid, NetEvent.packet^.dataLength]);
505 if (nid
< 0) then exit
; // wtf?!
506 nc
:= @NetClients
[nid
];
508 if (NetEvent
.packet
^.dataLength
= 0) then
514 // don't time out clients during a file transfer
515 if (NetAuthTimeout
> 0) then
516 nc
^.AuthTime
:= gTime
+ NetAuthTimeout
;
517 if (NetPacketTimeout
> 0) then
518 nc
^.MsgTime
:= gTime
+ NetPacketTimeout
;
520 tf
:= @NetClients
[nid
].Transfer
;
521 tf
.lastAckTime
:= GetTimerMS();
523 cmd
:= Byte(NetEvent
.packet
^.data
^);
524 //e_LogWritefln('RECEIVE: nid=%d; cmd=%u', [nid, cmd]);
526 NTF_CLIENT_FILE_REQUEST
: // file request
528 if (tf
.stream
<> nil) then
533 if (NetEvent
.packet
^.dataLength
< 2) then
538 // new transfer request; build packet
539 if not msg
.Init(NetEvent
.packet
^.data
+1, NetEvent
.packet
^.dataLength
-1, True) then
544 // get resource index
545 ridx
:= msg
.ReadLongInt();
546 if (ridx
< -1) or (ridx
>= length(gExternalResources
)) then
548 e_LogWritefln('Invalid resource index %d', [ridx
], TMsgType
.Warning
);
552 if (ridx
< 0) then fname
:= gGameSettings
.WAD
else fname
:= gExternalResources
[ridx
].diskName
;
553 if (length(fname
) = 0) then
555 e_WriteLog('Invalid filename: '+fname
, TMsgType
.Warning
);
559 tf
.diskName
:= findDiskWad(fname
);
560 if (length(tf
.diskName
) = 0) then
562 e_LogWritefln('NETWORK: file "%s" not found!', [fname
], TMsgType
.Fatal
);
567 //tf.hash := MD5File(tf.diskName);
568 if (ridx
< 0) then tf
.hash
:= gWADHash
else tf
.hash
:= gExternalResources
[ridx
].hash
;
569 // create file stream
570 tf
.diskName
:= findDiskWad(fname
);
572 tf
.stream
:= openDiskFileRO(tf
.diskName
);
576 if (tf
.stream
= nil) then
578 e_WriteLog(Format('NETWORK: file "%s" not found!', [fname
]), TMsgType
.Fatal
);
582 e_LogWritefln('client #%d requested resource #%d (file is `%s` : `%s`)', [nc
.ID
, ridx
, fname
, tf
.diskName
]);
583 tf
.size
:= tf
.stream
.size
;
584 tf
.chunkSize
:= FILE_CHUNK_SIZE
; // arbitrary
585 tf
.lastSentChunk
:= -1;
586 tf
.lastAckChunk
:= -1;
587 tf
.lastAckTime
:= GetTimerMS();
588 tf
.inProgress
:= False; // waiting for the first ACK or for the cancel
589 GetMem(tf
.diskBuffer
, tf
.chunkSize
);
590 // sent file info message
592 trans_omsg
.Write(Byte(NTF_SERVER_FILE_INFO
));
593 trans_omsg
.Write(tf
.hash
);
594 trans_omsg
.Write(tf
.size
);
595 trans_omsg
.Write(tf
.chunkSize
);
596 trans_omsg
.Write(ExtractFileName(fname
));
597 if not ftransSendServerMsg(nc
^, trans_omsg
) then exit
;
599 NTF_CLIENT_ABORT
: // do not send requested file, or abort current transfer
601 e_LogWritefln('client #%d aborted file transfer', [nc
.ID
]);
602 clearNetClientTransfers(nc
^);
604 NTF_CLIENT_START
: // start transfer; client may resume download by sending non-zero starting chunk
606 if not Assigned(tf
.stream
) then
611 if (tf
.lastSentChunk
<> -1) or (tf
.lastAckChunk
<> -1) or (tf
.inProgress
) then
613 // double ack, get lost
617 if (NetEvent
.packet
^.dataLength
< 2) then
623 if not msg
.Init(NetEvent
.packet
^.data
+1, NetEvent
.packet
^.dataLength
-1, True) then
628 chunk
:= msg
.ReadLongInt();
629 if (chunk
< 0) or (chunk
> (tf
.size
+tf
.chunkSize
-1) div tf
.chunkSize
) then
634 e_LogWritefln('client #%d started file transfer from chunk %d', [nc
.ID
, chunk
]);
635 // start sending chunks
636 tf
.inProgress
:= True;
637 tf
.lastSentChunk
:= chunk
-1;
638 tf
.lastAckChunk
:= chunk
-1;
639 ProcessChunkSend(nc
^);
641 NTF_CLIENT_ACK
: // chunk ack; chunk number follows
643 if not Assigned(tf
.stream
) then
648 if (tf
.lastSentChunk
< 0) or (not tf
.inProgress
) then
650 // double ack, get lost
654 if (NetEvent
.packet
^.dataLength
< 2) then
660 if not msg
.Init(NetEvent
.packet
^.data
+1, NetEvent
.packet
^.dataLength
-1, True) then
665 chunk
:= msg
.ReadLongInt();
666 if (chunk
< 0) or (chunk
> (tf
.size
+tf
.chunkSize
-1) div tf
.chunkSize
) then
671 // do it this way, so client may seek, or request retransfers for some reason
672 tf
.lastAckChunk
:= chunk
;
673 tf
.lastSentChunk
:= chunk
;
674 //e_LogWritefln('client #%d acked file transfer chunk %d', [nc.ID, chunk]);
675 ProcessChunkSend(nc
^);
677 NTF_CLIENT_MAP_REQUEST
:
679 e_LogWritefln('client #%d requested map info', [nc
.ID
]);
681 dfn
:= findDiskWad(gGameSettings
.WAD
);
682 if (dfn
= '') then dfn
:= '!wad_not_found!.wad'; //FIXME
683 //md5 := MD5File(dfn);
685 if (not GetDiskFileInfo(dfn
, fi
)) then
687 e_LogWritefln('client #%d requested map info, but i cannot get file info', [nc
.ID
]);
693 st := openDiskFileRO(dfn);
694 if not assigned(st) then exit; //wtf?!
699 trans_omsg
.Write(Byte(NTF_SERVER_MAP_INFO
));
701 trans_omsg
.Write(ExtractFileName(gGameSettings
.WAD
));
703 trans_omsg
.Write(md5
);
705 trans_omsg
.Write(size
);
706 // number of external resources for map
707 trans_omsg
.Write(LongInt(length(gExternalResources
)));
708 // external resource names
709 for f
:= 0 to High(gExternalResources
) do
712 //trans_omsg.Write(ExtractFileName(gExternalResources[f])); // GameDir+'/wads/'+ResList.Strings[i]
714 trans_omsg
.Write('!');
715 trans_omsg
.Write(LongInt(gExternalResources
[f
].size
));
716 trans_omsg
.Write(gExternalResources
[f
].hash
);
717 trans_omsg
.Write(ExtractFileName(gExternalResources
[f
].diskName
));
720 if not ftransSendServerMsg(nc
^, trans_omsg
) then exit
;
731 //**************************************************************************
733 // file transfer crap (both client and server)
735 //**************************************************************************
737 function getNewTimeoutEnd (): Int64;
739 result
:= GetTimerMS();
740 if (g_Net_DownloadTimeout
<= 0) then
742 result
:= result
+1000*60*3; // 3 minutes
746 result
:= result
+trunc(g_Net_DownloadTimeout
*1000);
751 // send map request to server, and wait for "map info" server reply
753 // returns `false` on error or user abort
755 // diskName: map wad file name (without a path)
756 // hash: map wad hash
757 // size: map wad size
758 // chunkSize: set too
759 // resList: list of resource wads
765 // for maps, first `tf.diskName` name will be map wad name, and `tf.hash`/`tf.size` will contain map info
766 function g_Net_Wait_MapInfo (var tf
: TNetFileTransfer
; var resList
: TNetMapResourceInfoArray
): Integer;
772 freePacket
: Boolean = false;
777 ri
: ^TNetMapResourceInfo
;
779 SetLength(resList
, 0);
783 trans_omsg
.Write(Byte(NTF_CLIENT_MAP_REQUEST
));
784 if not ftransSendClientMsg(trans_omsg
) then begin result
:= -1; exit
; end;
786 FillChar(ev
, SizeOf(ev
), 0);
789 ett
:= getNewTimeoutEnd();
791 status
:= enet_host_service(NetHost
, @ev
, 300);
795 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' network error', True);
800 if (status
<= 0) then
806 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' timeout reached', True);
815 ENET_EVENT_TYPE_RECEIVE
:
818 if (ev
.channelID
<> NET_CHAN_DOWNLOAD_EX
) then
820 //e_LogWritefln('g_Net_Wait_MapInfo: skip message from non-transfer channel', []);
822 g_Net_Client_HandlePacket(ev
.packet
, g_Net_ClientLightMsgHandler
);
823 if (g_Res_received_map_start
< 0) then begin result
:= -666; exit
; end;
827 ett
:= getNewTimeoutEnd();
828 if (ev
.packet
.dataLength
< 1) then
830 e_LogWritefln('g_Net_Wait_MapInfo: invalid server packet (no data)', []);
834 Ptr
:= ev
.packet
^.data
;
835 rMsgId
:= Byte(Ptr
^);
836 e_LogWritefln('g_Net_Wait_MapInfo: got message %u from server (dataLength=%u)', [rMsgId
, ev
.packet
^.dataLength
]);
837 if (rMsgId
= NTF_SERVER_FILE_INFO
) then
839 e_LogWritefln('g_Net_Wait_MapInfo: waiting for map info reply, but got file info reply', []);
843 else if (rMsgId
= NTF_SERVER_ABORT
) then
845 e_LogWritefln('g_Net_Wait_MapInfo: server aborted transfer', []);
849 else if (rMsgId
= NTF_SERVER_MAP_INFO
) then
851 e_LogWritefln('g_Net_Wait_MapInfo: creating map info packet...', []);
852 if not msg
.Init(ev
.packet
^.data
+1, ev
.packet
^.dataLength
-1, True) then exit
;
853 e_LogWritefln('g_Net_Wait_MapInfo: parsing map info packet (rd=%d; max=%d)...', [msg
.ReadCount
, msg
.MaxSize
]);
854 SetLength(resList
, 0); // just in case
856 tf
.diskName
:= msg
.ReadString();
857 e_LogWritefln('g_Net_Wait_MapInfo: map wad is `%s`', [tf
.diskName
]);
859 tf
.hash
:= msg
.ReadMD5();
861 tf
.size
:= msg
.ReadLongInt();
862 e_LogWritefln('g_Net_Wait_MapInfo: map wad size is %d', [tf
.size
]);
863 // number of external resources for map
864 rc
:= msg
.ReadLongInt();
865 if (rc
< 0) or (rc
> 1024) then
867 e_LogWritefln('g_Net_Wait_Event: invalid number of map external resources (%d)', [rc
]);
871 e_LogWritefln('g_Net_Wait_MapInfo: map external resource count is %d', [rc
]);
872 SetLength(resList
, rc
);
873 // external resource names
874 for f
:= 0 to rc
-1 do
877 s
:= msg
.ReadString();
878 if (length(s
) = 0) then begin result
:= -1; exit
; end;
882 ri
.size
:= msg
.ReadLongInt();
883 ri
.hash
:= msg
.ReadMD5();
884 ri
.wadName
:= ExtractFileName(msg
.ReadString());
885 if (length(ri
.wadName
) = 0) or (ri
.size
< 0) then begin result
:= -1; exit
; end;
889 // old-style packet, only name
890 ri
.wadName
:= ExtractFileName(s
);
891 if (length(ri
.wadName
) = 0) then begin result
:= -1; exit
; end;
892 ri
.size
:= -1; // unknown
895 e_LogWritefln('g_Net_Wait_MapInfo: got map info', []);
896 Result
:= 0; // success
901 e_LogWritefln('g_Net_Wait_Event: invalid server packet type', []);
907 ENET_EVENT_TYPE_DISCONNECT
:
909 if (ev
.data
<= NET_DISC_MAX
) then
910 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' ' + _lc
[TStrings_Locale(Cardinal(I_NET_DISC_NONE
) + ev
.data
)], True);
916 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' unknown ENet event ' + IntToStr(Ord(ev
.kind
)), True);
921 if (freePacket
) then begin freePacket
:= false; enet_packet_destroy(ev
.packet
); end;
924 ProcessLoading(False);
925 if g_Net_UserRequestExit() then
927 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' user abort', True);
933 if (freePacket
) then enet_packet_destroy(ev
.packet
);
938 // send file request to server, and wait for server reply
940 // returns `false` on error or user abort
942 // diskName (actually, base name)
951 // for maps, first `tf.diskName` name will be map wad name, and `tf.hash`/`tf.size` will contain map info
952 function g_Net_RequestResFileInfo (resIndex
: LongInt; out tf
: TNetFileTransfer
): Integer;
958 freePacket
: Boolean = false;
964 trans_omsg
.Write(Byte(NTF_CLIENT_FILE_REQUEST
));
965 trans_omsg
.Write(resIndex
);
966 if not ftransSendClientMsg(trans_omsg
) then begin result
:= -1; exit
; end;
968 FillChar(ev
, SizeOf(ev
), 0);
971 ett
:= getNewTimeoutEnd();
973 status
:= enet_host_service(NetHost
, @ev
, 300);
977 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' network error', True);
982 if (status
<= 0) then
988 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' timeout reached', True);
997 ENET_EVENT_TYPE_RECEIVE
:
1000 if (ev
.channelID
<> NET_CHAN_DOWNLOAD_EX
) then
1002 //e_LogWriteln('g_Net_Wait_Event: skip message from non-transfer channel');
1003 freePacket
:= false;
1004 g_Net_Client_HandlePacket(ev
.packet
, g_Net_ClientLightMsgHandler
);
1005 if (g_Res_received_map_start
< 0) then begin result
:= -666; exit
; end;
1009 ett
:= getNewTimeoutEnd();
1010 if (ev
.packet
.dataLength
< 1) then
1012 e_LogWriteln('g_Net_Wait_Event: invalid server packet (no data)');
1016 Ptr
:= ev
.packet
^.data
;
1017 rMsgId
:= Byte(Ptr
^);
1018 e_LogWritefln('received transfer packet with id %d (%u bytes)', [rMsgId
, ev
.packet
^.dataLength
]);
1019 if (rMsgId
= NTF_SERVER_FILE_INFO
) then
1021 if not msg
.Init(ev
.packet
^.data
+1, ev
.packet
^.dataLength
-1, True) then exit
;
1022 tf
.hash
:= msg
.ReadMD5();
1023 tf
.size
:= msg
.ReadLongInt();
1024 tf
.chunkSize
:= msg
.ReadLongInt();
1025 tf
.diskName
:= ExtractFileName(msg
.readString());
1026 if (tf
.size
< 0) or (tf
.chunkSize
<> FILE_CHUNK_SIZE
) or (length(tf
.diskName
) = 0) then
1028 e_LogWritefln('g_Net_RequestResFileInfo: invalid file info packet', []);
1032 e_LogWritefln('got file info for resource #%d: size=%d; name=%s', [resIndex
, tf
.size
, tf
.diskName
]);
1033 Result
:= 0; // success
1036 else if (rMsgId
= NTF_SERVER_ABORT
) then
1038 e_LogWriteln('g_Net_RequestResFileInfo: server aborted transfer');
1042 else if (rMsgId
= NTF_SERVER_MAP_INFO
) then
1044 e_LogWriteln('g_Net_RequestResFileInfo: waiting for map info reply, but got file info reply');
1050 e_LogWriteln('g_Net_RequestResFileInfo: invalid server packet type');
1056 ENET_EVENT_TYPE_DISCONNECT
:
1058 if (ev
.data
<= NET_DISC_MAX
) then
1059 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' ' + _lc
[TStrings_Locale(Cardinal(I_NET_DISC_NONE
) + ev
.data
)], True);
1065 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' unknown ENet event ' + IntToStr(Ord(ev
.kind
)), True);
1070 if (freePacket
) then begin freePacket
:= false; enet_packet_destroy(ev
.packet
); end;
1073 ProcessLoading(False);
1074 if g_Net_UserRequestExit() then
1076 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' user abort', True);
1082 if (freePacket
) then enet_packet_destroy(ev
.packet
);
1087 // call this to cancel file transfer requested by `g_Net_RequestResFileInfo()`
1088 function g_Net_AbortResTransfer (var tf
: TNetFileTransfer
): Boolean;
1091 e_LogWritefln('aborting file transfer...', []);
1094 trans_omsg
.Write(Byte(NTF_CLIENT_ABORT
));
1095 result
:= ftransSendClientMsg(trans_omsg
);
1096 if result
then enet_host_flush(NetHost
);
1100 // call this to start file transfer requested by `g_Net_RequestResFileInfo()`
1102 // returns `false` on error or user abort
1111 // 2 on server abort
1112 // for maps, first `tf.diskName` name will be map wad name, and `tf.hash`/`tf.size` will contain map info
1113 function g_Net_ReceiveResourceFile (resIndex
: LongInt; var tf
: TNetFileTransfer
; strm
: TStream
): Integer;
1119 freePacket
: Boolean = false;
1122 nextChunk
: Integer = 0;
1123 chunkTotal
: Integer;
1130 tf
.resumed
:= false;
1131 e_LogWritefln('file `%s`, size=%d (%d)', [tf
.diskName
, Integer(strm
.size
), tf
.size
], TMsgType
.Notify
);
1132 // check if we should resume downloading
1133 resumed
:= (strm
.size
> tf
.chunkSize
) and (strm
.size
< tf
.size
);
1136 trans_omsg
.Write(Byte(NTF_CLIENT_START
));
1137 if resumed
then chunk
:= strm
.size
div tf
.chunkSize
else chunk
:= 0;
1138 trans_omsg
.Write(LongInt(chunk
));
1139 if not ftransSendClientMsg(trans_omsg
) then begin result
:= -1; exit
; end;
1141 strm
.Seek(chunk
*tf
.chunkSize
, soFromBeginning
);
1142 chunkTotal
:= (tf
.size
+tf
.chunkSize
-1) div tf
.chunkSize
;
1143 e_LogWritefln('receiving file `%s` (%d chunks)', [tf
.diskName
, chunkTotal
], TMsgType
.Notify
);
1144 g_Game_SetLoadingText('downloading "'+ExtractFileName(tf
.diskName
)+'"', chunkTotal
, False);
1145 tf
.resumed
:= resumed
;
1147 if (chunk
> 0) then g_Game_StepLoading(chunk
);
1150 // wait for reply data
1151 FillChar(ev
, SizeOf(ev
), 0);
1153 GetMem(buf
, tf
.chunkSize
);
1155 ett
:= getNewTimeoutEnd();
1157 //stx := -GetTimerMS();
1158 status
:= enet_host_service(NetHost
, @ev
, 300);
1160 if (status < 0) then
1162 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' network error', True);
1167 if (status
<= 0) then
1169 // check for timeout
1173 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' timeout reached', True);
1182 ENET_EVENT_TYPE_RECEIVE
:
1185 if (ev
.channelID
<> NET_CHAN_DOWNLOAD_EX
) then
1187 //e_LogWritefln('g_Net_Wait_Event: skip message from non-transfer channel', []);
1188 freePacket
:= false;
1189 g_Net_Client_HandlePacket(ev
.packet
, g_Net_ClientLightMsgHandler
);
1190 if (g_Res_received_map_start
< 0) then begin result
:= -666; exit
; end;
1194 //stx := stx+GetTimerMS();
1195 //e_LogWritefln('g_Net_ReceiveResourceFile: stx=%d', [Integer(stx)]);
1196 //stx := -GetTimerMS();
1197 ett
:= getNewTimeoutEnd();
1198 if (ev
.packet
.dataLength
< 1) then
1200 e_LogWritefln('g_Net_ReceiveResourceFile: invalid server packet (no data)', []);
1204 Ptr
:= ev
.packet
^.data
;
1205 rMsgId
:= Byte(Ptr
^);
1206 if (rMsgId
= NTF_SERVER_DONE
) then
1208 e_LogWritefln('file transfer complete.', []);
1212 else if (rMsgId
= NTF_SERVER_CHUNK
) then
1214 if not msg
.Init(ev
.packet
^.data
+1, ev
.packet
^.dataLength
-1, True) then exit
;
1215 chunk
:= msg
.ReadLongInt();
1216 csize
:= msg
.ReadLongInt();
1217 if (chunk
<> nextChunk
) then
1219 e_LogWritefln('received chunk %d, but expected chunk %d', [chunk
, nextChunk
]);
1223 if (csize
< 0) or (csize
> tf
.chunkSize
) then
1225 e_LogWritefln('received chunk with size %d, but expected chunk size is %d', [csize
, tf
.chunkSize
]);
1229 //e_LogWritefln('got chunk #%d of #%d (csize=%d)', [chunk, (tf.size+tf.chunkSize-1) div tf.chunkSize, csize]);
1230 msg
.ReadData(buf
, csize
);
1231 strm
.WriteBuffer(buf
^, csize
);
1232 nextChunk
:= chunk
+1;
1233 g_Game_StepLoading();
1236 trans_omsg
.Write(Byte(NTF_CLIENT_ACK
));
1237 trans_omsg
.Write(LongInt(chunk
));
1238 if not ftransSendClientMsg(trans_omsg
) then begin result
:= -1; exit
; end;
1240 else if (rMsgId
= NTF_SERVER_ABORT
) then
1242 e_LogWritefln('g_Net_ReceiveResourceFile: server aborted transfer', []);
1248 e_LogWritefln('g_Net_ReceiveResourceFile: invalid server packet type', []);
1252 //stx := stx+GetTimerMS();
1253 //e_LogWritefln('g_Net_ReceiveResourceFile: process stx=%d', [Integer(stx)]);
1256 ENET_EVENT_TYPE_DISCONNECT
:
1258 if (ev
.data
<= NET_DISC_MAX
) then
1259 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' ' + _lc
[TStrings_Locale(Cardinal(I_NET_DISC_NONE
) + ev
.data
)], True);
1265 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' unknown ENet event ' + IntToStr(Ord(ev
.kind
)), True);
1270 if (freePacket
) then begin freePacket
:= false; enet_packet_destroy(ev
.packet
); end;
1273 ProcessLoading(False);
1274 if g_Net_UserRequestExit() then
1276 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' user abort', True);
1283 if (freePacket
) then enet_packet_destroy(ev
.packet
);
1288 //**************************************************************************
1292 //**************************************************************************
1294 function g_Net_FindSlot(): Integer;
1303 for I
:= Low(NetClients
) to High(NetClients
) do
1305 if NetClients
[I
].Used
then
1314 if C
>= NetMaxClients
then
1322 if (Length(NetClients
) >= NetMaxClients
) then
1326 SetLength(NetClients
, Length(NetClients
) + 1);
1327 N
:= High(NetClients
);
1333 NetClients
[N
].Used
:= True;
1334 NetClients
[N
].ID
:= N
;
1335 NetClients
[N
].RequestedFullUpdate
:= False;
1336 NetClients
[N
].WaitForFirstSpawn
:= False;
1337 NetClients
[N
].RCONAuth
:= False;
1338 NetClients
[N
].Voted
:= False;
1339 NetClients
[N
].Player
:= 0;
1340 clearNetClientTransfers(NetClients
[N
]); // just in case
1347 function g_Net_Init(): Boolean;
1356 NetBuf
[NET_UNRELIABLE
].Clear();
1357 NetBuf
[NET_RELIABLE
].Clear();
1358 //SetLength(NetClients, 0);
1359 clearNetClients(true); // clear array
1365 NetAddr
.port
:= 25666;
1366 SetLength(NetBannedHosts
, 0);
1367 path
:= BANLIST_FILENAME
;
1368 if e_FindResource(DataDirs
, path
) = true then
1375 if StrToIp(IPstr
, IP
) then
1379 g_Net_SaveBanList();
1382 //Result := (enet_initialize() = 0);
1383 Result
:= enet_init_success
;
1386 procedure g_Net_Flush();
1390 F
, Chan
: enet_uint32
;
1394 Chan
:= NET_CHAN_GAME
;
1396 if NetMode
= NET_SERVER
then
1397 for T
:= NET_UNRELIABLE
to NET_RELIABLE
do
1399 if NetBuf
[T
].CurSize
> 0 then
1401 P
:= enet_packet_create(NetBuf
[T
].Data
, NetBuf
[T
].CurSize
, F
);
1402 if not Assigned(P
) then continue
;
1403 enet_host_broadcast(NetHost
, Chan
, P
);
1407 for I
:= Low(NetClients
) to High(NetClients
) do
1409 if not NetClients
[I
].Used
then continue
;
1410 if NetClients
[I
].NetOut
[T
].CurSize
<= 0 then continue
;
1411 P
:= enet_packet_create(NetClients
[I
].NetOut
[T
].Data
, NetClients
[I
].NetOut
[T
].CurSize
, F
);
1412 if not Assigned(P
) then continue
;
1413 enet_peer_send(NetClients
[I
].Peer
, Chan
, P
);
1414 NetClients
[I
].NetOut
[T
].Clear();
1417 // next and last iteration is always RELIABLE
1418 F
:= LongWord(ENET_PACKET_FLAG_RELIABLE
);
1419 Chan
:= NET_CHAN_IMPORTANT
;
1421 else if NetMode
= NET_CLIENT
then
1422 for T
:= NET_UNRELIABLE
to NET_RELIABLE
do
1424 if NetBuf
[T
].CurSize
> 0 then
1426 P
:= enet_packet_create(NetBuf
[T
].Data
, NetBuf
[T
].CurSize
, F
);
1427 if not Assigned(P
) then continue
;
1428 enet_peer_send(NetPeer
, Chan
, P
);
1431 // next and last iteration is always RELIABLE
1432 F
:= LongWord(ENET_PACKET_FLAG_RELIABLE
);
1433 Chan
:= NET_CHAN_IMPORTANT
;
1437 procedure g_Net_Cleanup();
1441 NetBuf
[NET_UNRELIABLE
].Clear();
1442 NetBuf
[NET_RELIABLE
].Clear();
1444 //SetLength(NetClients, 0);
1445 clearNetClients(true); // clear array
1446 NetClientCount
:= 0;
1450 g_Net_Slist_ServerClosed();
1454 NetState
:= NET_STATE_NONE
;
1456 NetPongSock
:= ENET_SOCKET_NULL
;
1458 NetTimeToMaster
:= 0;
1459 NetTimeToUpdate
:= 0;
1460 NetTimeToReliable
:= 0;
1462 NetMode
:= NET_NONE
;
1464 if NetPortThread
<> NilThreadId
then
1465 WaitForThreadTerminate(NetPortThread
, 66666);
1467 NetPortThread
:= NilThreadId
;
1468 g_Net_UnforwardPorts();
1474 procedure g_Net_Free();
1478 //enet_deinitialize();
1479 NetInitDone
:= False;
1483 //**************************************************************************
1487 //**************************************************************************
1489 function ForwardThread(Param
: Pointer): PtrInt
;
1492 if not g_Net_ForwardPorts() then Result
:= -1;
1495 function g_Net_Host(IPAddr
: LongWord; Port
: enet_uint16
; MaxClients
: Cardinal = 16): Boolean;
1497 if NetMode
<> NET_NONE
then
1499 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_INGAME
]);
1506 g_Console_Add(_lc
[I_NET_MSG
] + Format(_lc
[I_NET_MSG_HOST
], [Port
]));
1507 if not NetInitDone
then
1509 if (not g_Net_Init()) then
1511 g_Console_Add(_lc
[I_NET_MSG_FERROR
] + _lc
[I_NET_ERR_ENET
]);
1516 NetInitDone
:= True;
1519 NetAddr
.host
:= IPAddr
;
1520 NetAddr
.port
:= Port
;
1522 NetHost
:= enet_host_create(@NetAddr
, NET_MAXCLIENTS
, NET_CHANS
, 0, 0);
1524 if (NetHost
= nil) then
1526 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + Format(_lc
[I_NET_ERR_HOST
], [Port
]));
1532 if NetForwardPorts
then NetPortThread
:= BeginThread(ForwardThread
);
1534 NetPongSock
:= enet_socket_create(ENET_SOCKET_TYPE_DATAGRAM
);
1535 if NetPongSock
<> ENET_SOCKET_NULL
then
1537 NetPongAddr
.host
:= IPAddr
;
1538 NetPongAddr
.port
:= NET_PING_PORT
;
1539 if enet_socket_bind(NetPongSock
, @NetPongAddr
) < 0 then
1541 enet_socket_destroy(NetPongSock
);
1542 NetPongSock
:= ENET_SOCKET_NULL
;
1545 enet_socket_set_option(NetPongSock
, ENET_SOCKOPT_NONBLOCK
, 1);
1548 NetMode
:= NET_SERVER
;
1550 NetBuf
[NET_UNRELIABLE
].Clear();
1551 NetBuf
[NET_RELIABLE
].Clear();
1557 procedure g_Net_Host_Die();
1561 if NetMode
<> NET_SERVER
then Exit
;
1563 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_HOST_DISCALL
]);
1564 for I
:= 0 to High(NetClients
) do
1565 if NetClients
[I
].Used
then
1566 enet_peer_disconnect(NetClients
[I
].Peer
, NET_DISC_DOWN
);
1568 while enet_host_service(NetHost
, @NetEvent
, 1000) > 0 do
1569 if NetEvent
.kind
= ENET_EVENT_TYPE_RECEIVE
then
1570 enet_packet_destroy(NetEvent
.packet
);
1572 for I
:= 0 to High(NetClients
) do
1573 if NetClients
[I
].Used
then
1575 FreeMemory(NetClients
[I
].Peer
^.data
);
1576 NetClients
[I
].Peer
^.data
:= nil;
1577 enet_peer_reset(NetClients
[I
].Peer
);
1578 NetClients
[I
].Peer
:= nil;
1579 NetClients
[I
].Used
:= False;
1580 NetClients
[I
].Player
:= 0;
1581 NetClients
[I
].Crimes
:= 0;
1582 NetClients
[I
].AuthTime
:= 0;
1583 NetClients
[I
].MsgTime
:= 0;
1584 NetClients
[I
].NetOut
[NET_UNRELIABLE
].Free();
1585 NetClients
[I
].NetOut
[NET_RELIABLE
].Free();
1588 clearNetClients(false); // don't clear array
1589 g_Net_Slist_ServerClosed();
1590 if NetPongSock
<> ENET_SOCKET_NULL
then
1591 enet_socket_destroy(NetPongSock
);
1593 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_HOST_DIE
]);
1594 enet_host_destroy(NetHost
);
1596 NetMode
:= NET_NONE
;
1599 e_WriteLog('NET: Server stopped', TMsgType
.Notify
);
1603 procedure g_Net_Host_Send(ID
: Integer; Reliable
: Boolean; Chan
: Byte = NET_CHAN_GAME
);
1610 T
:= NET_UNRELIABLE
;
1614 if ID
> High(NetClients
) then Exit
;
1615 if NetClients
[ID
].Peer
= nil then Exit
;
1617 NetClients
[ID
].NetOut
[T
].Write(Integer(NetOut
.CurSize
));
1618 NetClients
[ID
].NetOut
[T
].Write(NetOut
);
1623 NetBuf
[T
].Write(Integer(NetOut
.CurSize
));
1624 NetBuf
[T
].Write(NetOut
);
1627 if NetDump
then g_Net_DumpSendBuffer();
1631 procedure g_Net_Host_Disconnect_Client(ID
: Integer; Force
: Boolean = False);
1636 TC
:= @NetClients
[ID
];
1637 if (TC
= nil) then Exit
;
1638 clearNetClient(NetClients
[ID
]);
1639 if not (TC
^.Used
) then Exit
;
1641 TP
:= g_Player_Get(TC
^.Player
);
1646 TP
.Kill(K_SIMPLEKILL
, 0, HIT_DISCON
);
1647 g_Console_Add(Format(_lc
[I_PLAYER_LEAVE
], [TP
.Name
]), True);
1648 e_WriteLog('NET: Client ' + TP
.Name
+ ' [' + IntToStr(TC
^.ID
) + '] disconnected.', TMsgType
.Notify
);
1649 g_Player_Remove(TP
.UID
);
1652 if (TC
^.Peer
^.data
<> nil) then
1654 FreeMemory(TC
^.Peer
^.data
);
1655 TC
^.Peer
^.data
:= nil;
1659 enet_peer_reset(TC
^.Peer
);
1662 TC
^.State
:= NET_STATE_NONE
;
1668 TC
^.RequestedFullUpdate
:= False;
1669 TC
^.FullUpdateSent
:= False;
1670 TC
^.WaitForFirstSpawn
:= False;
1671 TC
^.NetOut
[NET_UNRELIABLE
].Free();
1672 TC
^.NetOut
[NET_RELIABLE
].Free();
1674 g_Console_Add(_lc
[I_NET_MSG
] + Format(_lc
[I_NET_MSG_HOST_DISC
], [ID
]));
1675 Dec(NetClientCount
);
1677 if NetUseMaster
then g_Net_Slist_ServerPlayerLeaves();
1680 procedure g_Net_Host_Kick(ID
: Integer; Reason
: enet_uint32
);
1685 TC
:= @NetClients
[ID
];
1686 if (TC
<> nil) and TC
^.Used
and (TC
^.Peer
<> nil) then
1689 g_Net_Host_Disconnect_Client(ID
);
1690 enet_peer_disconnect(Peer
, Reason
);
1694 procedure g_Net_Host_CheckPings();
1696 ClAddr
: ENetAddress
;
1700 Ping
: array [0..9] of Byte;
1703 if (NetPongSock
= ENET_SOCKET_NULL
) or (NetHost
= nil) then Exit
;
1705 Buf
.data
:= Addr(Ping
[0]);
1706 Buf
.dataLength
:= 2+8;
1710 Len
:= enet_socket_receive(NetPongSock
, @ClAddr
, @Buf
, 1);
1711 if Len
< 0 then Exit
;
1713 if (Ping
[0] = Ord('D')) and (Ping
[1] = Ord('F')) then
1715 ClTime
:= Int64(Addr(Ping
[2])^);
1718 NetOut
.Write(Byte(Ord('D')));
1719 NetOut
.Write(Byte(Ord('F')));
1720 NetOut
.Write(NetHost
.address
.port
);
1721 NetOut
.Write(ClTime
);
1722 TMasterHost
.writeInfo(NetOut
);
1724 if gPlayer1
<> nil then Inc(NPl
);
1725 if gPlayer2
<> nil then Inc(NPl
);
1727 NetOut
.Write(gNumBots
);
1729 Buf
.data
:= NetOut
.Data
;
1730 Buf
.dataLength
:= NetOut
.CurSize
;
1731 enet_socket_send(NetPongSock
, @ClAddr
, @Buf
, 1);
1737 procedure g_Net_Host_CheckTimeouts();
1741 for ID
:= Low(NetClients
) to High(NetClients
) do
1743 with NetClients
[ID
] do
1745 if (Peer
= nil) or (State
= NET_STATE_NONE
) then continue
;
1746 if (State
= NET_STATE_AUTH
) and (AuthTime
> 0) and (AuthTime
<= gTime
) then
1748 g_Net_Penalize(@NetClients
[ID
], 'auth taking too long');
1749 AuthTime
:= gTime
+ 1000; // do it every second to give them a chance
1751 else if (State
= NET_STATE_GAME
) and (MsgTime
> 0) and (MsgTime
<= gTime
) then
1753 // client hasn't sent packets in a while; either ban em or kick em
1754 if (NetAutoBanForTimeout
) then
1756 g_Net_Penalize(@NetClients
[ID
], 'message timeout');
1757 MsgTime
:= gTime
+ (NetPacketTimeout
div 2) + 500; // wait less for the next check
1761 e_LogWritefln('NET: client #%u (cid #%u) timed out', [ID
, Player
]);
1762 g_Net_Host_Disconnect_Client(ID
, True);
1770 procedure g_Net_Host_Update();
1779 if NetUseMaster
then g_Net_Slist_Pulse();
1780 g_Net_Host_CheckPings();
1781 g_Net_Host_CheckTimeouts();
1783 while (enet_host_service(NetHost
, @NetEvent
, 0) > 0) do
1785 case (NetEvent
.kind
) of
1786 ENET_EVENT_TYPE_CONNECT
:
1788 IP
:= IpToStr(NetEvent
.Peer
^.address
.host
);
1789 Port
:= NetEvent
.Peer
^.address
.port
;
1790 g_Console_Add(_lc
[I_NET_MSG
] +
1791 Format(_lc
[I_NET_MSG_HOST_CONN
], [IP
, Port
]));
1792 e_WriteLog('NET: Connection request from ' + IP
+ '.', TMsgType
.Notify
);
1794 if (NetEvent
.data
<> NET_PROTOCOL_VER
) then
1796 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_HOST_REJECT
] +
1797 _lc
[I_NET_DISC_PROTOCOL
]);
1798 e_WriteLog('NET: Connection request from ' + IP
+ ' rejected: version mismatch',
1800 enet_peer_disconnect(NetEvent
.peer
, NET_DISC_PROTOCOL
);
1804 if g_Net_IsHostBanned(NetEvent
.Peer
^.address
.host
) then
1806 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_HOST_REJECT
] +
1807 _lc
[I_NET_DISC_BAN
]);
1808 e_WriteLog('NET: Connection request from ' + IP
+ ' rejected: banned',
1810 enet_peer_disconnect(NetEvent
.Peer
, NET_DISC_BAN
);
1814 ID
:= g_Net_FindSlot();
1818 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_HOST_REJECT
] +
1819 _lc
[I_NET_DISC_FULL
]);
1820 e_WriteLog('NET: Connection request from ' + IP
+ ' rejected: server full',
1822 enet_peer_disconnect(NetEvent
.peer
, NET_DISC_FULL
);
1826 NetClients
[ID
].Peer
:= NetEvent
.peer
;
1827 NetClients
[ID
].Peer
^.data
:= GetMemory(SizeOf(Byte));
1828 Byte(NetClients
[ID
].Peer
^.data
^) := ID
;
1829 NetClients
[ID
].State
:= NET_STATE_AUTH
;
1830 NetClients
[ID
].Player
:= 0;
1831 NetClients
[ID
].Crimes
:= 0;
1832 NetClients
[ID
].RCONAuth
:= False;
1833 NetClients
[ID
].NetOut
[NET_UNRELIABLE
].Alloc(NET_BUFSIZE
*2);
1834 NetClients
[ID
].NetOut
[NET_RELIABLE
].Alloc(NET_BUFSIZE
*2);
1835 if (NetAuthTimeout
> 0) then
1836 NetClients
[ID
].AuthTime
:= gTime
+ NetAuthTimeout
1838 NetClients
[ID
].AuthTime
:= 0;
1839 if (NetPacketTimeout
> 0) then
1840 NetClients
[ID
].MsgTime
:= gTime
+ NetPacketTimeout
1842 NetClients
[ID
].MsgTime
:= 0;
1843 clearNetClientTransfers(NetClients
[ID
]); // just in case
1845 enet_peer_timeout(NetEvent
.peer
, ENET_PEER_TIMEOUT_LIMIT
* 2, ENET_PEER_TIMEOUT_MINIMUM
* 2, ENET_PEER_TIMEOUT_MAXIMUM
* 2);
1847 Inc(NetClientCount
);
1848 g_Console_Add(_lc
[I_NET_MSG
] + Format(_lc
[I_NET_MSG_HOST_ADD
], [ID
]));
1851 ENET_EVENT_TYPE_RECEIVE
:
1853 //e_LogWritefln('RECEIVE: chan=%u', [NetEvent.channelID]);
1854 if (NetEvent
.channelID
= NET_CHAN_DOWNLOAD_EX
) then
1856 ProcessDownloadExPacket();
1860 if NetEvent
.peer
^.data
= nil then Exit
;
1862 ID
:= Byte(NetEvent
.peer
^.data
^);
1863 if ID
> High(NetClients
) then Exit
;
1864 TC
:= @NetClients
[ID
];
1866 if (NetPacketTimeout
> 0) then
1867 TC
^.MsgTime
:= gTime
+ NetPacketTimeout
;
1869 if NetDump
then g_Net_DumpRecvBuffer(NetEvent
.packet
^.data
, NetEvent
.packet
^.dataLength
);
1870 g_Net_Host_HandlePacket(TC
, NetEvent
.packet
, g_Net_HostMsgHandler
);
1874 ENET_EVENT_TYPE_DISCONNECT
:
1876 if NetEvent
.peer
^.data
<> nil then
1878 ID
:= Byte(NetEvent
.peer
^.data
^);
1879 if ID
> High(NetClients
) then Exit
;
1880 g_Net_Host_Disconnect_Client(ID
);
1888 //**************************************************************************
1892 //**************************************************************************
1894 procedure g_Net_Disconnect(Forced
: Boolean = False);
1896 if NetMode
<> NET_CLIENT
then Exit
;
1897 if (NetHost
= nil) or (NetPeer
= nil) then Exit
;
1901 enet_peer_disconnect(NetPeer
, NET_DISC_NONE
);
1903 while (enet_host_service(NetHost
, @NetEvent
, 1500) > 0) do
1905 if (NetEvent
.kind
= ENET_EVENT_TYPE_DISCONNECT
) then
1911 if (NetEvent
.kind
= ENET_EVENT_TYPE_RECEIVE
) then
1912 enet_packet_destroy(NetEvent
.packet
);
1915 if NetPeer
<> nil then
1917 enet_peer_reset(NetPeer
);
1923 e_WriteLog('NET: Kicked from server: ' + IntToStr(NetEvent
.data
), TMsgType
.Notify
);
1924 if (NetEvent
.data
<= NET_DISC_MAX
) then
1925 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_KICK
] +
1926 _lc
[TStrings_Locale(Cardinal(I_NET_DISC_NONE
) + NetEvent
.data
)], True);
1929 if NetHost
<> nil then
1931 enet_host_destroy(NetHost
);
1934 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_CLIENT_DISC
]);
1937 e_WriteLog('NET: Disconnected', TMsgType
.Notify
);
1940 procedure g_Net_Client_Send(Reliable
: Boolean; Chan
: Byte = NET_CHAN_GAME
);
1947 T
:= NET_UNRELIABLE
;
1950 NetBuf
[T
].Write(Integer(NetOut
.CurSize
));
1951 NetBuf
[T
].Write(NetOut
);
1953 if NetDump
then g_Net_DumpSendBuffer();
1955 g_Net_Flush(); // FIXME: for now, send immediately
1958 procedure g_Net_Client_Update();
1960 while (NetHost
<> nil) and (enet_host_service(NetHost
, @NetEvent
, 0) > 0) do
1962 case NetEvent
.kind
of
1963 ENET_EVENT_TYPE_RECEIVE
:
1965 if NetDump
then g_Net_DumpRecvBuffer(NetEvent
.packet
^.data
, NetEvent
.packet
^.dataLength
);
1966 g_Net_Client_HandlePacket(NetEvent
.packet
, g_Net_ClientMsgHandler
);
1969 ENET_EVENT_TYPE_DISCONNECT
:
1971 g_Net_Disconnect(True);
1978 function g_Net_Connect(IP
: string; Port
: enet_uint16
): Boolean;
1981 TimeoutTime
, T
: Int64;
1983 if NetMode
<> NET_NONE
then
1985 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_ERR_INGAME
], True);
1992 g_Console_Add(_lc
[I_NET_MSG
] + Format(_lc
[I_NET_MSG_CLIENT_CONN
],
1994 if not NetInitDone
then
1996 if (not g_Net_Init()) then
1998 g_Console_Add(_lc
[I_NET_MSG_FERROR
] + _lc
[I_NET_ERR_ENET
], True);
2003 NetInitDone
:= True;
2006 NetHost
:= enet_host_create(nil, 1, NET_CHANS
, 0, 0);
2008 if (NetHost
= nil) then
2010 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CLIENT
], True);
2016 enet_address_set_host(@NetAddr
, PChar(Addr(IP
[1])));
2017 NetAddr
.port
:= Port
;
2019 NetPeer
:= enet_host_connect(NetHost
, @NetAddr
, NET_CHANS
, NET_PROTOCOL_VER
);
2021 if (NetPeer
= nil) then
2023 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CLIENT
], True);
2024 enet_host_destroy(NetHost
);
2030 // предупредить что ждем слишком долго через N секунд
2031 TimeoutTime
:= sys_GetTicks() + NET_CONNECT_TIMEOUT
;
2036 while (enet_host_service(NetHost
, @NetEvent
, 0) > 0) do
2038 if (NetEvent
.kind
= ENET_EVENT_TYPE_CONNECT
) then
2040 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_CLIENT_DONE
]);
2041 NetMode
:= NET_CLIENT
;
2043 enet_peer_timeout(NetPeer
, ENET_PEER_TIMEOUT_LIMIT
* 2, ENET_PEER_TIMEOUT_MINIMUM
* 2, ENET_PEER_TIMEOUT_MAXIMUM
* 2);
2045 NetClientPort
:= Port
;
2052 T
:= sys_GetTicks();
2053 if T
> TimeoutTime
then
2055 TimeoutTime
:= T
+ NET_CONNECT_TIMEOUT
* 100; // одного предупреждения хватит
2056 g_Console_Add(_lc
[I_NET_MSG_TIMEOUT_WARN
], True);
2057 g_Console_Add(Format(_lc
[I_NET_MSG_PORTS
], [Integer(Port
), Integer(NET_PING_PORT
)]), True);
2060 ProcessLoading(True);
2061 if e_KeyPressed(IK_SPACE
) or e_KeyPressed(IK_ESCAPE
) or e_KeyPressed(VK_ESCAPE
) or
2062 e_KeyPressed(JOY0_JUMP
) or e_KeyPressed(JOY1_JUMP
) or e_KeyPressed(JOY2_JUMP
) or e_KeyPressed(JOY3_JUMP
) then
2066 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_TIMEOUT
], True);
2067 g_Console_Add(Format(_lc
[I_NET_MSG_PORTS
], [Integer(Port
), Integer(NET_PING_PORT
)]), True);
2068 if NetPeer
<> nil then enet_peer_reset(NetPeer
);
2069 if NetHost
<> nil then
2071 enet_host_destroy(NetHost
);
2078 function IpToStr(IP
: LongWord): string;
2083 Result
:= IntToStr(PByte(Ptr
+ 0)^) + '.';
2084 Result
:= Result
+ IntToStr(PByte(Ptr
+ 1)^) + '.';
2085 Result
:= Result
+ IntToStr(PByte(Ptr
+ 2)^) + '.';
2086 Result
:= Result
+ IntToStr(PByte(Ptr
+ 3)^);
2089 function StrToIp(IPstr
: string; var IP
: LongWord): Boolean;
2093 Result
:= enet_address_set_host(@EAddr
, PChar(@IPstr
[1])) = 0;
2097 function g_Net_Client_ByName(Name
: string): pTNetClient
;
2103 for a
:= Low(NetClients
) to High(NetClients
) do
2104 if (NetClients
[a
].Used
) and (NetClients
[a
].State
= NET_STATE_GAME
) then
2106 pl
:= g_Player_Get(NetClients
[a
].Player
);
2107 if pl
= nil then continue
;
2108 if Copy(LowerCase(pl
.Name
), 1, Length(Name
)) <> LowerCase(Name
) then continue
;
2109 if NetClients
[a
].Peer
<> nil then
2111 Result
:= @NetClients
[a
];
2117 function g_Net_Client_ByPlayer(PID
: Word): pTNetClient
;
2122 for a
:= Low(NetClients
) to High(NetClients
) do
2123 if (NetClients
[a
].Used
) and (NetClients
[a
].State
= NET_STATE_GAME
) then
2124 if NetClients
[a
].Player
= PID
then
2126 Result
:= @NetClients
[a
];
2131 function g_Net_ClientName_ByID(ID
: Integer): string;
2137 if ID
= NET_EVERYONE
then
2139 for a
:= Low(NetClients
) to High(NetClients
) do
2140 if (NetClients
[a
].ID
= ID
) and (NetClients
[a
].Used
) and (NetClients
[a
].State
= NET_STATE_GAME
) then
2142 pl
:= g_Player_Get(NetClients
[a
].Player
);
2143 if pl
= nil then Exit
;
2148 procedure g_Net_SendData(Data
: AByte
; peer
: pENetPeer
; Reliable
: Boolean; Chan
: Byte = NET_CHAN_DOWNLOAD
);
2152 dataLength
: Cardinal;
2154 dataLength
:= Length(Data
);
2157 then F
:= LongWord(ENET_PACKET_FLAG_RELIABLE
)
2160 P
:= enet_packet_create(@Data
[0], dataLength
, F
);
2161 if not Assigned(P
) then exit
;
2164 then enet_peer_send(peer
, Chan
, P
)
2165 else enet_host_broadcast(NetHost
, Chan
, P
);
2167 enet_host_flush(NetHost
);
2170 function g_Net_IsHostBanned(IP
: LongWord; Perm
: Boolean = False): Boolean;
2175 if NetBannedHosts
= nil then
2177 for I
:= 0 to High(NetBannedHosts
) do
2178 if (NetBannedHosts
[I
].IP
= IP
) and ((not Perm
) or (NetBannedHosts
[I
].Perm
)) then
2185 procedure g_Net_BanHost(IP
: LongWord; Perm
: Boolean = True); overload
;
2191 if g_Net_IsHostBanned(IP
, Perm
) then
2195 for I
:= Low(NetBannedHosts
) to High(NetBannedHosts
) do
2196 if NetBannedHosts
[I
].IP
= 0 then
2204 SetLength(NetBannedHosts
, Length(NetBannedHosts
) + 1);
2205 P
:= High(NetBannedHosts
);
2208 NetBannedHosts
[P
].IP
:= IP
;
2209 NetBannedHosts
[P
].Perm
:= Perm
;
2212 procedure g_Net_BanHost(IP
: string; Perm
: Boolean = True); overload
;
2217 b
:= StrToIp(IP
, a
);
2219 g_Net_BanHost(a
, Perm
);
2222 procedure g_Net_UnbanNonPermHosts();
2226 if NetBannedHosts
= nil then
2228 for I
:= Low(NetBannedHosts
) to High(NetBannedHosts
) do
2229 if (NetBannedHosts
[I
].IP
> 0) and not NetBannedHosts
[I
].Perm
then
2231 NetBannedHosts
[I
].IP
:= 0;
2232 NetBannedHosts
[I
].Perm
:= True;
2236 function g_Net_UnbanHost(IP
: string): Boolean; overload
;
2240 Result
:= StrToIp(IP
, a
);
2242 Result
:= g_Net_UnbanHost(a
);
2245 function g_Net_UnbanHost(IP
: LongWord): Boolean; overload
;
2252 if NetBannedHosts
= nil then
2254 for I
:= 0 to High(NetBannedHosts
) do
2255 if NetBannedHosts
[I
].IP
= IP
then
2257 NetBannedHosts
[I
].IP
:= 0;
2258 NetBannedHosts
[I
].Perm
:= True;
2260 // no break here to clear all bans of this host, perm and non-perm
2264 procedure g_Net_SaveBanList();
2270 path
:= e_GetWriteableDir(DataDirs
);
2273 path
:= e_CatPath(path
, BANLIST_FILENAME
);
2276 if NetBannedHosts
<> nil then
2277 for I
:= 0 to High(NetBannedHosts
) do
2278 if NetBannedHosts
[I
].Perm
and (NetBannedHosts
[I
].IP
> 0) then
2279 Writeln(F
, IpToStr(NetBannedHosts
[I
].IP
));
2284 procedure g_Net_Penalize(C
: pTNetClient
; Reason
: string);
2288 e_LogWritefln('NET: client #%u (cid #%u) triggered a penalty (%d/%d): %s',
2289 [C
^.ID
, C
^.Player
, C
^.Crimes
+ 1, NetAutoBanLimit
, Reason
]);
2291 if (NetAutoBanLimit
<= 0) then Exit
;
2293 if (C
^.Crimes
>= NetAutoBanLimit
) then
2295 // we have tried asking nicely before, now it is time to die
2296 e_LogWritefln('NET: client #%u (cid #%u) force kicked',
2297 [C
^.ID
, C
^.Player
]);
2298 g_Net_Host_Disconnect_Client(C
^.ID
, True);
2304 if (NetAutoBanWarn
) then
2305 MH_SEND_Chat('You have been warned by the server: ' + Reason
, NET_CHAT_SYSTEM
, C
^.ID
);
2307 if (C
^.Crimes
>= NetAutoBanLimit
) then
2309 s
:= '#' + IntToStr(C
^.ID
); // can't be arsed
2310 g_Net_BanHost(C
^.Peer
^.address
.host
, NetAutoBanPerm
);
2311 g_Net_Host_Kick(C
^.ID
, NET_DISC_BAN
);
2312 g_Console_Add(Format(_lc
[I_PLAYER_BAN
], [s
]));
2313 MH_SEND_GameEvent(NET_EV_PLAYER_BAN
, 0, s
);
2314 g_Net_Slist_ServerPlayerLeaves();
2318 procedure g_Net_DumpStart();
2320 if NetMode
= NET_SERVER
then
2321 NetDumpFile
:= e_CreateResource(LogDirs
, NETDUMP_FILENAME
+ '_server')
2323 NetDumpFile
:= e_CreateResource(LogDirs
, NETDUMP_FILENAME
+ '_client');
2326 procedure g_Net_DumpSendBuffer();
2328 writeInt(NetDumpFile
, gTime
);
2329 writeInt(NetDumpFile
, LongWord(NetOut
.CurSize
));
2330 writeInt(NetDumpFile
, Byte(1));
2331 NetDumpFile
.WriteBuffer(NetOut
.Data
^, NetOut
.CurSize
);
2334 procedure g_Net_DumpRecvBuffer(Buf
: penet_uint8
; Len
: LongWord);
2336 if (Buf
= nil) or (Len
= 0) then Exit
;
2337 writeInt(NetDumpFile
, gTime
);
2338 writeInt(NetDumpFile
, Len
);
2339 writeInt(NetDumpFile
, Byte(0));
2340 NetDumpFile
.WriteBuffer(Buf
^, Len
);
2343 procedure g_Net_DumpEnd();
2349 function g_Net_ForwardPorts(ForwardPongPort
: Boolean = True): Boolean;
2350 {$IFDEF USE_MINIUPNPC}
2355 LanAddr
: array [0..255] of Char;
2356 StrPort
: AnsiString;
2361 if NetHost
= nil then
2364 if NetPortForwarded
= NetHost
.address
.port
then
2370 NetPongForwarded
:= False;
2371 NetPortForwarded
:= 0;
2373 DevList
:= upnpDiscover(1000, nil, nil, 0, 0, 2, Addr(Err
));
2374 if DevList
= nil then
2376 conwritefln('port forwarding failed: upnpDiscover() failed: %d', [Err
]);
2380 I
:= UPNP_GetValidIGD(DevList
, @Urls
, @Data
, Addr(LanAddr
[0]), 256);
2384 conwriteln('port forwarding failed: could not find an IGD device on this LAN');
2385 FreeUPNPDevList(DevList
);
2386 FreeUPNPUrls(@Urls
);
2390 StrPort
:= IntToStr(NetHost
.address
.port
);
2391 I
:= UPNP_AddPortMapping(
2392 Urls
.controlURL
, Addr(data
.first
.servicetype
[1]),
2393 PChar(StrPort
), PChar(StrPort
), Addr(LanAddr
[0]), PChar('D2DF'),
2394 PChar('UDP'), nil, PChar('0')
2399 conwritefln('forwarding port %d failed: error %d', [NetHost
.address
.port
, I
]);
2400 FreeUPNPDevList(DevList
);
2401 FreeUPNPUrls(@Urls
);
2405 if ForwardPongPort
then
2407 StrPort
:= IntToStr(NET_PING_PORT
);
2408 I
:= UPNP_AddPortMapping(
2409 Urls
.controlURL
, Addr(data
.first
.servicetype
[1]),
2410 PChar(StrPort
), PChar(StrPort
), Addr(LanAddr
[0]), PChar('D2DF'),
2411 PChar('UDP'), nil, PChar('0')
2416 conwritefln('forwarding port %d failed: error %d', [NET_PING_PORT
, I
]);
2417 NetPongForwarded
:= False;
2421 conwritefln('forwarded port %d successfully', [NET_PING_PORT
]);
2422 NetPongForwarded
:= True;
2426 conwritefln('forwarded port %d successfully', [NetHost
.address
.port
]);
2427 NetIGDControl
:= AnsiString(Urls
.controlURL
);
2428 NetIGDService
:= data
.first
.servicetype
;
2429 NetPortForwarded
:= NetHost
.address
.port
;
2431 FreeUPNPDevList(DevList
);
2432 FreeUPNPUrls(@Urls
);
2441 procedure g_Net_UnforwardPorts();
2442 {$IFDEF USE_MINIUPNPC}
2445 StrPort
: AnsiString;
2447 if NetPortForwarded
= 0 then Exit
;
2449 conwriteln('unforwarding ports...');
2451 StrPort
:= IntToStr(NetPortForwarded
);
2452 I
:= UPNP_DeletePortMapping(
2453 PChar(NetIGDControl
), Addr(NetIGDService
[1]),
2454 PChar(StrPort
), PChar('UDP'), nil
2456 conwritefln(' port %d: %d', [NetPortForwarded
, I
]);
2458 if NetPongForwarded
then
2460 NetPongForwarded
:= False;
2461 StrPort
:= IntToStr(NET_PING_PORT
);
2462 I
:= UPNP_DeletePortMapping(
2463 PChar(NetIGDControl
), Addr(NetIGDService
[1]),
2464 PChar(StrPort
), PChar('UDP'), nil
2466 conwritefln(' port %d: %d', [NET_PING_PORT
, I
]);
2469 NetPortForwarded
:= 0;
2476 procedure NetServerCVars(P
: SSArray
);
2481 cmd
:= LowerCase(P
[0]);
2485 if (Length(P
) > 1) and (Length(P
[1]) > 0) then
2487 NetServerName
:= P
[1];
2488 if Length(NetServerName
) > 64 then
2489 SetLength(NetServerName
, 64);
2490 g_Net_Slist_ServerRenamed();
2492 g_Console_Add(cmd
+ ' "' + NetServerName
+ '"');
2496 if (Length(P
) > 1) and (Length(P
[1]) > 0) then
2498 NetPassword
:= P
[1];
2499 if Length(NetPassword
) > 24 then
2500 SetLength(NetPassword
, 24);
2501 g_Net_Slist_ServerRenamed();
2503 g_Console_Add(cmd
+ ' "' + AnsiLowerCase(NetPassword
) + '"');
2507 if (Length(P
) > 1) then
2509 NetMaxClients
:= nclamp(StrToIntDef(P
[1], NetMaxClients
), 1, NET_MAXCLIENTS
);
2510 if g_Game_IsServer
and g_Game_IsNet
then
2513 for a
:= 0 to High(NetClients
) do
2515 if NetClients
[a
].Used
then
2518 if b
> NetMaxClients
then
2520 s
:= g_Player_Get(NetClients
[a
].Player
).Name
;
2521 g_Net_Host_Kick(NetClients
[a
].ID
, NET_DISC_FULL
);
2522 g_Console_Add(Format(_lc
[I_PLAYER_KICK
], [s
]));
2523 MH_SEND_GameEvent(NET_EV_PLAYER_KICK
, 0, s
);
2527 g_Net_Slist_ServerRenamed();
2530 g_Console_Add(cmd
+ ' ' + IntToStr(NetMaxClients
));
2534 if (Length(P
) > 1) then
2536 NetUseMaster
:= StrToIntDef(P
[1], Byte(NetUseMaster
)) <> 0;
2537 if NetUseMaster
then g_Net_Slist_Public() else g_Net_Slist_Private();
2539 g_Console_Add(cmd
+ ' ' + IntToStr(Byte(NetUseMaster
)));
2543 if (Length(P
) > 1) then
2545 if not g_Game_IsNet
then
2546 NetPort
:= nclamp(StrToIntDef(P
[1], NetPort
), 0, $FFFF)
2548 g_Console_Add(_lc
[I_MSG_NOT_NETGAME
]);
2550 g_Console_Add(cmd
+ ' ' + IntToStr(Ord(NetUseMaster
)));
2556 conRegVar('cl_downloadtimeout', @g_Net_DownloadTimeout
, 0.0, 1000000.0, '', 'timeout in seconds, 0 to disable it');
2557 conRegVar('cl_predictself', @NetPredictSelf
, '', 'predict local player');
2558 conRegVar('cl_forceplayerupdate', @NetForcePlayerUpdate
, '', 'update net players on NET_MSG_PLRPOS');
2559 conRegVar('cl_interp', @NetInterpLevel
, '', 'net player interpolation steps');
2560 conRegVar('cl_last_ip', @NetClientIP
, '', 'address of the last you have connected to');
2561 conRegVar('cl_last_port', @NetClientPort
, '', 'port of the last server you have connected to');
2562 conRegVar('cl_deafen', @NetDeafLevel
, '', 'filter server messages (0-3)');
2564 conRegVar('sv_forwardports', @NetForwardPorts
, '', 'forward server port using miniupnpc (requires server restart)');
2565 conRegVar('sv_rcon', @NetAllowRCON
, '', 'enable remote console');
2566 conRegVar('sv_rcon_password', @NetRCONPassword
, '', 'remote console password');
2567 conRegVar('sv_update_interval', @NetUpdateRate
, '', 'unreliable update interval');
2568 conRegVar('sv_reliable_interval', @NetRelupdRate
, '', 'reliable update interval');
2569 conRegVar('sv_master_interval', @NetMasterRate
, '', 'master server update interval');
2571 conRegVar('sv_autoban_threshold', @NetAutoBanLimit
, '', 'max crimes before autoban (0 = no autoban)');
2572 conRegVar('sv_autoban_permanent', @NetAutoBanPerm
, '', 'whether autobans are permanent');
2573 conRegVar('sv_autoban_warn', @NetAutoBanWarn
, '', 'send warnings to the client when he triggers penalties');
2574 conRegVar('sv_autoban_packet_timeout', @NetAutoBanForTimeout
, '', 'autoban for packet timeouts');
2576 conRegVar('sv_auth_timeout', @NetAuthTimeout
, '', 'number of msec in which connecting clients must complete auth (0 = unlimited)');
2577 conRegVar('sv_packet_timeout', @NetPacketTimeout
, '', 'number of msec the client must idle to be kicked (0 = unlimited)');
2579 conRegVar('net_master_list', @NetMasterList
, '', 'list of master servers');
2581 SetLength(NetClients
, 0);
2582 g_Net_DownloadTimeout
:= 60;
2583 NetIn
.Alloc(NET_BUFSIZE
);
2584 NetOut
.Alloc(NET_BUFSIZE
);
2585 NetBuf
[NET_UNRELIABLE
].Alloc(NET_BUFSIZE
*2);
2586 NetBuf
[NET_RELIABLE
].Alloc(NET_BUFSIZE
*2);
2587 trans_omsg
.Alloc(NET_BUFSIZE
);
2591 NetBuf
[NET_UNRELIABLE
].Free();
2592 NetBuf
[NET_RELIABLE
].Free();