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;
164 NetAuthTimeout
: Integer = 15 * 1000;
165 NetPacketTimeout
: Integer = 30 * 1000;
167 NetState
: Integer = NET_STATE_NONE
;
169 NetMyID
: Integer = -1;
170 NetPlrUID1
: Integer = -1;
171 NetPlrUID2
: Integer = -1;
173 NetInterpLevel
: Integer = 1;
174 NetUpdateRate
: Cardinal = 0; // as soon as possible
175 NetRelupdRate
: Cardinal = 18; // around two times a second
176 NetMasterRate
: Cardinal = 60000;
178 NetForcePlayerUpdate
: Boolean = False;
179 NetPredictSelf
: Boolean = True;
180 NetForwardPorts
: Boolean = False;
182 NetGotEverything
: Boolean = False;
183 NetGotKeys
: Boolean = False;
185 NetDeafLevel
: Integer = 0;
187 {$IFDEF USE_MINIUPNPC}
188 NetPortForwarded
: Word = 0;
189 NetPongForwarded
: Boolean = False;
190 NetIGDControl
: AnsiString;
191 NetIGDService
: TURLStr
;
194 NetPortThread
: TThreadID
= NilThreadId
;
196 NetDumpFile
: TStream
;
198 g_Res_received_map_start
: Integer = 0; // set if we received "map change" event
201 function g_Net_Init(): Boolean;
202 procedure g_Net_Cleanup();
203 procedure g_Net_Free();
204 procedure g_Net_Flush();
206 function g_Net_Host(IPAddr
: LongWord; Port
: enet_uint16
; MaxClients
: Cardinal = 16): Boolean;
207 procedure g_Net_Host_Die();
208 procedure g_Net_Host_Send(ID
: Integer; Reliable
: Boolean; Chan
: Byte = NET_CHAN_GAME
);
209 function g_Net_Host_Update(): enet_size_t
;
211 function g_Net_Connect(IP
: string; Port
: enet_uint16
): Boolean;
212 procedure g_Net_Disconnect(Forced
: Boolean = False);
213 procedure g_Net_Client_Send(Reliable
: Boolean; Chan
: Byte = NET_CHAN_GAME
);
214 function g_Net_Client_Update(): enet_size_t
;
215 function g_Net_Client_UpdateWhileLoading(): enet_size_t
;
217 function g_Net_Client_ByName(Name
: string): pTNetClient
;
218 function g_Net_Client_ByPlayer(PID
: Word): pTNetClient
;
219 function g_Net_ClientName_ByID(ID
: Integer): string;
221 procedure g_Net_SendData(Data
: AByte
; peer
: pENetPeer
; Reliable
: Boolean; Chan
: Byte = NET_CHAN_DOWNLOAD
);
222 //function g_Net_Wait_Event(msgId: Word): TMemoryStream;
223 //function g_Net_Wait_FileInfo (var tf: TNetFileTransfer; asMap: Boolean; out resList: TStringList): Integer;
225 function IpToStr(IP
: LongWord): string;
226 function StrToIp(IPstr
: string; var IP
: LongWord): Boolean;
228 function g_Net_IsHostBanned(IP
: LongWord; Perm
: Boolean = False): Boolean;
229 procedure g_Net_BanHost(IP
: LongWord; Perm
: Boolean = True); overload
;
230 procedure g_Net_BanHost(IP
: string; Perm
: Boolean = True); overload
;
231 function g_Net_UnbanHost(IP
: string): Boolean; overload
;
232 function g_Net_UnbanHost(IP
: LongWord): Boolean; overload
;
233 procedure g_Net_UnbanNonPermHosts();
234 procedure g_Net_SaveBanList();
236 procedure g_Net_Penalize(C
: pTNetClient
; Reason
: string);
238 procedure g_Net_DumpStart();
239 procedure g_Net_DumpSendBuffer();
240 procedure g_Net_DumpRecvBuffer(Buf
: penet_uint8
; Len
: LongWord);
241 procedure g_Net_DumpEnd();
243 function g_Net_ForwardPorts(ForwardPongPort
: Boolean = True): Boolean;
244 procedure g_Net_UnforwardPorts();
246 function g_Net_UserRequestExit
: Boolean;
248 function g_Net_Wait_MapInfo (var tf
: TNetFileTransfer
; var resList
: TNetMapResourceInfoArray
): Integer;
249 function g_Net_RequestResFileInfo (resIndex
: LongInt; out tf
: TNetFileTransfer
): Integer;
250 function g_Net_AbortResTransfer (var tf
: TNetFileTransfer
): Boolean;
251 function g_Net_ReceiveResourceFile (resIndex
: LongInt; var tf
: TNetFileTransfer
; strm
: TStream
): Integer;
253 function g_Net_IsNetworkAvailable (): Boolean;
254 procedure g_Net_InitLowLevel ();
255 procedure g_Net_DeinitLowLevel ();
257 procedure NetServerCVars(P
: SSArray
);
262 // *enet_host_service()*
263 // fuck! https://www.mail-archive.com/enet-discuss@cubik.org/msg00852.html
264 // tl;dr: on shitdows, we can get -1 sometimes, and it is *NOT* a failure.
265 // thank you, enet. let's ignore failures altogether then.
270 g_nethandler
, g_netmsg
, g_netmaster
, g_player
, g_window
, g_console
,
271 g_main
, g_game
, g_language
, g_weapons
, ctypes
, g_system
, g_map
;
274 FILE_CHUNK_SIZE
= 8192;
277 enet_init_success
: Boolean = false;
278 g_Net_DownloadTimeout
: Single;
282 function g_Net_IsNetworkAvailable (): Boolean;
284 result
:= enet_init_success
;
287 procedure g_Net_InitLowLevel ();
290 v
:= enet_linked_version();
291 e_LogWritefln('ENet Version: %s.%s.%s', [ENET_VERSION_GET_MAJOR(v
), ENET_VERSION_GET_MINOR(v
), ENET_VERSION_GET_PATCH(v
)]);
292 if enet_init_success
then raise Exception
.Create('wuta?!');
293 enet_init_success
:= (enet_initialize() = 0);
296 procedure g_Net_DeinitLowLevel ();
298 if enet_init_success
then
301 enet_init_success
:= false;
306 //**************************************************************************
310 //**************************************************************************
312 procedure clearNetClientTransfers (var nc
: TNetClient
);
314 nc
.Transfer
.stream
.Free
;
315 nc
.Transfer
.diskName
:= ''; // just in case
316 if (nc
.Transfer
.diskBuffer
<> nil) then FreeMem(nc
.Transfer
.diskBuffer
);
317 nc
.Transfer
.stream
:= nil;
318 nc
.Transfer
.diskBuffer
:= nil;
322 procedure clearNetClient (var nc
: TNetClient
);
324 clearNetClientTransfers(nc
);
328 procedure clearNetClients (clearArray
: Boolean);
332 for f
:= Low(NetClients
) to High(NetClients
) do clearNetClient(NetClients
[f
]);
333 if (clearArray
) then SetLength(NetClients
, 0);
337 function g_Net_UserRequestExit (): Boolean;
339 Result
:= {e_KeyPressed(IK_SPACE) or}
340 e_KeyPressed(IK_ESCAPE
) or
341 e_KeyPressed(VK_ESCAPE
) or
342 e_KeyPressed(JOY0_JUMP
) or
343 e_KeyPressed(JOY1_JUMP
) or
344 e_KeyPressed(JOY2_JUMP
) or
345 e_KeyPressed(JOY3_JUMP
)
348 //**************************************************************************
350 // file transfer declaraions and host packet processor
352 //**************************************************************************
355 // server packet type
356 NTF_SERVER_DONE
= 10; // done with this file
357 NTF_SERVER_FILE_INFO
= 11; // sent after client request
358 NTF_SERVER_CHUNK
= 12; // next chunk; chunk number follows
359 NTF_SERVER_ABORT
= 13; // server abort
360 NTF_SERVER_MAP_INFO
= 14;
362 // client packet type
363 NTF_CLIENT_MAP_REQUEST
= 100; // map file request; also, returns list of additional wads to download
364 NTF_CLIENT_FILE_REQUEST
= 101; // resource file request (by index)
365 NTF_CLIENT_ABORT
= 102; // do not send requested file, or abort current transfer
366 NTF_CLIENT_START
= 103; // start transfer; client may resume download by sending non-zero starting chunk
367 NTF_CLIENT_ACK
= 104; // chunk ack; chunk number follows
370 // disconnect client due to some file transfer error
371 procedure killClientByFT (var nc
: TNetClient
);
373 e_LogWritefln('disconnected client #%d due to file transfer error', [nc
.ID
], TMsgType
.Warning
);
374 enet_peer_disconnect(nc
.Peer
, NET_DISC_FILE_TIMEOUT
);
375 clearNetClientTransfers(nc
);
376 g_Net_Slist_ServerPlayerLeaves();
380 // send file transfer message from server to client
381 function ftransSendServerMsg (var nc
: TNetClient
; var m
: TMsg
): Boolean;
386 if (m
.CurSize
< 1) then exit
;
387 pkt
:= enet_packet_create(m
.Data
, m
.CurSize
, ENET_PACKET_FLAG_RELIABLE
);
388 if not Assigned(pkt
) then begin killClientByFT(nc
); exit
; end;
389 if (enet_peer_send(nc
.Peer
, NET_CHAN_DOWNLOAD_EX
, pkt
) <> 0) then begin killClientByFT(nc
); exit
; end;
394 // send file transfer message from client to server
395 function ftransSendClientMsg (var m
: TMsg
): Boolean;
400 if (m
.CurSize
< 1) then exit
;
401 pkt
:= enet_packet_create(m
.Data
, m
.CurSize
, ENET_PACKET_FLAG_RELIABLE
);
402 if not Assigned(pkt
) then exit
;
403 if (enet_peer_send(NetPeer
, NET_CHAN_DOWNLOAD_EX
, pkt
) <> 0) then exit
;
409 procedure ProcessChunkSend (var nc
: TNetClient
);
411 tf
: ^TNetFileTransfer
;
417 if (tf
.stream
= nil) then exit
;
419 // arbitrary timeout number
420 if (ct
-tf
.lastAckTime
>= 5000) then
425 // check if we need to send something
426 if (not tf
.inProgress
) then exit
; // waiting for the initial ack
427 // ok, we're sending chunks
428 if (tf
.lastAckChunk
<> tf
.lastSentChunk
) then exit
;
429 Inc(tf
.lastSentChunk
);
430 // do it one chunk at a time; client ack will advance our chunk counter
431 chunks
:= (tf
.size
+tf
.chunkSize
-1) div tf
.chunkSize
;
433 if (tf
.lastSentChunk
> chunks
) then
440 if (tf
.lastSentChunk
= chunks
) then
442 // we're done with this file
443 e_LogWritefln('download: client #%d, DONE sending chunks #%d/#%d', [nc
.ID
, tf
.lastSentChunk
, chunks
]);
444 trans_omsg
.Write(Byte(NTF_SERVER_DONE
));
445 clearNetClientTransfers(nc
);
450 trans_omsg
.Write(Byte(NTF_SERVER_CHUNK
));
451 trans_omsg
.Write(LongInt(tf
.lastSentChunk
));
453 rd
:= tf
.size
-(tf
.lastSentChunk
*tf
.chunkSize
);
454 if (rd
> tf
.chunkSize
) then rd
:= tf
.chunkSize
;
455 trans_omsg
.Write(LongInt(rd
));
456 //e_LogWritefln('download: client #%d, sending chunk #%d/#%d (%d bytes)', [nc.ID, tf.lastSentChunk, chunks, rd]);
457 //FIXME: check for errors here
459 tf
.stream
.Seek(tf
.lastSentChunk
*tf
.chunkSize
, soFromBeginning
);
460 tf
.stream
.ReadBuffer(tf
.diskBuffer
^, rd
);
461 trans_omsg
.WriteData(tf
.diskBuffer
, rd
);
468 ftransSendServerMsg(nc
, trans_omsg
);
472 // server file transfer packet processor
473 // received packet is in `NetEvent`
474 procedure ProcessDownloadExPacket ();
481 tf
: ^TNetFileTransfer
;
491 // find client index by peer
492 for f
:= Low(NetClients
) to High(NetClients
) do
494 if (not NetClients
[f
].Used
) then continue
;
495 if (NetClients
[f
].Peer
= NetEvent
.peer
) then
501 //e_LogWritefln('RECEIVE: dlpacket; client=%d (datalen=%u)', [nid, NetEvent.packet^.dataLength]);
503 if (nid
< 0) then exit
; // wtf?!
504 nc
:= @NetClients
[nid
];
506 if (NetEvent
.packet
^.dataLength
= 0) then
512 // don't time out clients during a file transfer
513 if (NetAuthTimeout
> 0) then
514 nc
^.AuthTime
:= gTime
+ NetAuthTimeout
;
515 if (NetPacketTimeout
> 0) then
516 nc
^.MsgTime
:= gTime
+ NetPacketTimeout
;
518 tf
:= @NetClients
[nid
].Transfer
;
519 tf
.lastAckTime
:= GetTimerMS();
521 cmd
:= Byte(NetEvent
.packet
^.data
^);
522 //e_LogWritefln('RECEIVE: nid=%d; cmd=%u', [nid, cmd]);
524 NTF_CLIENT_FILE_REQUEST
: // file request
526 if (tf
.stream
<> nil) then
531 if (NetEvent
.packet
^.dataLength
< 2) then
536 // new transfer request; build packet
537 if not msg
.Init(NetEvent
.packet
^.data
+1, NetEvent
.packet
^.dataLength
-1, True) then
542 // get resource index
543 ridx
:= msg
.ReadLongInt();
544 if (ridx
< -1) or (ridx
>= length(gExternalResources
)) then
546 e_LogWritefln('Invalid resource index %d', [ridx
], TMsgType
.Warning
);
550 if (ridx
< 0) then fname
:= gGameSettings
.WAD
else fname
:= gExternalResources
[ridx
].diskName
;
551 if (length(fname
) = 0) then
553 e_WriteLog('Invalid filename: '+fname
, TMsgType
.Warning
);
557 tf
.diskName
:= findDiskWad(fname
);
558 if (length(tf
.diskName
) = 0) then
560 e_LogWritefln('NETWORK: file "%s" not found!', [fname
], TMsgType
.Fatal
);
565 //tf.hash := MD5File(tf.diskName);
566 if (ridx
< 0) then tf
.hash
:= gWADHash
else tf
.hash
:= gExternalResources
[ridx
].hash
;
567 // create file stream
568 tf
.diskName
:= findDiskWad(fname
);
570 tf
.stream
:= openDiskFileRO(tf
.diskName
);
574 if (tf
.stream
= nil) then
576 e_WriteLog(Format('NETWORK: file "%s" not found!', [fname
]), TMsgType
.Fatal
);
580 e_LogWritefln('client #%d requested resource #%d (file is `%s` : `%s`)', [nc
.ID
, ridx
, fname
, tf
.diskName
]);
581 tf
.size
:= tf
.stream
.size
;
582 tf
.chunkSize
:= FILE_CHUNK_SIZE
; // arbitrary
583 tf
.lastSentChunk
:= -1;
584 tf
.lastAckChunk
:= -1;
585 tf
.lastAckTime
:= GetTimerMS();
586 tf
.inProgress
:= False; // waiting for the first ACK or for the cancel
587 GetMem(tf
.diskBuffer
, tf
.chunkSize
);
588 // sent file info message
590 trans_omsg
.Write(Byte(NTF_SERVER_FILE_INFO
));
591 trans_omsg
.Write(tf
.hash
);
592 trans_omsg
.Write(tf
.size
);
593 trans_omsg
.Write(tf
.chunkSize
);
594 trans_omsg
.Write(ExtractFileName(fname
));
595 if not ftransSendServerMsg(nc
^, trans_omsg
) then exit
;
597 NTF_CLIENT_ABORT
: // do not send requested file, or abort current transfer
599 e_LogWritefln('client #%d aborted file transfer', [nc
.ID
]);
600 clearNetClientTransfers(nc
^);
602 NTF_CLIENT_START
: // start transfer; client may resume download by sending non-zero starting chunk
604 if not Assigned(tf
.stream
) then
609 if (tf
.lastSentChunk
<> -1) or (tf
.lastAckChunk
<> -1) or (tf
.inProgress
) then
611 // double ack, get lost
615 if (NetEvent
.packet
^.dataLength
< 2) then
621 if not msg
.Init(NetEvent
.packet
^.data
+1, NetEvent
.packet
^.dataLength
-1, True) then
626 chunk
:= msg
.ReadLongInt();
627 if (chunk
< 0) or (chunk
> (tf
.size
+tf
.chunkSize
-1) div tf
.chunkSize
) then
632 e_LogWritefln('client #%d started file transfer from chunk %d', [nc
.ID
, chunk
]);
633 // start sending chunks
634 tf
.inProgress
:= True;
635 tf
.lastSentChunk
:= chunk
-1;
636 tf
.lastAckChunk
:= chunk
-1;
637 ProcessChunkSend(nc
^);
639 NTF_CLIENT_ACK
: // chunk ack; chunk number follows
641 if not Assigned(tf
.stream
) then
646 if (tf
.lastSentChunk
< 0) or (not tf
.inProgress
) then
648 // double ack, get lost
652 if (NetEvent
.packet
^.dataLength
< 2) then
658 if not msg
.Init(NetEvent
.packet
^.data
+1, NetEvent
.packet
^.dataLength
-1, True) then
663 chunk
:= msg
.ReadLongInt();
664 if (chunk
< 0) or (chunk
> (tf
.size
+tf
.chunkSize
-1) div tf
.chunkSize
) then
669 // do it this way, so client may seek, or request retransfers for some reason
670 tf
.lastAckChunk
:= chunk
;
671 tf
.lastSentChunk
:= chunk
;
672 //e_LogWritefln('client #%d acked file transfer chunk %d', [nc.ID, chunk]);
673 ProcessChunkSend(nc
^);
675 NTF_CLIENT_MAP_REQUEST
:
677 e_LogWritefln('client #%d requested map info', [nc
.ID
]);
679 dfn
:= findDiskWad(gGameSettings
.WAD
);
680 if (dfn
= '') then dfn
:= '!wad_not_found!.wad'; //FIXME
681 //md5 := MD5File(dfn);
683 if (not GetDiskFileInfo(dfn
, fi
)) then
685 e_LogWritefln('client #%d requested map info, but i cannot get file info', [nc
.ID
]);
691 st := openDiskFileRO(dfn);
692 if not assigned(st) then exit; //wtf?!
697 trans_omsg
.Write(Byte(NTF_SERVER_MAP_INFO
));
699 trans_omsg
.Write(ExtractFileName(gGameSettings
.WAD
));
701 trans_omsg
.Write(md5
);
703 trans_omsg
.Write(size
);
704 // number of external resources for map
705 trans_omsg
.Write(LongInt(length(gExternalResources
)));
706 // external resource names
707 for f
:= 0 to High(gExternalResources
) do
710 //trans_omsg.Write(ExtractFileName(gExternalResources[f])); // GameDir+'/wads/'+ResList.Strings[i]
712 trans_omsg
.Write('!');
713 trans_omsg
.Write(LongInt(gExternalResources
[f
].size
));
714 trans_omsg
.Write(gExternalResources
[f
].hash
);
715 trans_omsg
.Write(ExtractFileName(gExternalResources
[f
].diskName
));
718 if not ftransSendServerMsg(nc
^, trans_omsg
) then exit
;
729 //**************************************************************************
731 // file transfer crap (both client and server)
733 //**************************************************************************
735 function getNewTimeoutEnd (): Int64;
737 result
:= GetTimerMS();
738 if (g_Net_DownloadTimeout
<= 0) then
740 result
:= result
+1000*60*3; // 3 minutes
744 result
:= result
+trunc(g_Net_DownloadTimeout
*1000);
749 // send map request to server, and wait for "map info" server reply
751 // returns `false` on error or user abort
753 // diskName: map wad file name (without a path)
754 // hash: map wad hash
755 // size: map wad size
756 // chunkSize: set too
757 // resList: list of resource wads
763 // for maps, first `tf.diskName` name will be map wad name, and `tf.hash`/`tf.size` will contain map info
764 function g_Net_Wait_MapInfo (var tf
: TNetFileTransfer
; var resList
: TNetMapResourceInfoArray
): Integer;
770 freePacket
: Boolean = false;
775 ri
: ^TNetMapResourceInfo
;
777 SetLength(resList
, 0);
781 trans_omsg
.Write(Byte(NTF_CLIENT_MAP_REQUEST
));
782 if not ftransSendClientMsg(trans_omsg
) then begin result
:= -1; exit
; end;
784 FillChar(ev
, SizeOf(ev
), 0);
787 ett
:= getNewTimeoutEnd();
789 status
:= enet_host_service(NetHost
, @ev
, 300);
793 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' network error', True);
798 if (status
<= 0) then
804 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' timeout reached', True);
813 ENET_EVENT_TYPE_RECEIVE
:
816 if (ev
.channelID
<> NET_CHAN_DOWNLOAD_EX
) then
818 //e_LogWritefln('g_Net_Wait_MapInfo: skip message from non-transfer channel', []);
820 g_Net_Client_HandlePacket(ev
.packet
, g_Net_ClientLightMsgHandler
);
821 if (g_Res_received_map_start
< 0) then begin result
:= -666; exit
; end;
825 ett
:= getNewTimeoutEnd();
826 if (ev
.packet
.dataLength
< 1) then
828 e_LogWritefln('g_Net_Wait_MapInfo: invalid server packet (no data)', []);
832 Ptr
:= ev
.packet
^.data
;
833 rMsgId
:= Byte(Ptr
^);
834 e_LogWritefln('g_Net_Wait_MapInfo: got message %u from server (dataLength=%u)', [rMsgId
, ev
.packet
^.dataLength
]);
835 if (rMsgId
= NTF_SERVER_FILE_INFO
) then
837 e_LogWritefln('g_Net_Wait_MapInfo: waiting for map info reply, but got file info reply', []);
841 else if (rMsgId
= NTF_SERVER_ABORT
) then
843 e_LogWritefln('g_Net_Wait_MapInfo: server aborted transfer', []);
847 else if (rMsgId
= NTF_SERVER_MAP_INFO
) then
849 e_LogWritefln('g_Net_Wait_MapInfo: creating map info packet...', []);
850 if not msg
.Init(ev
.packet
^.data
+1, ev
.packet
^.dataLength
-1, True) then exit
;
851 e_LogWritefln('g_Net_Wait_MapInfo: parsing map info packet (rd=%d; max=%d)...', [msg
.ReadCount
, msg
.MaxSize
]);
852 SetLength(resList
, 0); // just in case
854 tf
.diskName
:= msg
.ReadString();
855 e_LogWritefln('g_Net_Wait_MapInfo: map wad is `%s`', [tf
.diskName
]);
857 tf
.hash
:= msg
.ReadMD5();
859 tf
.size
:= msg
.ReadLongInt();
860 e_LogWritefln('g_Net_Wait_MapInfo: map wad size is %d', [tf
.size
]);
861 // number of external resources for map
862 rc
:= msg
.ReadLongInt();
863 if (rc
< 0) or (rc
> 1024) then
865 e_LogWritefln('g_Net_Wait_Event: invalid number of map external resources (%d)', [rc
]);
869 e_LogWritefln('g_Net_Wait_MapInfo: map external resource count is %d', [rc
]);
870 SetLength(resList
, rc
);
871 // external resource names
872 for f
:= 0 to rc
-1 do
875 s
:= msg
.ReadString();
876 if (length(s
) = 0) then begin result
:= -1; exit
; end;
880 ri
.size
:= msg
.ReadLongInt();
881 ri
.hash
:= msg
.ReadMD5();
882 ri
.wadName
:= ExtractFileName(msg
.ReadString());
883 if (length(ri
.wadName
) = 0) or (ri
.size
< 0) then begin result
:= -1; exit
; end;
887 // old-style packet, only name
888 ri
.wadName
:= ExtractFileName(s
);
889 if (length(ri
.wadName
) = 0) then begin result
:= -1; exit
; end;
890 ri
.size
:= -1; // unknown
893 e_LogWritefln('g_Net_Wait_MapInfo: got map info', []);
894 Result
:= 0; // success
899 e_LogWritefln('g_Net_Wait_Event: invalid server packet type', []);
905 ENET_EVENT_TYPE_DISCONNECT
:
907 if (ev
.data
<= NET_DISC_MAX
) then
908 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' ' + _lc
[TStrings_Locale(Cardinal(I_NET_DISC_NONE
) + ev
.data
)], True);
914 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' unknown ENet event ' + IntToStr(Ord(ev
.kind
)), True);
919 if (freePacket
) then begin freePacket
:= false; enet_packet_destroy(ev
.packet
); end;
922 if g_Net_UserRequestExit() then
924 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' user abort', True);
930 if (freePacket
) then enet_packet_destroy(ev
.packet
);
935 // send file request to server, and wait for server reply
937 // returns `false` on error or user abort
939 // diskName (actually, base name)
948 // for maps, first `tf.diskName` name will be map wad name, and `tf.hash`/`tf.size` will contain map info
949 function g_Net_RequestResFileInfo (resIndex
: LongInt; out tf
: TNetFileTransfer
): Integer;
955 freePacket
: Boolean = false;
961 trans_omsg
.Write(Byte(NTF_CLIENT_FILE_REQUEST
));
962 trans_omsg
.Write(resIndex
);
963 if not ftransSendClientMsg(trans_omsg
) then begin result
:= -1; exit
; end;
965 FillChar(ev
, SizeOf(ev
), 0);
968 ett
:= getNewTimeoutEnd();
970 status
:= enet_host_service(NetHost
, @ev
, 300);
974 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' network error', True);
979 if (status
<= 0) then
985 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' timeout reached', True);
994 ENET_EVENT_TYPE_RECEIVE
:
997 if (ev
.channelID
<> NET_CHAN_DOWNLOAD_EX
) then
999 //e_LogWriteln('g_Net_Wait_Event: skip message from non-transfer channel');
1000 freePacket
:= false;
1001 g_Net_Client_HandlePacket(ev
.packet
, g_Net_ClientLightMsgHandler
);
1002 if (g_Res_received_map_start
< 0) then begin result
:= -666; exit
; end;
1006 ett
:= getNewTimeoutEnd();
1007 if (ev
.packet
.dataLength
< 1) then
1009 e_LogWriteln('g_Net_Wait_Event: invalid server packet (no data)');
1013 Ptr
:= ev
.packet
^.data
;
1014 rMsgId
:= Byte(Ptr
^);
1015 e_LogWritefln('received transfer packet with id %d (%u bytes)', [rMsgId
, ev
.packet
^.dataLength
]);
1016 if (rMsgId
= NTF_SERVER_FILE_INFO
) then
1018 if not msg
.Init(ev
.packet
^.data
+1, ev
.packet
^.dataLength
-1, True) then exit
;
1019 tf
.hash
:= msg
.ReadMD5();
1020 tf
.size
:= msg
.ReadLongInt();
1021 tf
.chunkSize
:= msg
.ReadLongInt();
1022 tf
.diskName
:= ExtractFileName(msg
.readString());
1023 if (tf
.size
< 0) or (tf
.chunkSize
<> FILE_CHUNK_SIZE
) or (length(tf
.diskName
) = 0) then
1025 e_LogWritefln('g_Net_RequestResFileInfo: invalid file info packet', []);
1029 e_LogWritefln('got file info for resource #%d: size=%d; name=%s', [resIndex
, tf
.size
, tf
.diskName
]);
1030 Result
:= 0; // success
1033 else if (rMsgId
= NTF_SERVER_ABORT
) then
1035 e_LogWriteln('g_Net_RequestResFileInfo: server aborted transfer');
1039 else if (rMsgId
= NTF_SERVER_MAP_INFO
) then
1041 e_LogWriteln('g_Net_RequestResFileInfo: waiting for map info reply, but got file info reply');
1047 e_LogWriteln('g_Net_RequestResFileInfo: invalid server packet type');
1053 ENET_EVENT_TYPE_DISCONNECT
:
1055 if (ev
.data
<= NET_DISC_MAX
) then
1056 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' ' + _lc
[TStrings_Locale(Cardinal(I_NET_DISC_NONE
) + ev
.data
)], True);
1062 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' unknown ENet event ' + IntToStr(Ord(ev
.kind
)), True);
1067 if (freePacket
) then begin freePacket
:= false; enet_packet_destroy(ev
.packet
); end;
1070 if g_Net_UserRequestExit() then
1072 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' user abort', True);
1078 if (freePacket
) then enet_packet_destroy(ev
.packet
);
1083 // call this to cancel file transfer requested by `g_Net_RequestResFileInfo()`
1084 function g_Net_AbortResTransfer (var tf
: TNetFileTransfer
): Boolean;
1087 e_LogWritefln('aborting file transfer...', []);
1090 trans_omsg
.Write(Byte(NTF_CLIENT_ABORT
));
1091 result
:= ftransSendClientMsg(trans_omsg
);
1092 if result
then enet_host_flush(NetHost
);
1096 // call this to start file transfer requested by `g_Net_RequestResFileInfo()`
1098 // returns `false` on error or user abort
1107 // 2 on server abort
1108 // for maps, first `tf.diskName` name will be map wad name, and `tf.hash`/`tf.size` will contain map info
1109 function g_Net_ReceiveResourceFile (resIndex
: LongInt; var tf
: TNetFileTransfer
; strm
: TStream
): Integer;
1115 freePacket
: Boolean = false;
1118 nextChunk
: Integer = 0;
1119 chunkTotal
: Integer;
1126 tf
.resumed
:= false;
1127 e_LogWritefln('file `%s`, size=%d (%d)', [tf
.diskName
, Integer(strm
.size
), tf
.size
], TMsgType
.Notify
);
1128 // check if we should resume downloading
1129 resumed
:= (strm
.size
> tf
.chunkSize
) and (strm
.size
< tf
.size
);
1132 trans_omsg
.Write(Byte(NTF_CLIENT_START
));
1133 if resumed
then chunk
:= strm
.size
div tf
.chunkSize
else chunk
:= 0;
1134 trans_omsg
.Write(LongInt(chunk
));
1135 if not ftransSendClientMsg(trans_omsg
) then begin result
:= -1; exit
; end;
1137 strm
.Seek(chunk
*tf
.chunkSize
, soFromBeginning
);
1138 chunkTotal
:= (tf
.size
+tf
.chunkSize
-1) div tf
.chunkSize
;
1139 e_LogWritefln('receiving file `%s` (%d chunks)', [tf
.diskName
, chunkTotal
], TMsgType
.Notify
);
1140 g_Game_SetLoadingText('downloading "'+ExtractFileName(tf
.diskName
)+'"', chunkTotal
, False);
1141 tf
.resumed
:= resumed
;
1143 if (chunk
> 0) then g_Game_StepLoading(chunk
);
1146 // wait for reply data
1147 FillChar(ev
, SizeOf(ev
), 0);
1149 GetMem(buf
, tf
.chunkSize
);
1151 ett
:= getNewTimeoutEnd();
1153 //stx := -GetTimerMS();
1154 status
:= enet_host_service(NetHost
, @ev
, 300);
1156 if (status < 0) then
1158 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' network error', True);
1163 if (status
<= 0) then
1165 // check for timeout
1169 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' timeout reached', True);
1178 ENET_EVENT_TYPE_RECEIVE
:
1181 if (ev
.channelID
<> NET_CHAN_DOWNLOAD_EX
) then
1183 //e_LogWritefln('g_Net_Wait_Event: skip message from non-transfer channel', []);
1184 freePacket
:= false;
1185 g_Net_Client_HandlePacket(ev
.packet
, g_Net_ClientLightMsgHandler
);
1186 if (g_Res_received_map_start
< 0) then begin result
:= -666; exit
; end;
1190 //stx := stx+GetTimerMS();
1191 //e_LogWritefln('g_Net_ReceiveResourceFile: stx=%d', [Integer(stx)]);
1192 //stx := -GetTimerMS();
1193 ett
:= getNewTimeoutEnd();
1194 if (ev
.packet
.dataLength
< 1) then
1196 e_LogWritefln('g_Net_ReceiveResourceFile: invalid server packet (no data)', []);
1200 Ptr
:= ev
.packet
^.data
;
1201 rMsgId
:= Byte(Ptr
^);
1202 if (rMsgId
= NTF_SERVER_DONE
) then
1204 e_LogWritefln('file transfer complete.', []);
1208 else if (rMsgId
= NTF_SERVER_CHUNK
) then
1210 if not msg
.Init(ev
.packet
^.data
+1, ev
.packet
^.dataLength
-1, True) then exit
;
1211 chunk
:= msg
.ReadLongInt();
1212 csize
:= msg
.ReadLongInt();
1213 if (chunk
<> nextChunk
) then
1215 e_LogWritefln('received chunk %d, but expected chunk %d', [chunk
, nextChunk
]);
1219 if (csize
< 0) or (csize
> tf
.chunkSize
) then
1221 e_LogWritefln('received chunk with size %d, but expected chunk size is %d', [csize
, tf
.chunkSize
]);
1225 //e_LogWritefln('got chunk #%d of #%d (csize=%d)', [chunk, (tf.size+tf.chunkSize-1) div tf.chunkSize, csize]);
1226 msg
.ReadData(buf
, csize
);
1227 strm
.WriteBuffer(buf
^, csize
);
1228 nextChunk
:= chunk
+1;
1229 g_Game_StepLoading();
1232 trans_omsg
.Write(Byte(NTF_CLIENT_ACK
));
1233 trans_omsg
.Write(LongInt(chunk
));
1234 if not ftransSendClientMsg(trans_omsg
) then begin result
:= -1; exit
; end;
1236 else if (rMsgId
= NTF_SERVER_ABORT
) then
1238 e_LogWritefln('g_Net_ReceiveResourceFile: server aborted transfer', []);
1244 e_LogWritefln('g_Net_ReceiveResourceFile: invalid server packet type', []);
1248 //stx := stx+GetTimerMS();
1249 //e_LogWritefln('g_Net_ReceiveResourceFile: process stx=%d', [Integer(stx)]);
1252 ENET_EVENT_TYPE_DISCONNECT
:
1254 if (ev
.data
<= NET_DISC_MAX
) then
1255 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' ' + _lc
[TStrings_Locale(Cardinal(I_NET_DISC_NONE
) + ev
.data
)], True);
1261 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' unknown ENet event ' + IntToStr(Ord(ev
.kind
)), True);
1266 if (freePacket
) then begin freePacket
:= false; enet_packet_destroy(ev
.packet
); end;
1269 if g_Net_UserRequestExit() then
1271 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' user abort', True);
1278 if (freePacket
) then enet_packet_destroy(ev
.packet
);
1283 //**************************************************************************
1287 //**************************************************************************
1289 function g_Net_FindSlot(): Integer;
1298 for I
:= Low(NetClients
) to High(NetClients
) do
1300 if NetClients
[I
].Used
then
1309 if C
>= NetMaxClients
then
1317 if (Length(NetClients
) >= NetMaxClients
) then
1321 SetLength(NetClients
, Length(NetClients
) + 1);
1322 N
:= High(NetClients
);
1328 NetClients
[N
].Used
:= True;
1329 NetClients
[N
].ID
:= N
;
1330 NetClients
[N
].RequestedFullUpdate
:= False;
1331 NetClients
[N
].WaitForFirstSpawn
:= False;
1332 NetClients
[N
].RCONAuth
:= False;
1333 NetClients
[N
].Voted
:= False;
1334 NetClients
[N
].Player
:= 0;
1335 clearNetClientTransfers(NetClients
[N
]); // just in case
1342 function g_Net_Init(): Boolean;
1351 NetBuf
[NET_UNRELIABLE
].Clear();
1352 NetBuf
[NET_RELIABLE
].Clear();
1353 //SetLength(NetClients, 0);
1354 clearNetClients(true); // clear array
1360 NetAddr
.port
:= 25666;
1361 SetLength(NetBannedHosts
, 0);
1362 path
:= BANLIST_FILENAME
;
1363 if e_FindResource(DataDirs
, path
) = true then
1370 if StrToIp(IPstr
, IP
) then
1374 g_Net_SaveBanList();
1377 //Result := (enet_initialize() = 0);
1378 Result
:= enet_init_success
;
1381 procedure g_Net_Flush();
1385 F
, Chan
: enet_uint32
;
1389 Chan
:= NET_CHAN_GAME
;
1391 if NetMode
= NET_SERVER
then
1392 for T
:= NET_UNRELIABLE
to NET_RELIABLE
do
1394 if NetBuf
[T
].CurSize
> 0 then
1396 P
:= enet_packet_create(NetBuf
[T
].Data
, NetBuf
[T
].CurSize
, F
);
1397 if not Assigned(P
) then continue
;
1398 enet_host_broadcast(NetHost
, Chan
, P
);
1402 for I
:= Low(NetClients
) to High(NetClients
) do
1404 if not NetClients
[I
].Used
then continue
;
1405 if NetClients
[I
].NetOut
[T
].CurSize
<= 0 then continue
;
1406 P
:= enet_packet_create(NetClients
[I
].NetOut
[T
].Data
, NetClients
[I
].NetOut
[T
].CurSize
, F
);
1407 if not Assigned(P
) then continue
;
1408 enet_peer_send(NetClients
[I
].Peer
, Chan
, P
);
1409 NetClients
[I
].NetOut
[T
].Clear();
1412 // next and last iteration is always RELIABLE
1413 F
:= LongWord(ENET_PACKET_FLAG_RELIABLE
);
1414 Chan
:= NET_CHAN_IMPORTANT
;
1416 else if NetMode
= NET_CLIENT
then
1417 for T
:= NET_UNRELIABLE
to NET_RELIABLE
do
1419 if NetBuf
[T
].CurSize
> 0 then
1421 P
:= enet_packet_create(NetBuf
[T
].Data
, NetBuf
[T
].CurSize
, F
);
1422 if not Assigned(P
) then continue
;
1423 enet_peer_send(NetPeer
, Chan
, P
);
1426 // next and last iteration is always RELIABLE
1427 F
:= LongWord(ENET_PACKET_FLAG_RELIABLE
);
1428 Chan
:= NET_CHAN_IMPORTANT
;
1432 procedure g_Net_Cleanup();
1436 NetBuf
[NET_UNRELIABLE
].Clear();
1437 NetBuf
[NET_RELIABLE
].Clear();
1439 //SetLength(NetClients, 0);
1440 clearNetClients(true); // clear array
1441 NetClientCount
:= 0;
1445 g_Net_Slist_ServerClosed();
1449 NetState
:= NET_STATE_NONE
;
1451 NetPongSock
:= ENET_SOCKET_NULL
;
1453 NetTimeToMaster
:= 0;
1454 NetTimeToUpdate
:= 0;
1455 NetTimeToReliable
:= 0;
1457 NetMode
:= NET_NONE
;
1459 if NetPortThread
<> NilThreadId
then
1460 WaitForThreadTerminate(NetPortThread
, 66666);
1462 NetPortThread
:= NilThreadId
;
1463 g_Net_UnforwardPorts();
1469 procedure g_Net_Free();
1473 //enet_deinitialize();
1474 NetInitDone
:= False;
1478 //**************************************************************************
1482 //**************************************************************************
1484 function ForwardThread(Param
: Pointer): PtrInt
;
1487 if not g_Net_ForwardPorts() then Result
:= -1;
1490 function g_Net_Host(IPAddr
: LongWord; Port
: enet_uint16
; MaxClients
: Cardinal = 16): Boolean;
1492 if NetMode
<> NET_NONE
then
1494 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_INGAME
]);
1501 g_Console_Add(_lc
[I_NET_MSG
] + Format(_lc
[I_NET_MSG_HOST
], [Port
]));
1502 if not NetInitDone
then
1504 if (not g_Net_Init()) then
1506 g_Console_Add(_lc
[I_NET_MSG_FERROR
] + _lc
[I_NET_ERR_ENET
]);
1511 NetInitDone
:= True;
1514 NetAddr
.host
:= IPAddr
;
1515 NetAddr
.port
:= Port
;
1517 NetHost
:= enet_host_create(@NetAddr
, NET_MAXCLIENTS
, NET_CHANS
, 0, 0);
1519 if (NetHost
= nil) then
1521 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + Format(_lc
[I_NET_ERR_HOST
], [Port
]));
1527 if NetForwardPorts
then NetPortThread
:= BeginThread(ForwardThread
);
1529 NetPongSock
:= enet_socket_create(ENET_SOCKET_TYPE_DATAGRAM
);
1530 if NetPongSock
<> ENET_SOCKET_NULL
then
1532 NetPongAddr
.host
:= IPAddr
;
1533 NetPongAddr
.port
:= NET_PING_PORT
;
1534 if enet_socket_bind(NetPongSock
, @NetPongAddr
) < 0 then
1536 enet_socket_destroy(NetPongSock
);
1537 NetPongSock
:= ENET_SOCKET_NULL
;
1540 enet_socket_set_option(NetPongSock
, ENET_SOCKOPT_NONBLOCK
, 1);
1543 NetMode
:= NET_SERVER
;
1545 NetBuf
[NET_UNRELIABLE
].Clear();
1546 NetBuf
[NET_RELIABLE
].Clear();
1552 procedure g_Net_Host_Die();
1556 if NetMode
<> NET_SERVER
then Exit
;
1558 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_HOST_DISCALL
]);
1559 for I
:= 0 to High(NetClients
) do
1560 if NetClients
[I
].Used
then
1561 enet_peer_disconnect(NetClients
[I
].Peer
, NET_DISC_DOWN
);
1563 while enet_host_service(NetHost
, @NetEvent
, 1000) > 0 do
1564 if NetEvent
.kind
= ENET_EVENT_TYPE_RECEIVE
then
1565 enet_packet_destroy(NetEvent
.packet
);
1567 for I
:= 0 to High(NetClients
) do
1568 if NetClients
[I
].Used
then
1570 FreeMemory(NetClients
[I
].Peer
^.data
);
1571 NetClients
[I
].Peer
^.data
:= nil;
1572 enet_peer_reset(NetClients
[I
].Peer
);
1573 NetClients
[I
].Peer
:= nil;
1574 NetClients
[I
].Used
:= False;
1575 NetClients
[I
].Player
:= 0;
1576 NetClients
[I
].Crimes
:= 0;
1577 NetClients
[I
].AuthTime
:= 0;
1578 NetClients
[I
].MsgTime
:= 0;
1579 NetClients
[I
].NetOut
[NET_UNRELIABLE
].Free();
1580 NetClients
[I
].NetOut
[NET_RELIABLE
].Free();
1583 clearNetClients(false); // don't clear array
1584 g_Net_Slist_ServerClosed();
1585 if NetPongSock
<> ENET_SOCKET_NULL
then
1586 enet_socket_destroy(NetPongSock
);
1588 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_HOST_DIE
]);
1589 enet_host_destroy(NetHost
);
1591 NetMode
:= NET_NONE
;
1594 e_WriteLog('NET: Server stopped', TMsgType
.Notify
);
1598 procedure g_Net_Host_Send(ID
: Integer; Reliable
: Boolean; Chan
: Byte = NET_CHAN_GAME
);
1605 T
:= NET_UNRELIABLE
;
1609 if ID
> High(NetClients
) then Exit
;
1610 if NetClients
[ID
].Peer
= nil then Exit
;
1612 NetClients
[ID
].NetOut
[T
].Write(Integer(NetOut
.CurSize
));
1613 NetClients
[ID
].NetOut
[T
].Write(NetOut
);
1618 NetBuf
[T
].Write(Integer(NetOut
.CurSize
));
1619 NetBuf
[T
].Write(NetOut
);
1622 if NetDump
then g_Net_DumpSendBuffer();
1626 procedure g_Net_Host_CheckPings();
1628 ClAddr
: ENetAddress
;
1632 Ping
: array [0..9] of Byte;
1635 if (NetPongSock
= ENET_SOCKET_NULL
) or (NetHost
= nil) then Exit
;
1637 Buf
.data
:= Addr(Ping
[0]);
1638 Buf
.dataLength
:= 2+8;
1642 Len
:= enet_socket_receive(NetPongSock
, @ClAddr
, @Buf
, 1);
1643 if Len
< 0 then Exit
;
1645 if (Ping
[0] = Ord('D')) and (Ping
[1] = Ord('F')) then
1647 ClTime
:= Int64(Addr(Ping
[2])^);
1650 NetOut
.Write(Byte(Ord('D')));
1651 NetOut
.Write(Byte(Ord('F')));
1652 NetOut
.Write(NetHost
.address
.port
);
1653 NetOut
.Write(ClTime
);
1654 TMasterHost
.writeInfo(NetOut
);
1656 if gPlayer1
<> nil then Inc(NPl
);
1657 if gPlayer2
<> nil then Inc(NPl
);
1659 NetOut
.Write(gNumBots
);
1661 Buf
.data
:= NetOut
.Data
;
1662 Buf
.dataLength
:= NetOut
.CurSize
;
1663 enet_socket_send(NetPongSock
, @ClAddr
, @Buf
, 1);
1669 procedure g_Net_Host_CheckTimeouts();
1673 for ID
:= Low(NetClients
) to High(NetClients
) do
1675 with NetClients
[ID
] do
1677 if (Peer
= nil) or (State
= NET_STATE_NONE
) then continue
;
1678 if (State
= NET_STATE_AUTH
) and (AuthTime
> 0) and (AuthTime
<= gTime
) then
1680 g_Net_Penalize(@NetClients
[ID
], 'auth taking too long');
1681 AuthTime
:= gTime
+ 500; // do it twice a second to give them a chance
1683 else if (State
= NET_STATE_GAME
) and (MsgTime
> 0) and (MsgTime
<= gTime
) then
1685 g_Net_Penalize(@NetClients
[ID
], 'message timeout');
1686 AuthTime
:= gTime
+ 500; // do it twice a second to give them a chance
1692 procedure g_Net_Host_Disconnect_Client(ID
: Integer; Force
: Boolean = False);
1697 TC
:= @NetClients
[ID
];
1698 if (TC
= nil) then Exit
;
1699 clearNetClient(NetClients
[ID
]);
1700 if not (TC
^.Used
) then Exit
;
1702 TP
:= g_Player_Get(TC
^.Player
);
1707 TP
.Kill(K_SIMPLEKILL
, 0, HIT_DISCON
);
1708 g_Console_Add(Format(_lc
[I_PLAYER_LEAVE
], [TP
.Name
]), True);
1709 e_WriteLog('NET: Client ' + TP
.Name
+ ' [' + IntToStr(TC
^.ID
) + '] disconnected.', TMsgType
.Notify
);
1710 g_Player_Remove(TP
.UID
);
1713 if (TC
^.Peer
^.data
<> nil) then
1715 FreeMemory(TC
^.Peer
^.data
);
1716 TC
^.Peer
^.data
:= nil;
1720 enet_peer_reset(TC
^.Peer
);
1723 TC
^.State
:= NET_STATE_NONE
;
1729 TC
^.RequestedFullUpdate
:= False;
1730 TC
^.WaitForFirstSpawn
:= False;
1731 TC
^.NetOut
[NET_UNRELIABLE
].Free();
1732 TC
^.NetOut
[NET_RELIABLE
].Free();
1734 g_Console_Add(_lc
[I_NET_MSG
] + Format(_lc
[I_NET_MSG_HOST_DISC
], [ID
]));
1735 Dec(NetClientCount
);
1737 if NetUseMaster
then g_Net_Slist_ServerPlayerLeaves();
1741 function g_Net_Host_Update(): enet_size_t
;
1751 if NetUseMaster
then g_Net_Slist_Pulse();
1752 g_Net_Host_CheckPings();
1753 g_Net_Host_CheckTimeouts();
1755 while (enet_host_service(NetHost
, @NetEvent
, 0) > 0) do
1757 case (NetEvent
.kind
) of
1758 ENET_EVENT_TYPE_CONNECT
:
1760 IP
:= IpToStr(NetEvent
.Peer
^.address
.host
);
1761 Port
:= NetEvent
.Peer
^.address
.port
;
1762 g_Console_Add(_lc
[I_NET_MSG
] +
1763 Format(_lc
[I_NET_MSG_HOST_CONN
], [IP
, Port
]));
1764 e_WriteLog('NET: Connection request from ' + IP
+ '.', TMsgType
.Notify
);
1766 if (NetEvent
.data
<> NET_PROTOCOL_VER
) then
1768 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_HOST_REJECT
] +
1769 _lc
[I_NET_DISC_PROTOCOL
]);
1770 e_WriteLog('NET: Connection request from ' + IP
+ ' rejected: version mismatch',
1772 NetEvent
.peer
^.data
:= GetMemory(SizeOf(Byte));
1773 Byte(NetEvent
.peer
^.data
^) := 255;
1774 enet_peer_disconnect(NetEvent
.peer
, NET_DISC_PROTOCOL
);
1775 enet_host_flush(NetHost
);
1779 if g_Net_IsHostBanned(NetEvent
.Peer
^.address
.host
) then
1781 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_HOST_REJECT
] +
1782 _lc
[I_NET_DISC_BAN
]);
1783 e_WriteLog('NET: Connection request from ' + IP
+ ' rejected: banned',
1785 NetEvent
.peer
^.data
:= GetMemory(SizeOf(Byte));
1786 Byte(NetEvent
.peer
^.data
^) := 255;
1787 enet_peer_disconnect(NetEvent
.Peer
, NET_DISC_BAN
);
1788 enet_host_flush(NetHost
);
1792 ID
:= g_Net_FindSlot();
1796 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_HOST_REJECT
] +
1797 _lc
[I_NET_DISC_FULL
]);
1798 e_WriteLog('NET: Connection request from ' + IP
+ ' rejected: server full',
1800 NetEvent
.Peer
^.data
:= GetMemory(SizeOf(Byte));
1801 Byte(NetEvent
.peer
^.data
^) := 255;
1802 enet_peer_disconnect(NetEvent
.peer
, NET_DISC_FULL
);
1803 enet_host_flush(NetHost
);
1807 NetClients
[ID
].Peer
:= NetEvent
.peer
;
1808 NetClients
[ID
].Peer
^.data
:= GetMemory(SizeOf(Byte));
1809 Byte(NetClients
[ID
].Peer
^.data
^) := ID
;
1810 NetClients
[ID
].State
:= NET_STATE_AUTH
;
1811 NetClients
[ID
].Player
:= 0;
1812 NetClients
[ID
].Crimes
:= 0;
1813 NetClients
[ID
].RCONAuth
:= False;
1814 NetClients
[ID
].NetOut
[NET_UNRELIABLE
].Alloc(NET_BUFSIZE
*2);
1815 NetClients
[ID
].NetOut
[NET_RELIABLE
].Alloc(NET_BUFSIZE
*2);
1816 if (NetAuthTimeout
> 0) then
1817 NetClients
[ID
].AuthTime
:= gTime
+ NetAuthTimeout
1819 NetClients
[ID
].AuthTime
:= 0;
1820 if (NetPacketTimeout
> 0) then
1821 NetClients
[ID
].MsgTime
:= gTime
+ NetPacketTimeout
1823 NetClients
[ID
].MsgTime
:= 0;
1824 clearNetClientTransfers(NetClients
[ID
]); // just in case
1826 enet_peer_timeout(NetEvent
.peer
, ENET_PEER_TIMEOUT_LIMIT
* 2, ENET_PEER_TIMEOUT_MINIMUM
* 2, ENET_PEER_TIMEOUT_MAXIMUM
* 2);
1828 Inc(NetClientCount
);
1829 g_Console_Add(_lc
[I_NET_MSG
] + Format(_lc
[I_NET_MSG_HOST_ADD
], [ID
]));
1832 ENET_EVENT_TYPE_RECEIVE
:
1834 //e_LogWritefln('RECEIVE: chan=%u', [NetEvent.channelID]);
1835 if (NetEvent
.channelID
= NET_CHAN_DOWNLOAD_EX
) then
1837 ProcessDownloadExPacket();
1841 ID
:= Byte(NetEvent
.peer
^.data
^);
1842 if ID
> High(NetClients
) then Exit
;
1843 TC
:= @NetClients
[ID
];
1845 if (NetPacketTimeout
> 0) then
1846 TC
^.MsgTime
:= gTime
+ NetPacketTimeout
;
1848 if NetDump
then g_Net_DumpRecvBuffer(NetEvent
.packet
^.data
, NetEvent
.packet
^.dataLength
);
1849 g_Net_Host_HandlePacket(TC
, NetEvent
.packet
, g_Net_HostMsgHandler
);
1853 ENET_EVENT_TYPE_DISCONNECT
:
1855 ID
:= Byte(NetEvent
.peer
^.data
^);
1856 if ID
> High(NetClients
) then Exit
;
1857 g_Net_Host_Disconnect_Client(ID
);
1864 //**************************************************************************
1868 //**************************************************************************
1870 procedure g_Net_Disconnect(Forced
: Boolean = False);
1872 if NetMode
<> NET_CLIENT
then Exit
;
1873 if (NetHost
= nil) or (NetPeer
= nil) then Exit
;
1877 enet_peer_disconnect(NetPeer
, NET_DISC_NONE
);
1879 while (enet_host_service(NetHost
, @NetEvent
, 1500) > 0) do
1881 if (NetEvent
.kind
= ENET_EVENT_TYPE_DISCONNECT
) then
1887 if (NetEvent
.kind
= ENET_EVENT_TYPE_RECEIVE
) then
1888 enet_packet_destroy(NetEvent
.packet
);
1891 if NetPeer
<> nil then
1893 enet_peer_reset(NetPeer
);
1899 e_WriteLog('NET: Kicked from server: ' + IntToStr(NetEvent
.data
), TMsgType
.Notify
);
1900 if (NetEvent
.data
<= NET_DISC_MAX
) then
1901 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_KICK
] +
1902 _lc
[TStrings_Locale(Cardinal(I_NET_DISC_NONE
) + NetEvent
.data
)], True);
1905 if NetHost
<> nil then
1907 enet_host_destroy(NetHost
);
1910 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_CLIENT_DISC
]);
1913 e_WriteLog('NET: Disconnected', TMsgType
.Notify
);
1916 procedure g_Net_Client_Send(Reliable
: Boolean; Chan
: Byte = NET_CHAN_GAME
);
1923 T
:= NET_UNRELIABLE
;
1926 NetBuf
[T
].Write(Integer(NetOut
.CurSize
));
1927 NetBuf
[T
].Write(NetOut
);
1929 if NetDump
then g_Net_DumpSendBuffer();
1931 g_Net_Flush(); // FIXME: for now, send immediately
1934 function g_Net_Client_Update(): enet_size_t
;
1937 while (NetHost
<> nil) and (enet_host_service(NetHost
, @NetEvent
, 0) > 0) do
1939 case NetEvent
.kind
of
1940 ENET_EVENT_TYPE_RECEIVE
:
1942 if (NetEvent
.channelID
= NET_CHAN_DOWNLOAD_EX
) then continue
; // ignore all download packets, they're processed by separate code
1943 if NetDump
then g_Net_DumpRecvBuffer(NetEvent
.packet
^.data
, NetEvent
.packet
^.dataLength
);
1944 g_Net_Client_HandlePacket(NetEvent
.packet
, g_Net_ClientMsgHandler
);
1947 ENET_EVENT_TYPE_DISCONNECT
:
1949 g_Net_Disconnect(True);
1957 function g_Net_Client_UpdateWhileLoading(): enet_size_t
;
1960 while (enet_host_service(NetHost
, @NetEvent
, 0) > 0) do
1962 case NetEvent
.kind
of
1963 ENET_EVENT_TYPE_RECEIVE
:
1965 if (NetEvent
.channelID
= NET_CHAN_DOWNLOAD_EX
) then continue
; // ignore all download packets, they're processed by separate code
1966 if NetDump
then g_Net_DumpRecvBuffer(NetEvent
.packet
^.data
, NetEvent
.packet
^.dataLength
);
1967 g_Net_Client_HandlePacket(NetEvent
.packet
, g_Net_ClientLightMsgHandler
);
1970 ENET_EVENT_TYPE_DISCONNECT
:
1972 g_Net_Disconnect(True);
1981 function g_Net_Connect(IP
: string; Port
: enet_uint16
): Boolean;
1984 TimeoutTime
, T
: Int64;
1986 if NetMode
<> NET_NONE
then
1988 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_ERR_INGAME
], True);
1995 g_Console_Add(_lc
[I_NET_MSG
] + Format(_lc
[I_NET_MSG_CLIENT_CONN
],
1997 if not NetInitDone
then
1999 if (not g_Net_Init()) then
2001 g_Console_Add(_lc
[I_NET_MSG_FERROR
] + _lc
[I_NET_ERR_ENET
], True);
2006 NetInitDone
:= True;
2009 NetHost
:= enet_host_create(nil, 1, NET_CHANS
, 0, 0);
2011 if (NetHost
= nil) then
2013 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CLIENT
], True);
2019 enet_address_set_host(@NetAddr
, PChar(Addr(IP
[1])));
2020 NetAddr
.port
:= Port
;
2022 NetPeer
:= enet_host_connect(NetHost
, @NetAddr
, NET_CHANS
, NET_PROTOCOL_VER
);
2024 if (NetPeer
= nil) then
2026 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CLIENT
], True);
2027 enet_host_destroy(NetHost
);
2033 // предупредить что ждем слишком долго через N секунд
2034 TimeoutTime
:= sys_GetTicks() + NET_CONNECT_TIMEOUT
;
2039 while (enet_host_service(NetHost
, @NetEvent
, 0) > 0) do
2041 if (NetEvent
.kind
= ENET_EVENT_TYPE_CONNECT
) then
2043 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_CLIENT_DONE
]);
2044 NetMode
:= NET_CLIENT
;
2046 enet_peer_timeout(NetPeer
, ENET_PEER_TIMEOUT_LIMIT
* 2, ENET_PEER_TIMEOUT_MINIMUM
* 2, ENET_PEER_TIMEOUT_MAXIMUM
* 2);
2048 NetClientPort
:= Port
;
2055 T
:= sys_GetTicks();
2056 if T
> TimeoutTime
then
2058 TimeoutTime
:= T
+ NET_CONNECT_TIMEOUT
* 100; // одного предупреждения хватит
2059 g_Console_Add(_lc
[I_NET_MSG_TIMEOUT_WARN
], True);
2060 g_Console_Add(Format(_lc
[I_NET_MSG_PORTS
], [Integer(Port
), Integer(NET_PING_PORT
)]), True);
2063 ProcessLoading(true);
2065 if e_KeyPressed(IK_SPACE
) or e_KeyPressed(IK_ESCAPE
) or e_KeyPressed(VK_ESCAPE
) or
2066 e_KeyPressed(JOY0_JUMP
) or e_KeyPressed(JOY1_JUMP
) or e_KeyPressed(JOY2_JUMP
) or e_KeyPressed(JOY3_JUMP
) then
2070 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_TIMEOUT
], True);
2071 g_Console_Add(Format(_lc
[I_NET_MSG_PORTS
], [Integer(Port
), Integer(NET_PING_PORT
)]), True);
2072 if NetPeer
<> nil then enet_peer_reset(NetPeer
);
2073 if NetHost
<> nil then
2075 enet_host_destroy(NetHost
);
2082 function IpToStr(IP
: LongWord): string;
2087 Result
:= IntToStr(PByte(Ptr
+ 0)^) + '.';
2088 Result
:= Result
+ IntToStr(PByte(Ptr
+ 1)^) + '.';
2089 Result
:= Result
+ IntToStr(PByte(Ptr
+ 2)^) + '.';
2090 Result
:= Result
+ IntToStr(PByte(Ptr
+ 3)^);
2093 function StrToIp(IPstr
: string; var IP
: LongWord): Boolean;
2097 Result
:= enet_address_set_host(@EAddr
, PChar(@IPstr
[1])) = 0;
2101 function g_Net_Client_ByName(Name
: string): pTNetClient
;
2107 for a
:= Low(NetClients
) to High(NetClients
) do
2108 if (NetClients
[a
].Used
) and (NetClients
[a
].State
= NET_STATE_GAME
) then
2110 pl
:= g_Player_Get(NetClients
[a
].Player
);
2111 if pl
= nil then continue
;
2112 if Copy(LowerCase(pl
.Name
), 1, Length(Name
)) <> LowerCase(Name
) then continue
;
2113 if NetClients
[a
].Peer
<> nil then
2115 Result
:= @NetClients
[a
];
2121 function g_Net_Client_ByPlayer(PID
: Word): pTNetClient
;
2126 for a
:= Low(NetClients
) to High(NetClients
) do
2127 if (NetClients
[a
].Used
) and (NetClients
[a
].State
= NET_STATE_GAME
) then
2128 if NetClients
[a
].Player
= PID
then
2130 Result
:= @NetClients
[a
];
2135 function g_Net_ClientName_ByID(ID
: Integer): string;
2141 if ID
= NET_EVERYONE
then
2143 for a
:= Low(NetClients
) to High(NetClients
) do
2144 if (NetClients
[a
].ID
= ID
) and (NetClients
[a
].Used
) and (NetClients
[a
].State
= NET_STATE_GAME
) then
2146 pl
:= g_Player_Get(NetClients
[a
].Player
);
2147 if pl
= nil then Exit
;
2152 procedure g_Net_SendData(Data
: AByte
; peer
: pENetPeer
; Reliable
: Boolean; Chan
: Byte = NET_CHAN_DOWNLOAD
);
2156 dataLength
: Cardinal;
2158 dataLength
:= Length(Data
);
2161 F
:= LongWord(ENET_PACKET_FLAG_RELIABLE
)
2165 if (peer
<> nil) then
2167 P
:= enet_packet_create(@Data
[0], dataLength
, F
);
2168 if not Assigned(P
) then Exit
;
2169 enet_peer_send(peer
, Chan
, P
);
2173 P
:= enet_packet_create(@Data
[0], dataLength
, F
);
2174 if not Assigned(P
) then Exit
;
2175 enet_host_broadcast(NetHost
, Chan
, P
);
2178 enet_host_flush(NetHost
);
2181 function g_Net_IsHostBanned(IP
: LongWord; Perm
: Boolean = False): Boolean;
2186 if NetBannedHosts
= nil then
2188 for I
:= 0 to High(NetBannedHosts
) do
2189 if (NetBannedHosts
[I
].IP
= IP
) and ((not Perm
) or (NetBannedHosts
[I
].Perm
)) then
2196 procedure g_Net_BanHost(IP
: LongWord; Perm
: Boolean = True); overload
;
2202 if g_Net_IsHostBanned(IP
, Perm
) then
2206 for I
:= Low(NetBannedHosts
) to High(NetBannedHosts
) do
2207 if NetBannedHosts
[I
].IP
= 0 then
2215 SetLength(NetBannedHosts
, Length(NetBannedHosts
) + 1);
2216 P
:= High(NetBannedHosts
);
2219 NetBannedHosts
[P
].IP
:= IP
;
2220 NetBannedHosts
[P
].Perm
:= Perm
;
2223 procedure g_Net_BanHost(IP
: string; Perm
: Boolean = True); overload
;
2228 b
:= StrToIp(IP
, a
);
2230 g_Net_BanHost(a
, Perm
);
2233 procedure g_Net_UnbanNonPermHosts();
2237 if NetBannedHosts
= nil then
2239 for I
:= Low(NetBannedHosts
) to High(NetBannedHosts
) do
2240 if (NetBannedHosts
[I
].IP
> 0) and not NetBannedHosts
[I
].Perm
then
2242 NetBannedHosts
[I
].IP
:= 0;
2243 NetBannedHosts
[I
].Perm
:= True;
2247 function g_Net_UnbanHost(IP
: string): Boolean; overload
;
2251 Result
:= StrToIp(IP
, a
);
2253 Result
:= g_Net_UnbanHost(a
);
2256 function g_Net_UnbanHost(IP
: LongWord): Boolean; overload
;
2263 if NetBannedHosts
= nil then
2265 for I
:= 0 to High(NetBannedHosts
) do
2266 if NetBannedHosts
[I
].IP
= IP
then
2268 NetBannedHosts
[I
].IP
:= 0;
2269 NetBannedHosts
[I
].Perm
:= True;
2271 // no break here to clear all bans of this host, perm and non-perm
2275 procedure g_Net_SaveBanList();
2281 path
:= e_GetWriteableDir(DataDirs
);
2284 path
:= e_CatPath(path
, BANLIST_FILENAME
);
2287 if NetBannedHosts
<> nil then
2288 for I
:= 0 to High(NetBannedHosts
) do
2289 if NetBannedHosts
[I
].Perm
and (NetBannedHosts
[I
].IP
> 0) then
2290 Writeln(F
, IpToStr(NetBannedHosts
[I
].IP
));
2295 procedure g_Net_Penalize(C
: pTNetClient
; Reason
: string);
2299 e_LogWritefln('NET: client #%u (cid #%u) triggered a penalty (%d/%d): %s',
2300 [C
^.ID
, C
^.Player
, C
^.Crimes
+ 1, NetAutoBanLimit
, Reason
]);
2302 if (NetAutoBanLimit
<= 0) then Exit
;
2304 if (C
^.Crimes
>= NetAutoBanLimit
) then
2306 // we have tried asking nicely before, now it is time to die
2307 e_LogWritefln('NET: client #%u (cid #%u) force kicked',
2308 [C
^.ID
, C
^.Player
]);
2309 g_Net_Host_Disconnect_Client(C
^.ID
, True);
2315 if (NetAutoBanWarn
) then
2316 MH_SEND_Chat('You have been warned by the server: ' + Reason
, NET_CHAT_SYSTEM
, C
^.ID
);
2318 if (C
^.Crimes
>= NetAutoBanLimit
) then
2320 s
:= '#' + IntToStr(C
^.ID
); // can't be arsed
2321 g_Net_BanHost(C
^.Peer
^.address
.host
, NetAutoBanPerm
);
2322 enet_peer_disconnect(C
^.Peer
, NET_DISC_BAN
);
2323 g_Console_Add(Format(_lc
[I_PLAYER_BAN
], [s
]));
2324 MH_SEND_GameEvent(NET_EV_PLAYER_BAN
, 0, s
);
2325 g_Net_Slist_ServerPlayerLeaves();
2329 procedure g_Net_DumpStart();
2331 if NetMode
= NET_SERVER
then
2332 NetDumpFile
:= e_CreateResource(LogDirs
, NETDUMP_FILENAME
+ '_server')
2334 NetDumpFile
:= e_CreateResource(LogDirs
, NETDUMP_FILENAME
+ '_client');
2337 procedure g_Net_DumpSendBuffer();
2339 writeInt(NetDumpFile
, gTime
);
2340 writeInt(NetDumpFile
, LongWord(NetOut
.CurSize
));
2341 writeInt(NetDumpFile
, Byte(1));
2342 NetDumpFile
.WriteBuffer(NetOut
.Data
^, NetOut
.CurSize
);
2345 procedure g_Net_DumpRecvBuffer(Buf
: penet_uint8
; Len
: LongWord);
2347 if (Buf
= nil) or (Len
= 0) then Exit
;
2348 writeInt(NetDumpFile
, gTime
);
2349 writeInt(NetDumpFile
, Len
);
2350 writeInt(NetDumpFile
, Byte(0));
2351 NetDumpFile
.WriteBuffer(Buf
^, Len
);
2354 procedure g_Net_DumpEnd();
2360 function g_Net_ForwardPorts(ForwardPongPort
: Boolean = True): Boolean;
2361 {$IFDEF USE_MINIUPNPC}
2366 LanAddr
: array [0..255] of Char;
2367 StrPort
: AnsiString;
2372 if NetHost
= nil then
2375 if NetPortForwarded
= NetHost
.address
.port
then
2381 NetPongForwarded
:= False;
2382 NetPortForwarded
:= 0;
2384 DevList
:= upnpDiscover(1000, nil, nil, 0, 0, 2, Addr(Err
));
2385 if DevList
= nil then
2387 conwritefln('port forwarding failed: upnpDiscover() failed: %d', [Err
]);
2391 I
:= UPNP_GetValidIGD(DevList
, @Urls
, @Data
, Addr(LanAddr
[0]), 256);
2395 conwriteln('port forwarding failed: could not find an IGD device on this LAN');
2396 FreeUPNPDevList(DevList
);
2397 FreeUPNPUrls(@Urls
);
2401 StrPort
:= IntToStr(NetHost
.address
.port
);
2402 I
:= UPNP_AddPortMapping(
2403 Urls
.controlURL
, Addr(data
.first
.servicetype
[1]),
2404 PChar(StrPort
), PChar(StrPort
), Addr(LanAddr
[0]), PChar('D2DF'),
2405 PChar('UDP'), nil, PChar('0')
2410 conwritefln('forwarding port %d failed: error %d', [NetHost
.address
.port
, I
]);
2411 FreeUPNPDevList(DevList
);
2412 FreeUPNPUrls(@Urls
);
2416 if ForwardPongPort
then
2418 StrPort
:= IntToStr(NET_PING_PORT
);
2419 I
:= UPNP_AddPortMapping(
2420 Urls
.controlURL
, Addr(data
.first
.servicetype
[1]),
2421 PChar(StrPort
), PChar(StrPort
), Addr(LanAddr
[0]), PChar('D2DF'),
2422 PChar('UDP'), nil, PChar('0')
2427 conwritefln('forwarding port %d failed: error %d', [NET_PING_PORT
, I
]);
2428 NetPongForwarded
:= False;
2432 conwritefln('forwarded port %d successfully', [NET_PING_PORT
]);
2433 NetPongForwarded
:= True;
2437 conwritefln('forwarded port %d successfully', [NetHost
.address
.port
]);
2438 NetIGDControl
:= AnsiString(Urls
.controlURL
);
2439 NetIGDService
:= data
.first
.servicetype
;
2440 NetPortForwarded
:= NetHost
.address
.port
;
2442 FreeUPNPDevList(DevList
);
2443 FreeUPNPUrls(@Urls
);
2452 procedure g_Net_UnforwardPorts();
2453 {$IFDEF USE_MINIUPNPC}
2456 StrPort
: AnsiString;
2458 if NetPortForwarded
= 0 then Exit
;
2460 conwriteln('unforwarding ports...');
2462 StrPort
:= IntToStr(NetPortForwarded
);
2463 I
:= UPNP_DeletePortMapping(
2464 PChar(NetIGDControl
), Addr(NetIGDService
[1]),
2465 PChar(StrPort
), PChar('UDP'), nil
2467 conwritefln(' port %d: %d', [NetPortForwarded
, I
]);
2469 if NetPongForwarded
then
2471 NetPongForwarded
:= False;
2472 StrPort
:= IntToStr(NET_PING_PORT
);
2473 I
:= UPNP_DeletePortMapping(
2474 PChar(NetIGDControl
), Addr(NetIGDService
[1]),
2475 PChar(StrPort
), PChar('UDP'), nil
2477 conwritefln(' port %d: %d', [NET_PING_PORT
, I
]);
2480 NetPortForwarded
:= 0;
2487 procedure NetServerCVars(P
: SSArray
);
2492 cmd
:= LowerCase(P
[0]);
2496 if (Length(P
) > 1) and (Length(P
[1]) > 0) then
2498 NetServerName
:= P
[1];
2499 if Length(NetServerName
) > 64 then
2500 SetLength(NetServerName
, 64);
2501 g_Net_Slist_ServerRenamed();
2503 g_Console_Add(cmd
+ ' "' + NetServerName
+ '"');
2507 if (Length(P
) > 1) and (Length(P
[1]) > 0) then
2509 NetPassword
:= P
[1];
2510 if Length(NetPassword
) > 24 then
2511 SetLength(NetPassword
, 24);
2512 g_Net_Slist_ServerRenamed();
2514 g_Console_Add(cmd
+ ' "' + AnsiLowerCase(NetPassword
) + '"');
2518 if (Length(P
) > 1) then
2520 NetMaxClients
:= nclamp(StrToIntDef(P
[1], NetMaxClients
), 1, NET_MAXCLIENTS
);
2521 if g_Game_IsServer
and g_Game_IsNet
then
2524 for a
:= 0 to High(NetClients
) do
2526 if NetClients
[a
].Used
then
2529 if b
> NetMaxClients
then
2531 s
:= g_Player_Get(NetClients
[a
].Player
).Name
;
2532 enet_peer_disconnect(NetClients
[a
].Peer
, NET_DISC_FULL
);
2533 g_Console_Add(Format(_lc
[I_PLAYER_KICK
], [s
]));
2534 MH_SEND_GameEvent(NET_EV_PLAYER_KICK
, 0, s
);
2538 g_Net_Slist_ServerRenamed();
2541 g_Console_Add(cmd
+ ' ' + IntToStr(NetMaxClients
));
2545 if (Length(P
) > 1) then
2547 NetUseMaster
:= StrToIntDef(P
[1], Byte(NetUseMaster
)) <> 0;
2548 if NetUseMaster
then g_Net_Slist_Public() else g_Net_Slist_Private();
2550 g_Console_Add(cmd
+ ' ' + IntToStr(Byte(NetUseMaster
)));
2554 if (Length(P
) > 1) then
2556 if not g_Game_IsNet
then
2557 NetPort
:= nclamp(StrToIntDef(P
[1], NetPort
), 0, $FFFF)
2559 g_Console_Add(_lc
[I_MSG_NOT_NETGAME
]);
2561 g_Console_Add(cmd
+ ' ' + IntToStr(Ord(NetUseMaster
)));
2567 conRegVar('cl_downloadtimeout', @g_Net_DownloadTimeout
, 0.0, 1000000.0, '', 'timeout in seconds, 0 to disable it');
2568 conRegVar('cl_predictself', @NetPredictSelf
, '', 'predict local player');
2569 conRegVar('cl_forceplayerupdate', @NetForcePlayerUpdate
, '', 'update net players on NET_MSG_PLRPOS');
2570 conRegVar('cl_interp', @NetInterpLevel
, '', 'net player interpolation steps');
2571 conRegVar('cl_last_ip', @NetClientIP
, '', 'address of the last you have connected to');
2572 conRegVar('cl_last_port', @NetClientPort
, '', 'port of the last server you have connected to');
2573 conRegVar('cl_deafen', @NetDeafLevel
, '', 'filter server messages (0-3)');
2575 conRegVar('sv_forwardports', @NetForwardPorts
, '', 'forward server port using miniupnpc (requires server restart)');
2576 conRegVar('sv_rcon', @NetAllowRCON
, '', 'enable remote console');
2577 conRegVar('sv_rcon_password', @NetRCONPassword
, '', 'remote console password');
2578 conRegVar('sv_update_interval', @NetUpdateRate
, '', 'unreliable update interval');
2579 conRegVar('sv_reliable_interval', @NetRelupdRate
, '', 'reliable update interval');
2580 conRegVar('sv_master_interval', @NetMasterRate
, '', 'master server update interval');
2582 conRegVar('sv_autoban_threshold', @NetAutoBanLimit
, '', 'max crimes before autoban (0 = no autoban)');
2583 conRegVar('sv_autoban_permanent', @NetAutoBanPerm
, '', 'whether autobans are permanent');
2584 conRegVar('sv_autoban_warn', @NetAutoBanWarn
, '', 'send warnings to the client when he triggers penalties');
2586 conRegVar('sv_auth_timeout', @NetAuthTimeout
, '', 'number of msec in which connecting clients must complete auth (0 = unlimited)');
2587 conRegVar('sv_packet_timeout', @NetPacketTimeout
, '', 'number of msec the client must idle to be kicked (0 = unlimited)');
2589 conRegVar('net_master_list', @NetMasterList
, '', 'list of master servers');
2591 SetLength(NetClients
, 0);
2592 g_Net_DownloadTimeout
:= 60;
2593 NetIn
.Alloc(NET_BUFSIZE
);
2594 NetOut
.Alloc(NET_BUFSIZE
);
2595 NetBuf
[NET_UNRELIABLE
].Alloc(NET_BUFSIZE
*2);
2596 NetBuf
[NET_RELIABLE
].Alloc(NET_BUFSIZE
*2);
2597 trans_omsg
.Alloc(NET_BUFSIZE
);
2601 NetBuf
[NET_UNRELIABLE
].Free();
2602 NetBuf
[NET_RELIABLE
].Free();