1 (* Copyright (C) Doom 2D: Forever Developers
3 * This program is free software: you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation, version 3 of the License ONLY.
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
12 * You should have received a copy of the GNU General Public License
13 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 {$INCLUDE ../shared/a_modes.inc}
21 e_log
, e_msg
, ENet
, Classes
, md5
, MAPDEF
{$IFDEF USE_MINIUPNPC}, miniupnpc
;{$ELSE};{$ENDIF}
24 NET_PROTOCOL_VER
= 182;
30 NET_CHAN_IMPORTANT
= 1;
33 NET_CHAN_PLAYERPOS
= 4;
35 NET_CHAN_MONSTERPOS
= 6;
36 NET_CHAN_LARGEDATA
= 7;
38 NET_CHAN_DOWNLOAD
= 9;
40 NET_CHAN_DOWNLOAD_EX
= 11;
47 NET_PING_PORT
= $DF2D;
54 NET_DISC_NONE
: enet_uint32
= 0;
55 NET_DISC_PROTOCOL
: enet_uint32
= 1;
56 NET_DISC_VERSION
: enet_uint32
= 2;
57 NET_DISC_FULL
: enet_uint32
= 3;
58 NET_DISC_KICK
: enet_uint32
= 4;
59 NET_DISC_DOWN
: enet_uint32
= 5;
60 NET_DISC_PASSWORD
: enet_uint32
= 6;
61 NET_DISC_TEMPBAN
: enet_uint32
= 7;
62 NET_DISC_BAN
: enet_uint32
= 8;
63 NET_DISC_MAX
: enet_uint32
= 8;
64 NET_DISC_FILE_TIMEOUT
: enet_uint32
= 13;
70 NET_CONNECT_TIMEOUT
= 1000 * 10;
72 BANLIST_FILENAME
= 'banlist.txt';
73 NETDUMP_FILENAME
= 'netdump';
82 TNetMapResourceInfo
= record
83 wadName
: AnsiString; // wad file name, without a path
84 size
: Integer; // wad file size (-1: size and hash are not known)
85 hash
: TMD5Digest
; // wad hash
88 TNetMapResourceInfoArray
= array of TNetMapResourceInfo
;
90 TNetFileTransfer
= record
94 size
: Integer; // file size in bytes
96 lastSentChunk
: Integer;
97 lastAckChunk
: Integer;
98 lastAckTime
: Int64; // msecs; if not "in progress", we're waiting for the first ack
100 diskBuffer
: PChar; // of `chunkSize` bytes
110 RequestedFullUpdate
: Boolean;
113 Transfer
: TNetFileTransfer
; // only one transfer may be active
114 NetOut
: array [0..1] of TMsg
;
120 pTNetClient
= ^TNetClient
;
122 AByte
= array of Byte;
125 NetInitDone
: Boolean = False;
126 NetMode
: Byte = NET_NONE
;
127 NetDump
: Boolean = False;
129 NetServerName
: string = 'Unnamed Server';
130 NetPassword
: string = '';
131 NetPort
: Word = 25666;
133 NetAllowRCON
: Boolean = False;
134 NetRCONPassword
: string = '';
136 NetTimeToUpdate
: Cardinal = 0;
137 NetTimeToReliable
: Cardinal = 0;
138 NetTimeToMaster
: Cardinal = 0;
140 NetHost
: pENetHost
= nil;
141 NetPeer
: pENetPeer
= nil;
143 NetAddr
: ENetAddress
;
145 NetPongAddr
: ENetAddress
;
146 NetPongSock
: ENetSocket
= ENET_SOCKET_NULL
;
148 NetUseMaster
: Boolean = True;
149 NetSlistAddr
: ENetAddress
;
150 NetSlistIP
: string = 'mpms.doom2d.org';
151 NetSlistPort
: Word = 25665;
153 NetClientIP
: string = '127.0.0.1';
154 NetClientPort
: Word = 25666;
157 NetBuf
: array [0..1] of TMsg
;
159 NetClients
: array of TNetClient
;
160 NetClientCount
: Byte = 0;
161 NetMaxClients
: Byte = 255;
162 NetBannedHosts
: array of TBanRecord
;
164 NetState
: Integer = NET_STATE_NONE
;
166 NetMyID
: Integer = -1;
167 NetPlrUID1
: Integer = -1;
168 NetPlrUID2
: Integer = -1;
170 NetInterpLevel
: Integer = 1;
171 NetUpdateRate
: Cardinal = 0; // as soon as possible
172 NetRelupdRate
: Cardinal = 18; // around two times a second
173 NetMasterRate
: Cardinal = 60000;
175 NetForcePlayerUpdate
: Boolean = False;
176 NetPredictSelf
: Boolean = True;
177 NetForwardPorts
: Boolean = False;
179 NetGotEverything
: Boolean = False;
180 NetGotKeys
: Boolean = False;
182 {$IFDEF USE_MINIUPNPC}
183 NetPortForwarded
: Word = 0;
184 NetPongForwarded
: Boolean = False;
185 NetIGDControl
: AnsiString;
186 NetIGDService
: TURLStr
;
189 NetPortThread
: TThreadID
= NilThreadId
;
191 NetDumpFile
: TStream
;
193 g_Res_received_map_start
: Integer = 0; // set if we received "map change" event
196 function g_Net_Init(): Boolean;
197 procedure g_Net_Cleanup();
198 procedure g_Net_Free();
199 procedure g_Net_Flush();
201 function g_Net_Host(IPAddr
: LongWord; Port
: enet_uint16
; MaxClients
: Cardinal = 16): Boolean;
202 procedure g_Net_Host_Die();
203 procedure g_Net_Host_Send(ID
: Integer; Reliable
: Boolean; Chan
: Byte = NET_CHAN_GAME
);
204 function g_Net_Host_Update(): enet_size_t
;
206 function g_Net_Connect(IP
: string; Port
: enet_uint16
): Boolean;
207 procedure g_Net_Disconnect(Forced
: Boolean = False);
208 procedure g_Net_Client_Send(Reliable
: Boolean; Chan
: Byte = NET_CHAN_GAME
);
209 function g_Net_Client_Update(): enet_size_t
;
210 function g_Net_Client_UpdateWhileLoading(): enet_size_t
;
212 function g_Net_Client_ByName(Name
: string): pTNetClient
;
213 function g_Net_Client_ByPlayer(PID
: Word): pTNetClient
;
214 function g_Net_ClientName_ByID(ID
: Integer): string;
216 procedure g_Net_SendData(Data
: AByte
; peer
: pENetPeer
; Reliable
: Boolean; Chan
: Byte = NET_CHAN_DOWNLOAD
);
217 //function g_Net_Wait_Event(msgId: Word): TMemoryStream;
218 //function g_Net_Wait_FileInfo (var tf: TNetFileTransfer; asMap: Boolean; out resList: TStringList): Integer;
220 function IpToStr(IP
: LongWord): string;
221 function StrToIp(IPstr
: string; var IP
: LongWord): Boolean;
223 function g_Net_IsHostBanned(IP
: LongWord; Perm
: Boolean = False): Boolean;
224 procedure g_Net_BanHost(IP
: LongWord; Perm
: Boolean = True); overload
;
225 procedure g_Net_BanHost(IP
: string; Perm
: Boolean = True); overload
;
226 function g_Net_UnbanHost(IP
: string): Boolean; overload
;
227 function g_Net_UnbanHost(IP
: LongWord): Boolean; overload
;
228 procedure g_Net_UnbanNonPermHosts();
229 procedure g_Net_SaveBanList();
231 procedure g_Net_DumpStart();
232 procedure g_Net_DumpSendBuffer();
233 procedure g_Net_DumpRecvBuffer(Buf
: penet_uint8
; Len
: LongWord);
234 procedure g_Net_DumpEnd();
236 function g_Net_ForwardPorts(ForwardPongPort
: Boolean = True): Boolean;
237 procedure g_Net_UnforwardPorts();
239 function g_Net_UserRequestExit
: Boolean;
241 function g_Net_Wait_MapInfo (var tf
: TNetFileTransfer
; var resList
: TNetMapResourceInfoArray
): Integer;
242 function g_Net_RequestResFileInfo (resIndex
: LongInt; out tf
: TNetFileTransfer
): Integer;
243 function g_Net_AbortResTransfer (var tf
: TNetFileTransfer
): Boolean;
244 function g_Net_ReceiveResourceFile (resIndex
: LongInt; var tf
: TNetFileTransfer
; strm
: TStream
): Integer;
251 e_input
, g_nethandler
, g_netmsg
, g_netmaster
, g_player
, g_window
, g_console
,
252 g_main
, g_game
, g_language
, g_weapons
, utils
, ctypes
,
256 FILE_CHUNK_SIZE
= 8192;
259 g_Net_DownloadTimeout
: Single;
263 //**************************************************************************
267 //**************************************************************************
269 procedure clearNetClientTransfers (var nc
: TNetClient
);
271 nc
.Transfer
.stream
.Free
;
272 nc
.Transfer
.diskName
:= ''; // just in case
273 if (nc
.Transfer
.diskBuffer
<> nil) then FreeMem(nc
.Transfer
.diskBuffer
);
274 nc
.Transfer
.stream
:= nil;
275 nc
.Transfer
.diskBuffer
:= nil;
279 procedure clearNetClient (var nc
: TNetClient
);
281 clearNetClientTransfers(nc
);
285 procedure clearNetClients (clearArray
: Boolean);
289 for f
:= Low(NetClients
) to High(NetClients
) do clearNetClient(NetClients
[f
]);
290 if (clearArray
) then SetLength(NetClients
, 0);
294 function g_Net_UserRequestExit (): Boolean;
296 Result
:= {e_KeyPressed(IK_SPACE) or}
297 e_KeyPressed(IK_ESCAPE
) or
298 e_KeyPressed(VK_ESCAPE
) or
299 e_KeyPressed(JOY0_JUMP
) or
300 e_KeyPressed(JOY1_JUMP
) or
301 e_KeyPressed(JOY2_JUMP
) or
302 e_KeyPressed(JOY3_JUMP
)
306 //**************************************************************************
308 // file transfer declaraions and host packet processor
310 //**************************************************************************
313 // server packet type
314 NTF_SERVER_DONE
= 10; // done with this file
315 NTF_SERVER_FILE_INFO
= 11; // sent after client request
316 NTF_SERVER_CHUNK
= 12; // next chunk; chunk number follows
317 NTF_SERVER_ABORT
= 13; // server abort
318 NTF_SERVER_MAP_INFO
= 14;
320 // client packet type
321 NTF_CLIENT_MAP_REQUEST
= 100; // map file request; also, returns list of additional wads to download
322 NTF_CLIENT_FILE_REQUEST
= 101; // resource file request (by index)
323 NTF_CLIENT_ABORT
= 102; // do not send requested file, or abort current transfer
324 NTF_CLIENT_START
= 103; // start transfer; client may resume download by sending non-zero starting chunk
325 NTF_CLIENT_ACK
= 104; // chunk ack; chunk number follows
328 // disconnect client due to some file transfer error
329 procedure killClientByFT (var nc
: TNetClient
);
331 e_LogWritefln('disconnected client #%d due to file transfer error', [nc
.ID
], TMsgType
.Warning
);
332 enet_peer_disconnect(nc
.Peer
, NET_DISC_FILE_TIMEOUT
);
333 clearNetClientTransfers(nc
);
337 // send file transfer message from server to client
338 function ftransSendServerMsg (var nc
: TNetClient
; var m
: TMsg
): Boolean;
343 if (m
.CurSize
< 1) then exit
;
344 pkt
:= enet_packet_create(m
.Data
, m
.CurSize
, ENET_PACKET_FLAG_RELIABLE
);
345 if not Assigned(pkt
) then begin killClientByFT(nc
); exit
; end;
346 if (enet_peer_send(nc
.Peer
, NET_CHAN_DOWNLOAD_EX
, pkt
) <> 0) then begin killClientByFT(nc
); exit
; end;
351 // send file transfer message from client to server
352 function ftransSendClientMsg (var m
: TMsg
): Boolean;
357 if (m
.CurSize
< 1) then exit
;
358 pkt
:= enet_packet_create(m
.Data
, m
.CurSize
, ENET_PACKET_FLAG_RELIABLE
);
359 if not Assigned(pkt
) then exit
;
360 if (enet_peer_send(NetPeer
, NET_CHAN_DOWNLOAD_EX
, pkt
) <> 0) then exit
;
366 procedure ProcessChunkSend (var nc
: TNetClient
);
368 tf
: ^TNetFileTransfer
;
374 if (tf
.stream
= nil) then exit
;
376 // arbitrary timeout number
377 if (ct
-tf
.lastAckTime
>= 5000) then
382 // check if we need to send something
383 if (not tf
.inProgress
) then exit
; // waiting for the initial ack
384 // ok, we're sending chunks
385 if (tf
.lastAckChunk
<> tf
.lastSentChunk
) then exit
;
386 Inc(tf
.lastSentChunk
);
387 // do it one chunk at a time; client ack will advance our chunk counter
388 chunks
:= (tf
.size
+tf
.chunkSize
-1) div tf
.chunkSize
;
390 if (tf
.lastSentChunk
> chunks
) then
397 if (tf
.lastSentChunk
= chunks
) then
399 // we're done with this file
400 e_LogWritefln('download: client #%d, DONE sending chunks #%d/#%d', [nc
.ID
, tf
.lastSentChunk
, chunks
]);
401 trans_omsg
.Write(Byte(NTF_SERVER_DONE
));
402 clearNetClientTransfers(nc
);
407 trans_omsg
.Write(Byte(NTF_SERVER_CHUNK
));
408 trans_omsg
.Write(LongInt(tf
.lastSentChunk
));
410 rd
:= tf
.size
-(tf
.lastSentChunk
*tf
.chunkSize
);
411 if (rd
> tf
.chunkSize
) then rd
:= tf
.chunkSize
;
412 trans_omsg
.Write(LongInt(rd
));
413 //e_LogWritefln('download: client #%d, sending chunk #%d/#%d (%d bytes)', [nc.ID, tf.lastSentChunk, chunks, rd]);
414 //FIXME: check for errors here
416 tf
.stream
.Seek(tf
.lastSentChunk
*tf
.chunkSize
, soFromBeginning
);
417 tf
.stream
.ReadBuffer(tf
.diskBuffer
^, rd
);
418 trans_omsg
.WriteData(tf
.diskBuffer
, rd
);
425 ftransSendServerMsg(nc
, trans_omsg
);
429 // server file transfer packet processor
430 // received packet is in `NetEvent`
431 procedure ProcessDownloadExPacket ();
438 tf
: ^TNetFileTransfer
;
448 // find client index by peer
449 for f
:= Low(NetClients
) to High(NetClients
) do
451 if (not NetClients
[f
].Used
) then continue
;
452 if (NetClients
[f
].Peer
= NetEvent
.peer
) then
458 //e_LogWritefln('RECEIVE: dlpacket; client=%d (datalen=%u)', [nid, NetEvent.packet^.dataLength]);
460 if (nid
< 0) then exit
; // wtf?!
461 nc
:= @NetClients
[nid
];
463 if (NetEvent
.packet
^.dataLength
= 0) then
469 tf
:= @NetClients
[nid
].Transfer
;
470 tf
.lastAckTime
:= GetTimerMS();
472 cmd
:= Byte(NetEvent
.packet
^.data
^);
473 //e_LogWritefln('RECEIVE: nid=%d; cmd=%u', [nid, cmd]);
475 NTF_CLIENT_FILE_REQUEST
: // file request
477 if (tf
.stream
<> nil) then
482 if (NetEvent
.packet
^.dataLength
< 2) then
487 // new transfer request; build packet
488 if not msg
.Init(NetEvent
.packet
^.data
+1, NetEvent
.packet
^.dataLength
-1, True) then
493 // get resource index
494 ridx
:= msg
.ReadLongInt();
495 if (ridx
< -1) or (ridx
>= length(gExternalResources
)) then
497 e_LogWritefln('Invalid resource index %d', [ridx
], TMsgType
.Warning
);
501 if (ridx
< 0) then fname
:= MapsDir
+gGameSettings
.WAD
else fname
:= {GameDir+'/wads/'+}gExternalResources
[ridx
].diskName
;
502 if (length(fname
) = 0) then
504 e_WriteLog('Invalid filename: '+fname
, TMsgType
.Warning
);
508 tf
.diskName
:= findDiskWad(fname
);
509 //if (length(tf.diskName) = 0) then tf.diskName := findDiskWad(GameDir+'/wads/'+fname);
510 if (length(tf
.diskName
) = 0) then
512 e_LogWritefln('NETWORK: file "%s" not found!', [fname
], TMsgType
.Fatal
);
517 //tf.hash := MD5File(tf.diskName);
518 if (ridx
< 0) then tf
.hash
:= gWADHash
else tf
.hash
:= gExternalResources
[ridx
].hash
;
519 // create file stream
520 tf
.diskName
:= findDiskWad(fname
);
522 tf
.stream
:= openDiskFileRO(tf
.diskName
);
526 if (tf
.stream
= nil) then
528 e_WriteLog(Format('NETWORK: file "%s" not found!', [fname
]), TMsgType
.Fatal
);
532 e_LogWritefln('client #%d requested resource #%d (file is `%s` : `%s`)', [nc
.ID
, ridx
, fname
, tf
.diskName
]);
533 tf
.size
:= tf
.stream
.size
;
534 tf
.chunkSize
:= FILE_CHUNK_SIZE
; // arbitrary
535 tf
.lastSentChunk
:= -1;
536 tf
.lastAckChunk
:= -1;
537 tf
.lastAckTime
:= GetTimerMS();
538 tf
.inProgress
:= False; // waiting for the first ACK or for the cancel
539 GetMem(tf
.diskBuffer
, tf
.chunkSize
);
540 // sent file info message
542 trans_omsg
.Write(Byte(NTF_SERVER_FILE_INFO
));
543 trans_omsg
.Write(tf
.hash
);
544 trans_omsg
.Write(tf
.size
);
545 trans_omsg
.Write(tf
.chunkSize
);
546 trans_omsg
.Write(ExtractFileName(fname
));
547 if not ftransSendServerMsg(nc
^, trans_omsg
) then exit
;
549 NTF_CLIENT_ABORT
: // do not send requested file, or abort current transfer
551 e_LogWritefln('client #%d aborted file transfer', [nc
.ID
]);
552 clearNetClientTransfers(nc
^);
554 NTF_CLIENT_START
: // start transfer; client may resume download by sending non-zero starting chunk
556 if not Assigned(tf
.stream
) then
561 if (tf
.lastSentChunk
<> -1) or (tf
.lastAckChunk
<> -1) or (tf
.inProgress
) then
563 // double ack, get lost
567 if (NetEvent
.packet
^.dataLength
< 2) then
573 if not msg
.Init(NetEvent
.packet
^.data
+1, NetEvent
.packet
^.dataLength
-1, True) then
578 chunk
:= msg
.ReadLongInt();
579 if (chunk
< 0) or (chunk
> (tf
.size
+tf
.chunkSize
-1) div tf
.chunkSize
) then
584 e_LogWritefln('client #%d started file transfer from chunk %d', [nc
.ID
, chunk
]);
585 // start sending chunks
586 tf
.inProgress
:= True;
587 tf
.lastSentChunk
:= chunk
-1;
588 tf
.lastAckChunk
:= chunk
-1;
589 ProcessChunkSend(nc
^);
591 NTF_CLIENT_ACK
: // chunk ack; chunk number follows
593 if not Assigned(tf
.stream
) then
598 if (tf
.lastSentChunk
< 0) or (not tf
.inProgress
) then
600 // double ack, get lost
604 if (NetEvent
.packet
^.dataLength
< 2) then
610 if not msg
.Init(NetEvent
.packet
^.data
+1, NetEvent
.packet
^.dataLength
-1, True) then
615 chunk
:= msg
.ReadLongInt();
616 if (chunk
< 0) or (chunk
> (tf
.size
+tf
.chunkSize
-1) div tf
.chunkSize
) then
621 // do it this way, so client may seek, or request retransfers for some reason
622 tf
.lastAckChunk
:= chunk
;
623 tf
.lastSentChunk
:= chunk
;
624 //e_LogWritefln('client #%d acked file transfer chunk %d', [nc.ID, chunk]);
625 ProcessChunkSend(nc
^);
627 NTF_CLIENT_MAP_REQUEST
:
629 e_LogWritefln('client #%d requested map info', [nc
.ID
]);
631 dfn
:= findDiskWad(MapsDir
+gGameSettings
.WAD
);
632 if (dfn
= '') then dfn
:= '!wad_not_found!.wad'; //FIXME
633 //md5 := MD5File(dfn);
635 if (not GetDiskFileInfo(dfn
, fi
)) then
637 e_LogWritefln('client #%d requested map info, but i cannot get file info', [nc
.ID
]);
643 st := openDiskFileRO(dfn);
644 if not assigned(st) then exit; //wtf?!
649 trans_omsg
.Write(Byte(NTF_SERVER_MAP_INFO
));
651 trans_omsg
.Write(gGameSettings
.WAD
);
653 trans_omsg
.Write(md5
);
655 trans_omsg
.Write(size
);
656 // number of external resources for map
657 trans_omsg
.Write(LongInt(length(gExternalResources
)));
658 // external resource names
659 for f
:= 0 to High(gExternalResources
) do
662 //trans_omsg.Write(ExtractFileName(gExternalResources[f])); // GameDir+'/wads/'+ResList.Strings[i]
664 trans_omsg
.Write('!');
665 trans_omsg
.Write(LongInt(gExternalResources
[f
].size
));
666 trans_omsg
.Write(gExternalResources
[f
].hash
);
667 trans_omsg
.Write(ExtractFileName(gExternalResources
[f
].diskName
));
670 if not ftransSendServerMsg(nc
^, trans_omsg
) then exit
;
681 //**************************************************************************
683 // file transfer crap (both client and server)
685 //**************************************************************************
687 function getNewTimeoutEnd (): Int64;
689 result
:= GetTimerMS();
690 if (g_Net_DownloadTimeout
<= 0) then
692 result
:= result
+1000*60*3; // 3 minutes
696 result
:= result
+trunc(g_Net_DownloadTimeout
*1000);
701 // send map request to server, and wait for "map info" server reply
703 // returns `false` on error or user abort
705 // diskName: map wad file name (without a path)
706 // hash: map wad hash
707 // size: map wad size
708 // chunkSize: set too
709 // resList: list of resource wads
715 // for maps, first `tf.diskName` name will be map wad name, and `tf.hash`/`tf.size` will contain map info
716 function g_Net_Wait_MapInfo (var tf
: TNetFileTransfer
; var resList
: TNetMapResourceInfoArray
): Integer;
722 freePacket
: Boolean = false;
727 ri
: ^TNetMapResourceInfo
;
729 SetLength(resList
, 0);
733 trans_omsg
.Write(Byte(NTF_CLIENT_MAP_REQUEST
));
734 if not ftransSendClientMsg(trans_omsg
) then begin result
:= -1; exit
; end;
736 FillChar(ev
, SizeOf(ev
), 0);
739 ett
:= getNewTimeoutEnd();
741 status
:= enet_host_service(NetHost
, @ev
, 300);
744 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' network error', True);
754 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' timeout reached', True);
763 ENET_EVENT_TYPE_RECEIVE
:
766 if (ev
.channelID
<> NET_CHAN_DOWNLOAD_EX
) then
768 //e_LogWritefln('g_Net_Wait_MapInfo: skip message from non-transfer channel', []);
770 g_Net_Client_HandlePacket(ev
.packet
, g_Net_ClientLightMsgHandler
);
771 if (g_Res_received_map_start
< 0) then begin result
:= -666; exit
; end;
775 ett
:= getNewTimeoutEnd();
776 if (ev
.packet
.dataLength
< 1) then
778 e_LogWritefln('g_Net_Wait_MapInfo: invalid server packet (no data)', []);
782 Ptr
:= ev
.packet
^.data
;
783 rMsgId
:= Byte(Ptr
^);
784 e_LogWritefln('g_Net_Wait_MapInfo: got message %u from server (dataLength=%u)', [rMsgId
, ev
.packet
^.dataLength
]);
785 if (rMsgId
= NTF_SERVER_FILE_INFO
) then
787 e_LogWritefln('g_Net_Wait_MapInfo: waiting for map info reply, but got file info reply', []);
791 else if (rMsgId
= NTF_SERVER_ABORT
) then
793 e_LogWritefln('g_Net_Wait_MapInfo: server aborted transfer', []);
797 else if (rMsgId
= NTF_SERVER_MAP_INFO
) then
799 e_LogWritefln('g_Net_Wait_MapInfo: creating map info packet...', []);
800 if not msg
.Init(ev
.packet
^.data
+1, ev
.packet
^.dataLength
-1, True) then exit
;
801 e_LogWritefln('g_Net_Wait_MapInfo: parsing map info packet (rd=%d; max=%d)...', [msg
.ReadCount
, msg
.MaxSize
]);
802 SetLength(resList
, 0); // just in case
804 tf
.diskName
:= msg
.ReadString();
805 e_LogWritefln('g_Net_Wait_MapInfo: map wad is `%s`', [tf
.diskName
]);
807 tf
.hash
:= msg
.ReadMD5();
809 tf
.size
:= msg
.ReadLongInt();
810 e_LogWritefln('g_Net_Wait_MapInfo: map wad size is %d', [tf
.size
]);
811 // number of external resources for map
812 rc
:= msg
.ReadLongInt();
813 if (rc
< 0) or (rc
> 1024) then
815 e_LogWritefln('g_Net_Wait_Event: invalid number of map external resources (%d)', [rc
]);
819 e_LogWritefln('g_Net_Wait_MapInfo: map external resource count is %d', [rc
]);
820 SetLength(resList
, rc
);
821 // external resource names
822 for f
:= 0 to rc
-1 do
825 s
:= msg
.ReadString();
826 if (length(s
) = 0) then begin result
:= -1; exit
; end;
830 ri
.size
:= msg
.ReadLongInt();
831 ri
.hash
:= msg
.ReadMD5();
832 ri
.wadName
:= ExtractFileName(msg
.ReadString());
833 if (length(ri
.wadName
) = 0) or (ri
.size
< 0) then begin result
:= -1; exit
; end;
837 // old-style packet, only name
838 ri
.wadName
:= ExtractFileName(s
);
839 if (length(ri
.wadName
) = 0) then begin result
:= -1; exit
; end;
840 ri
.size
:= -1; // unknown
843 e_LogWritefln('g_Net_Wait_MapInfo: got map info', []);
844 Result
:= 0; // success
849 e_LogWritefln('g_Net_Wait_Event: invalid server packet type', []);
855 ENET_EVENT_TYPE_DISCONNECT
:
857 if (ev
.data
<= NET_DISC_MAX
) then
858 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' ' + _lc
[TStrings_Locale(Cardinal(I_NET_DISC_NONE
) + ev
.data
)], True);
864 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' unknown ENet event ' + IntToStr(Ord(ev
.kind
)), True);
869 if (freePacket
) then begin freePacket
:= false; enet_packet_destroy(ev
.packet
); end;
872 if g_Net_UserRequestExit() then
874 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' user abort', True);
880 if (freePacket
) then enet_packet_destroy(ev
.packet
);
885 // send file request to server, and wait for server reply
887 // returns `false` on error or user abort
889 // diskName (actually, base name)
898 // for maps, first `tf.diskName` name will be map wad name, and `tf.hash`/`tf.size` will contain map info
899 function g_Net_RequestResFileInfo (resIndex
: LongInt; out tf
: TNetFileTransfer
): Integer;
905 freePacket
: Boolean = false;
911 trans_omsg
.Write(Byte(NTF_CLIENT_FILE_REQUEST
));
912 trans_omsg
.Write(resIndex
);
913 if not ftransSendClientMsg(trans_omsg
) then begin result
:= -1; exit
; end;
915 FillChar(ev
, SizeOf(ev
), 0);
918 ett
:= getNewTimeoutEnd();
920 status
:= enet_host_service(NetHost
, @ev
, 300);
923 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' network error', True);
933 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' timeout reached', True);
942 ENET_EVENT_TYPE_RECEIVE
:
945 if (ev
.channelID
<> NET_CHAN_DOWNLOAD_EX
) then
947 //e_LogWriteln('g_Net_Wait_Event: skip message from non-transfer channel');
949 g_Net_Client_HandlePacket(ev
.packet
, g_Net_ClientLightMsgHandler
);
950 if (g_Res_received_map_start
< 0) then begin result
:= -666; exit
; end;
954 ett
:= getNewTimeoutEnd();
955 if (ev
.packet
.dataLength
< 1) then
957 e_LogWriteln('g_Net_Wait_Event: invalid server packet (no data)');
961 Ptr
:= ev
.packet
^.data
;
962 rMsgId
:= Byte(Ptr
^);
963 e_LogWritefln('received transfer packet with id %d (%u bytes)', [rMsgId
, ev
.packet
^.dataLength
]);
964 if (rMsgId
= NTF_SERVER_FILE_INFO
) then
966 if not msg
.Init(ev
.packet
^.data
+1, ev
.packet
^.dataLength
-1, True) then exit
;
967 tf
.hash
:= msg
.ReadMD5();
968 tf
.size
:= msg
.ReadLongInt();
969 tf
.chunkSize
:= msg
.ReadLongInt();
970 tf
.diskName
:= ExtractFileName(msg
.readString());
971 if (tf
.size
< 0) or (tf
.chunkSize
<> FILE_CHUNK_SIZE
) or (length(tf
.diskName
) = 0) then
973 e_LogWritefln('g_Net_RequestResFileInfo: invalid file info packet', []);
977 e_LogWritefln('got file info for resource #%d: size=%d; name=%s', [resIndex
, tf
.size
, tf
.diskName
]);
978 Result
:= 0; // success
981 else if (rMsgId
= NTF_SERVER_ABORT
) then
983 e_LogWriteln('g_Net_RequestResFileInfo: server aborted transfer');
987 else if (rMsgId
= NTF_SERVER_MAP_INFO
) then
989 e_LogWriteln('g_Net_RequestResFileInfo: waiting for map info reply, but got file info reply');
995 e_LogWriteln('g_Net_RequestResFileInfo: invalid server packet type');
1001 ENET_EVENT_TYPE_DISCONNECT
:
1003 if (ev
.data
<= NET_DISC_MAX
) then
1004 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' ' + _lc
[TStrings_Locale(Cardinal(I_NET_DISC_NONE
) + ev
.data
)], True);
1010 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' unknown ENet event ' + IntToStr(Ord(ev
.kind
)), True);
1015 if (freePacket
) then begin freePacket
:= false; enet_packet_destroy(ev
.packet
); end;
1018 if g_Net_UserRequestExit() then
1020 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' user abort', True);
1026 if (freePacket
) then enet_packet_destroy(ev
.packet
);
1031 // call this to cancel file transfer requested by `g_Net_RequestResFileInfo()`
1032 function g_Net_AbortResTransfer (var tf
: TNetFileTransfer
): Boolean;
1035 e_LogWritefln('aborting file transfer...', []);
1038 trans_omsg
.Write(Byte(NTF_CLIENT_ABORT
));
1039 result
:= ftransSendClientMsg(trans_omsg
);
1040 if result
then enet_host_flush(NetHost
);
1044 // call this to start file transfer requested by `g_Net_RequestResFileInfo()`
1046 // returns `false` on error or user abort
1055 // 2 on server abort
1056 // for maps, first `tf.diskName` name will be map wad name, and `tf.hash`/`tf.size` will contain map info
1057 function g_Net_ReceiveResourceFile (resIndex
: LongInt; var tf
: TNetFileTransfer
; strm
: TStream
): Integer;
1063 freePacket
: Boolean = false;
1066 nextChunk
: Integer = 0;
1067 chunkTotal
: Integer;
1074 tf
.resumed
:= false;
1075 e_LogWritefln('file `%s`, size=%d (%d)', [tf
.diskName
, Integer(strm
.size
), tf
.size
], TMsgType
.Notify
);
1076 // check if we should resume downloading
1077 resumed
:= (strm
.size
> tf
.chunkSize
) and (strm
.size
< tf
.size
);
1080 trans_omsg
.Write(Byte(NTF_CLIENT_START
));
1081 if resumed
then chunk
:= strm
.size
div tf
.chunkSize
else chunk
:= 0;
1082 trans_omsg
.Write(LongInt(chunk
));
1083 if not ftransSendClientMsg(trans_omsg
) then begin result
:= -1; exit
; end;
1085 strm
.Seek(chunk
*tf
.chunkSize
, soFromBeginning
);
1086 chunkTotal
:= (tf
.size
+tf
.chunkSize
-1) div tf
.chunkSize
;
1087 e_LogWritefln('receiving file `%s` (%d chunks)', [tf
.diskName
, chunkTotal
], TMsgType
.Notify
);
1088 g_Game_SetLoadingText('downloading "'+ExtractFileName(tf
.diskName
)+'"', chunkTotal
, False);
1089 tf
.resumed
:= resumed
;
1091 if (chunk
> 0) then g_Game_StepLoading(chunk
);
1094 // wait for reply data
1095 FillChar(ev
, SizeOf(ev
), 0);
1097 GetMem(buf
, tf
.chunkSize
);
1099 ett
:= getNewTimeoutEnd();
1101 //stx := -GetTimerMS();
1102 status
:= enet_host_service(NetHost
, @ev
, 300);
1103 if (status
< 0) then
1105 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' network error', True);
1109 if (status
= 0) then
1111 // check for timeout
1115 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' timeout reached', True);
1124 ENET_EVENT_TYPE_RECEIVE
:
1127 if (ev
.channelID
<> NET_CHAN_DOWNLOAD_EX
) then
1129 //e_LogWritefln('g_Net_Wait_Event: skip message from non-transfer channel', []);
1130 freePacket
:= false;
1131 g_Net_Client_HandlePacket(ev
.packet
, g_Net_ClientLightMsgHandler
);
1132 if (g_Res_received_map_start
< 0) then begin result
:= -666; exit
; end;
1136 //stx := stx+GetTimerMS();
1137 //e_LogWritefln('g_Net_ReceiveResourceFile: stx=%d', [Integer(stx)]);
1138 //stx := -GetTimerMS();
1139 ett
:= getNewTimeoutEnd();
1140 if (ev
.packet
.dataLength
< 1) then
1142 e_LogWritefln('g_Net_ReceiveResourceFile: invalid server packet (no data)', []);
1146 Ptr
:= ev
.packet
^.data
;
1147 rMsgId
:= Byte(Ptr
^);
1148 if (rMsgId
= NTF_SERVER_DONE
) then
1150 e_LogWritefln('file transfer complete.', []);
1154 else if (rMsgId
= NTF_SERVER_CHUNK
) then
1156 if not msg
.Init(ev
.packet
^.data
+1, ev
.packet
^.dataLength
-1, True) then exit
;
1157 chunk
:= msg
.ReadLongInt();
1158 csize
:= msg
.ReadLongInt();
1159 if (chunk
<> nextChunk
) then
1161 e_LogWritefln('received chunk %d, but expected chunk %d', [chunk
, nextChunk
]);
1165 if (csize
< 0) or (csize
> tf
.chunkSize
) then
1167 e_LogWritefln('received chunk with size %d, but expected chunk size is %d', [csize
, tf
.chunkSize
]);
1171 //e_LogWritefln('got chunk #%d of #%d (csize=%d)', [chunk, (tf.size+tf.chunkSize-1) div tf.chunkSize, csize]);
1172 msg
.ReadData(buf
, csize
);
1173 strm
.WriteBuffer(buf
^, csize
);
1174 nextChunk
:= chunk
+1;
1175 g_Game_StepLoading();
1178 trans_omsg
.Write(Byte(NTF_CLIENT_ACK
));
1179 trans_omsg
.Write(LongInt(chunk
));
1180 if not ftransSendClientMsg(trans_omsg
) then begin result
:= -1; exit
; end;
1182 else if (rMsgId
= NTF_SERVER_ABORT
) then
1184 e_LogWritefln('g_Net_ReceiveResourceFile: server aborted transfer', []);
1190 e_LogWritefln('g_Net_ReceiveResourceFile: invalid server packet type', []);
1194 //stx := stx+GetTimerMS();
1195 //e_LogWritefln('g_Net_ReceiveResourceFile: process stx=%d', [Integer(stx)]);
1198 ENET_EVENT_TYPE_DISCONNECT
:
1200 if (ev
.data
<= NET_DISC_MAX
) then
1201 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' ' + _lc
[TStrings_Locale(Cardinal(I_NET_DISC_NONE
) + ev
.data
)], True);
1207 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' unknown ENet event ' + IntToStr(Ord(ev
.kind
)), True);
1212 if (freePacket
) then begin freePacket
:= false; enet_packet_destroy(ev
.packet
); end;
1215 if g_Net_UserRequestExit() then
1217 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' user abort', True);
1224 if (freePacket
) then enet_packet_destroy(ev
.packet
);
1229 //**************************************************************************
1233 //**************************************************************************
1235 function g_Net_FindSlot(): Integer;
1244 for I
:= Low(NetClients
) to High(NetClients
) do
1246 if NetClients
[I
].Used
then
1255 if C
>= NetMaxClients
then
1263 if (Length(NetClients
) >= NetMaxClients
) then
1267 SetLength(NetClients
, Length(NetClients
) + 1);
1268 N
:= High(NetClients
);
1274 NetClients
[N
].Used
:= True;
1275 NetClients
[N
].ID
:= N
;
1276 NetClients
[N
].RequestedFullUpdate
:= False;
1277 NetClients
[N
].RCONAuth
:= False;
1278 NetClients
[N
].Voted
:= False;
1279 NetClients
[N
].Player
:= 0;
1280 clearNetClientTransfers(NetClients
[N
]); // just in case
1286 function g_Net_Init(): Boolean;
1294 NetBuf
[NET_UNRELIABLE
].Clear();
1295 NetBuf
[NET_RELIABLE
].Clear();
1296 //SetLength(NetClients, 0);
1297 clearNetClients(true); // clear array
1303 NetAddr
.port
:= 25666;
1304 SetLength(NetBannedHosts
, 0);
1305 if FileExists(DataDir
+ BANLIST_FILENAME
) then
1307 Assign(F
, DataDir
+ BANLIST_FILENAME
);
1312 if StrToIp(IPstr
, IP
) then
1316 g_Net_SaveBanList();
1319 Result
:= (enet_initialize() = 0);
1322 procedure g_Net_Flush();
1326 F
, Chan
: enet_uint32
;
1330 Chan
:= NET_CHAN_GAME
;
1332 if NetMode
= NET_SERVER
then
1333 for T
:= NET_UNRELIABLE
to NET_RELIABLE
do
1335 if NetBuf
[T
].CurSize
> 0 then
1337 P
:= enet_packet_create(NetBuf
[T
].Data
, NetBuf
[T
].CurSize
, F
);
1338 if not Assigned(P
) then continue
;
1339 enet_host_broadcast(NetHost
, Chan
, P
);
1343 for I
:= Low(NetClients
) to High(NetClients
) do
1345 if not NetClients
[I
].Used
then continue
;
1346 if NetClients
[I
].NetOut
[T
].CurSize
<= 0 then continue
;
1347 P
:= enet_packet_create(NetClients
[I
].NetOut
[T
].Data
, NetClients
[I
].NetOut
[T
].CurSize
, F
);
1348 if not Assigned(P
) then continue
;
1349 enet_peer_send(NetClients
[I
].Peer
, Chan
, P
);
1350 NetClients
[I
].NetOut
[T
].Clear();
1353 // next and last iteration is always RELIABLE
1354 F
:= LongWord(ENET_PACKET_FLAG_RELIABLE
);
1355 Chan
:= NET_CHAN_IMPORTANT
;
1357 else if NetMode
= NET_CLIENT
then
1358 for T
:= NET_UNRELIABLE
to NET_RELIABLE
do
1360 if NetBuf
[T
].CurSize
> 0 then
1362 P
:= enet_packet_create(NetBuf
[T
].Data
, NetBuf
[T
].CurSize
, F
);
1363 if not Assigned(P
) then continue
;
1364 enet_peer_send(NetPeer
, Chan
, P
);
1367 // next and last iteration is always RELIABLE
1368 F
:= LongWord(ENET_PACKET_FLAG_RELIABLE
);
1369 Chan
:= NET_CHAN_IMPORTANT
;
1373 procedure g_Net_Cleanup();
1377 NetBuf
[NET_UNRELIABLE
].Clear();
1378 NetBuf
[NET_RELIABLE
].Clear();
1380 //SetLength(NetClients, 0);
1381 clearNetClients(true); // clear array
1382 NetClientCount
:= 0;
1391 NetState
:= NET_STATE_NONE
;
1393 NetPongSock
:= ENET_SOCKET_NULL
;
1395 NetTimeToMaster
:= 0;
1396 NetTimeToUpdate
:= 0;
1397 NetTimeToReliable
:= 0;
1399 NetMode
:= NET_NONE
;
1401 if NetPortThread
<> NilThreadId
then
1402 WaitForThreadTerminate(NetPortThread
, 66666);
1404 NetPortThread
:= NilThreadId
;
1405 g_Net_UnforwardPorts();
1411 procedure g_Net_Free();
1415 enet_deinitialize();
1416 NetInitDone
:= False;
1420 //**************************************************************************
1424 //**************************************************************************
1426 function ForwardThread(Param
: Pointer): PtrInt
;
1429 if not g_Net_ForwardPorts() then Result
:= -1;
1432 function g_Net_Host(IPAddr
: LongWord; Port
: enet_uint16
; MaxClients
: Cardinal = 16): Boolean;
1434 if NetMode
<> NET_NONE
then
1436 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_INGAME
]);
1443 g_Console_Add(_lc
[I_NET_MSG
] + Format(_lc
[I_NET_MSG_HOST
], [Port
]));
1444 if not NetInitDone
then
1446 if (not g_Net_Init()) then
1448 g_Console_Add(_lc
[I_NET_MSG_FERROR
] + _lc
[I_NET_ERR_ENET
]);
1453 NetInitDone
:= True;
1456 NetAddr
.host
:= IPAddr
;
1457 NetAddr
.port
:= Port
;
1459 if NetForwardPorts
then NetPortThread
:= BeginThread(ForwardThread
);
1461 NetHost
:= enet_host_create(@NetAddr
, NET_MAXCLIENTS
, NET_CHANS
, 0, 0);
1463 if (NetHost
= nil) then
1465 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + Format(_lc
[I_NET_ERR_HOST
], [Port
]));
1471 NetPongSock
:= enet_socket_create(ENET_SOCKET_TYPE_DATAGRAM
);
1472 if NetPongSock
<> ENET_SOCKET_NULL
then
1474 NetPongAddr
.host
:= IPAddr
;
1475 NetPongAddr
.port
:= NET_PING_PORT
;
1476 if enet_socket_bind(NetPongSock
, @NetPongAddr
) < 0 then
1478 enet_socket_destroy(NetPongSock
);
1479 NetPongSock
:= ENET_SOCKET_NULL
;
1482 enet_socket_set_option(NetPongSock
, ENET_SOCKOPT_NONBLOCK
, 1);
1485 NetMode
:= NET_SERVER
;
1487 NetBuf
[NET_UNRELIABLE
].Clear();
1488 NetBuf
[NET_RELIABLE
].Clear();
1494 procedure g_Net_Host_Die();
1498 if NetMode
<> NET_SERVER
then Exit
;
1500 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_HOST_DISCALL
]);
1501 for I
:= 0 to High(NetClients
) do
1502 if NetClients
[I
].Used
then
1503 enet_peer_disconnect(NetClients
[I
].Peer
, NET_DISC_DOWN
);
1505 while enet_host_service(NetHost
, @NetEvent
, 1000) > 0 do
1506 if NetEvent
.kind
= ENET_EVENT_TYPE_RECEIVE
then
1507 enet_packet_destroy(NetEvent
.packet
);
1509 for I
:= 0 to High(NetClients
) do
1510 if NetClients
[I
].Used
then
1512 FreeMemory(NetClients
[I
].Peer
^.data
);
1513 NetClients
[I
].Peer
^.data
:= nil;
1514 enet_peer_reset(NetClients
[I
].Peer
);
1515 NetClients
[I
].Peer
:= nil;
1516 NetClients
[I
].Used
:= False;
1517 NetClients
[I
].NetOut
[NET_UNRELIABLE
].Free();
1518 NetClients
[I
].NetOut
[NET_RELIABLE
].Free();
1521 clearNetClients(false); // don't clear array
1522 if (NetMPeer
<> nil) and (NetMHost
<> nil) then g_Net_Slist_Disconnect
;
1523 if NetPongSock
<> ENET_SOCKET_NULL
then
1524 enet_socket_destroy(NetPongSock
);
1526 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_HOST_DIE
]);
1527 enet_host_destroy(NetHost
);
1529 NetMode
:= NET_NONE
;
1532 e_WriteLog('NET: Server stopped', TMsgType
.Notify
);
1536 procedure g_Net_Host_Send(ID
: Integer; Reliable
: Boolean; Chan
: Byte = NET_CHAN_GAME
);
1543 T
:= NET_UNRELIABLE
;
1547 if ID
> High(NetClients
) then Exit
;
1548 if NetClients
[ID
].Peer
= nil then Exit
;
1550 NetClients
[ID
].NetOut
[T
].Write(Integer(NetOut
.CurSize
));
1551 NetClients
[ID
].NetOut
[T
].Write(NetOut
);
1556 NetBuf
[T
].Write(Integer(NetOut
.CurSize
));
1557 NetBuf
[T
].Write(NetOut
);
1560 if NetDump
then g_Net_DumpSendBuffer();
1564 procedure g_Net_Host_CheckPings();
1566 ClAddr
: ENetAddress
;
1570 Ping
: array [0..9] of Byte;
1573 if NetPongSock
= ENET_SOCKET_NULL
then Exit
;
1575 Buf
.data
:= Addr(Ping
[0]);
1576 Buf
.dataLength
:= 2+8;
1580 Len
:= enet_socket_receive(NetPongSock
, @ClAddr
, @Buf
, 1);
1581 if Len
< 0 then Exit
;
1583 if (Ping
[0] = Ord('D')) and (Ping
[1] = Ord('F')) then
1585 ClTime
:= Int64(Addr(Ping
[2])^);
1588 NetOut
.Write(Byte(Ord('D')));
1589 NetOut
.Write(Byte(Ord('F')));
1590 NetOut
.Write(NetPort
);
1591 NetOut
.Write(ClTime
);
1592 g_Net_Slist_WriteInfo();
1594 if gPlayer1
<> nil then Inc(NPl
);
1595 if gPlayer2
<> nil then Inc(NPl
);
1597 NetOut
.Write(gNumBots
);
1599 Buf
.data
:= NetOut
.Data
;
1600 Buf
.dataLength
:= NetOut
.CurSize
;
1601 enet_socket_send(NetPongSock
, @ClAddr
, @Buf
, 1);
1608 function g_Net_Host_Update(): enet_size_t
;
1619 if NetUseMaster
then g_Net_Slist_Check
;
1620 g_Net_Host_CheckPings
;
1622 while (enet_host_service(NetHost
, @NetEvent
, 0) > 0) do
1624 case (NetEvent
.kind
) of
1625 ENET_EVENT_TYPE_CONNECT
:
1627 IP
:= IpToStr(NetEvent
.Peer
^.address
.host
);
1628 Port
:= NetEvent
.Peer
^.address
.port
;
1629 g_Console_Add(_lc
[I_NET_MSG
] +
1630 Format(_lc
[I_NET_MSG_HOST_CONN
], [IP
, Port
]));
1632 if (NetEvent
.data
<> NET_PROTOCOL_VER
) then
1634 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_HOST_REJECT
] +
1635 _lc
[I_NET_DISC_PROTOCOL
]);
1636 NetEvent
.peer
^.data
:= GetMemory(SizeOf(Byte));
1637 Byte(NetEvent
.peer
^.data
^) := 255;
1638 enet_peer_disconnect(NetEvent
.peer
, NET_DISC_PROTOCOL
);
1639 enet_host_flush(NetHost
);
1643 ID
:= g_Net_FindSlot();
1647 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_HOST_REJECT
] +
1648 _lc
[I_NET_DISC_FULL
]);
1649 NetEvent
.Peer
^.data
:= GetMemory(SizeOf(Byte));
1650 Byte(NetEvent
.peer
^.data
^) := 255;
1651 enet_peer_disconnect(NetEvent
.peer
, NET_DISC_FULL
);
1652 enet_host_flush(NetHost
);
1656 NetClients
[ID
].Peer
:= NetEvent
.peer
;
1657 NetClients
[ID
].Peer
^.data
:= GetMemory(SizeOf(Byte));
1658 Byte(NetClients
[ID
].Peer
^.data
^) := ID
;
1659 NetClients
[ID
].State
:= NET_STATE_AUTH
;
1660 NetClients
[ID
].RCONAuth
:= False;
1661 NetClients
[ID
].NetOut
[NET_UNRELIABLE
].Alloc(NET_BUFSIZE
*2);
1662 NetClients
[ID
].NetOut
[NET_RELIABLE
].Alloc(NET_BUFSIZE
*2);
1663 clearNetClientTransfers(NetClients
[ID
]); // just in case
1665 enet_peer_timeout(NetEvent
.peer
, ENET_PEER_TIMEOUT_LIMIT
* 2, ENET_PEER_TIMEOUT_MINIMUM
* 2, ENET_PEER_TIMEOUT_MAXIMUM
* 2);
1667 Inc(NetClientCount
);
1668 g_Console_Add(_lc
[I_NET_MSG
] + Format(_lc
[I_NET_MSG_HOST_ADD
], [ID
]));
1671 ENET_EVENT_TYPE_RECEIVE
:
1673 //e_LogWritefln('RECEIVE: chan=%u', [NetEvent.channelID]);
1674 if (NetEvent
.channelID
= NET_CHAN_DOWNLOAD_EX
) then
1676 ProcessDownloadExPacket();
1680 ID
:= Byte(NetEvent
.peer
^.data
^);
1681 if ID
> High(NetClients
) then Exit
;
1682 TC
:= @NetClients
[ID
];
1684 if NetDump
then g_Net_DumpRecvBuffer(NetEvent
.packet
^.data
, NetEvent
.packet
^.dataLength
);
1685 g_Net_Host_HandlePacket(TC
, NetEvent
.packet
, g_Net_HostMsgHandler
);
1689 ENET_EVENT_TYPE_DISCONNECT
:
1691 ID
:= Byte(NetEvent
.peer
^.data
^);
1692 if ID
> High(NetClients
) then Exit
;
1693 clearNetClient(NetClients
[ID
]);
1694 TC
:= @NetClients
[ID
];
1695 if TC
= nil then Exit
;
1697 if not (TC
^.Used
) then Exit
;
1699 TP
:= g_Player_Get(TC
^.Player
);
1704 TP
.Kill(K_SIMPLEKILL
, 0, HIT_DISCON
);
1705 g_Console_Add(Format(_lc
[I_PLAYER_LEAVE
], [TP
.Name
]), True);
1706 e_WriteLog('NET: Client ' + TP
.Name
+ ' [' + IntToStr(ID
) + '] disconnected.', TMsgType
.Notify
);
1707 g_Player_Remove(TP
.UID
);
1711 TC
^.State
:= NET_STATE_NONE
;
1714 TC
^.RequestedFullUpdate
:= False;
1715 TC
^.NetOut
[NET_UNRELIABLE
].Free();
1716 TC
^.NetOut
[NET_RELIABLE
].Free();
1718 FreeMemory(NetEvent
.peer
^.data
);
1719 NetEvent
.peer
^.data
:= nil;
1720 g_Console_Add(_lc
[I_NET_MSG
] + Format(_lc
[I_NET_MSG_HOST_DISC
], [ID
]));
1721 Dec(NetClientCount
);
1723 if NetUseMaster
then g_Net_Slist_Update
;
1730 //**************************************************************************
1734 //**************************************************************************
1736 procedure g_Net_Disconnect(Forced
: Boolean = False);
1738 if NetMode
<> NET_CLIENT
then Exit
;
1739 if (NetHost
= nil) or (NetPeer
= nil) then Exit
;
1743 enet_peer_disconnect(NetPeer
, NET_DISC_NONE
);
1745 while (enet_host_service(NetHost
, @NetEvent
, 1500) > 0) do
1747 if (NetEvent
.kind
= ENET_EVENT_TYPE_DISCONNECT
) then
1753 if (NetEvent
.kind
= ENET_EVENT_TYPE_RECEIVE
) then
1754 enet_packet_destroy(NetEvent
.packet
);
1757 if NetPeer
<> nil then
1759 enet_peer_reset(NetPeer
);
1765 e_WriteLog('NET: Kicked from server: ' + IntToStr(NetEvent
.data
), TMsgType
.Notify
);
1766 if (NetEvent
.data
<= NET_DISC_MAX
) then
1767 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_KICK
] +
1768 _lc
[TStrings_Locale(Cardinal(I_NET_DISC_NONE
) + NetEvent
.data
)], True);
1771 if NetHost
<> nil then
1773 enet_host_destroy(NetHost
);
1776 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_CLIENT_DISC
]);
1779 e_WriteLog('NET: Disconnected', TMsgType
.Notify
);
1782 procedure g_Net_Client_Send(Reliable
: Boolean; Chan
: Byte = NET_CHAN_GAME
);
1789 T
:= NET_UNRELIABLE
;
1792 NetBuf
[T
].Write(Integer(NetOut
.CurSize
));
1793 NetBuf
[T
].Write(NetOut
);
1795 if NetDump
then g_Net_DumpSendBuffer();
1797 g_Net_Flush(); // FIXME: for now, send immediately
1800 function g_Net_Client_Update(): enet_size_t
;
1803 while (enet_host_service(NetHost
, @NetEvent
, 0) > 0) do
1805 case NetEvent
.kind
of
1806 ENET_EVENT_TYPE_RECEIVE
:
1808 if (NetEvent
.channelID
= NET_CHAN_DOWNLOAD_EX
) then continue
; // ignore all download packets, they're processed by separate code
1809 if NetDump
then g_Net_DumpRecvBuffer(NetEvent
.packet
^.data
, NetEvent
.packet
^.dataLength
);
1810 g_Net_Client_HandlePacket(NetEvent
.packet
, g_Net_ClientMsgHandler
);
1813 ENET_EVENT_TYPE_DISCONNECT
:
1815 g_Net_Disconnect(True);
1823 function g_Net_Client_UpdateWhileLoading(): enet_size_t
;
1826 while (enet_host_service(NetHost
, @NetEvent
, 0) > 0) do
1828 case NetEvent
.kind
of
1829 ENET_EVENT_TYPE_RECEIVE
:
1831 if (NetEvent
.channelID
= NET_CHAN_DOWNLOAD_EX
) then continue
; // ignore all download packets, they're processed by separate code
1832 if NetDump
then g_Net_DumpRecvBuffer(NetEvent
.packet
^.data
, NetEvent
.packet
^.dataLength
);
1833 g_Net_Client_HandlePacket(NetEvent
.packet
, g_Net_ClientLightMsgHandler
);
1836 ENET_EVENT_TYPE_DISCONNECT
:
1838 g_Net_Disconnect(True);
1847 function g_Net_Connect(IP
: string; Port
: enet_uint16
): Boolean;
1850 TimeoutTime
, T
: Int64;
1852 if NetMode
<> NET_NONE
then
1854 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_ERR_INGAME
], True);
1861 g_Console_Add(_lc
[I_NET_MSG
] + Format(_lc
[I_NET_MSG_CLIENT_CONN
],
1863 if not NetInitDone
then
1865 if (not g_Net_Init()) then
1867 g_Console_Add(_lc
[I_NET_MSG_FERROR
] + _lc
[I_NET_ERR_ENET
], True);
1872 NetInitDone
:= True;
1875 NetHost
:= enet_host_create(nil, 1, NET_CHANS
, 0, 0);
1877 if (NetHost
= nil) then
1879 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CLIENT
], True);
1885 enet_address_set_host(@NetAddr
, PChar(Addr(IP
[1])));
1886 NetAddr
.port
:= Port
;
1888 NetPeer
:= enet_host_connect(NetHost
, @NetAddr
, NET_CHANS
, NET_PROTOCOL_VER
);
1890 if (NetPeer
= nil) then
1892 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CLIENT
], True);
1893 enet_host_destroy(NetHost
);
1899 // предупредить что ждем слишком долго через N секунд
1900 TimeoutTime
:= GetTimer() + NET_CONNECT_TIMEOUT
;
1905 while (enet_host_service(NetHost
, @NetEvent
, 0) > 0) do
1907 if (NetEvent
.kind
= ENET_EVENT_TYPE_CONNECT
) then
1909 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_CLIENT_DONE
]);
1910 NetMode
:= NET_CLIENT
;
1912 enet_peer_timeout(NetPeer
, ENET_PEER_TIMEOUT_LIMIT
* 2, ENET_PEER_TIMEOUT_MINIMUM
* 2, ENET_PEER_TIMEOUT_MAXIMUM
* 2);
1914 NetClientPort
:= Port
;
1922 if T
> TimeoutTime
then
1924 TimeoutTime
:= T
+ NET_CONNECT_TIMEOUT
* 100; // одного предупреждения хватит
1925 g_Console_Add(_lc
[I_NET_MSG_TIMEOUT_WARN
], True);
1926 g_Console_Add(Format(_lc
[I_NET_MSG_PORTS
], [Integer(Port
), Integer(NET_PING_PORT
)]), True);
1929 ProcessLoading(true);
1931 if e_KeyPressed(IK_SPACE
) or e_KeyPressed(IK_ESCAPE
) or e_KeyPressed(VK_ESCAPE
) or
1932 e_KeyPressed(JOY0_JUMP
) or e_KeyPressed(JOY1_JUMP
) or e_KeyPressed(JOY2_JUMP
) or e_KeyPressed(JOY3_JUMP
) then
1936 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_TIMEOUT
], True);
1937 g_Console_Add(Format(_lc
[I_NET_MSG_PORTS
], [Integer(Port
), Integer(NET_PING_PORT
)]), True);
1938 if NetPeer
<> nil then enet_peer_reset(NetPeer
);
1939 if NetHost
<> nil then
1941 enet_host_destroy(NetHost
);
1948 function IpToStr(IP
: LongWord): string;
1953 Result
:= IntToStr(PByte(Ptr
+ 0)^) + '.';
1954 Result
:= Result
+ IntToStr(PByte(Ptr
+ 1)^) + '.';
1955 Result
:= Result
+ IntToStr(PByte(Ptr
+ 2)^) + '.';
1956 Result
:= Result
+ IntToStr(PByte(Ptr
+ 3)^);
1959 function StrToIp(IPstr
: string; var IP
: LongWord): Boolean;
1963 Result
:= enet_address_set_host(@EAddr
, PChar(@IPstr
[1])) = 0;
1967 function g_Net_Client_ByName(Name
: string): pTNetClient
;
1973 for a
:= Low(NetClients
) to High(NetClients
) do
1974 if (NetClients
[a
].Used
) and (NetClients
[a
].State
= NET_STATE_GAME
) then
1976 pl
:= g_Player_Get(NetClients
[a
].Player
);
1977 if pl
= nil then continue
;
1978 if Copy(LowerCase(pl
.Name
), 1, Length(Name
)) <> LowerCase(Name
) then continue
;
1979 if NetClients
[a
].Peer
<> nil then
1981 Result
:= @NetClients
[a
];
1987 function g_Net_Client_ByPlayer(PID
: Word): pTNetClient
;
1992 for a
:= Low(NetClients
) to High(NetClients
) do
1993 if (NetClients
[a
].Used
) and (NetClients
[a
].State
= NET_STATE_GAME
) then
1994 if NetClients
[a
].Player
= PID
then
1996 Result
:= @NetClients
[a
];
2001 function g_Net_ClientName_ByID(ID
: Integer): string;
2007 if ID
= NET_EVERYONE
then
2009 for a
:= Low(NetClients
) to High(NetClients
) do
2010 if (NetClients
[a
].ID
= ID
) and (NetClients
[a
].Used
) and (NetClients
[a
].State
= NET_STATE_GAME
) then
2012 pl
:= g_Player_Get(NetClients
[a
].Player
);
2013 if pl
= nil then Exit
;
2018 procedure g_Net_SendData(Data
: AByte
; peer
: pENetPeer
; Reliable
: Boolean; Chan
: Byte = NET_CHAN_DOWNLOAD
);
2022 dataLength
: Cardinal;
2024 dataLength
:= Length(Data
);
2027 F
:= LongWord(ENET_PACKET_FLAG_RELIABLE
)
2031 if (peer
<> nil) then
2033 P
:= enet_packet_create(@Data
[0], dataLength
, F
);
2034 if not Assigned(P
) then Exit
;
2035 enet_peer_send(peer
, Chan
, P
);
2039 P
:= enet_packet_create(@Data
[0], dataLength
, F
);
2040 if not Assigned(P
) then Exit
;
2041 enet_host_broadcast(NetHost
, Chan
, P
);
2044 enet_host_flush(NetHost
);
2047 function g_Net_IsHostBanned(IP
: LongWord; Perm
: Boolean = False): Boolean;
2052 if NetBannedHosts
= nil then
2054 for I
:= 0 to High(NetBannedHosts
) do
2055 if (NetBannedHosts
[I
].IP
= IP
) and ((not Perm
) or (NetBannedHosts
[I
].Perm
)) then
2062 procedure g_Net_BanHost(IP
: LongWord; Perm
: Boolean = True); overload
;
2068 if g_Net_IsHostBanned(IP
, Perm
) then
2072 for I
:= Low(NetBannedHosts
) to High(NetBannedHosts
) do
2073 if NetBannedHosts
[I
].IP
= 0 then
2081 SetLength(NetBannedHosts
, Length(NetBannedHosts
) + 1);
2082 P
:= High(NetBannedHosts
);
2085 NetBannedHosts
[P
].IP
:= IP
;
2086 NetBannedHosts
[P
].Perm
:= Perm
;
2089 procedure g_Net_BanHost(IP
: string; Perm
: Boolean = True); overload
;
2094 b
:= StrToIp(IP
, a
);
2096 g_Net_BanHost(a
, Perm
);
2099 procedure g_Net_UnbanNonPermHosts();
2103 if NetBannedHosts
= nil then
2105 for I
:= Low(NetBannedHosts
) to High(NetBannedHosts
) do
2106 if (NetBannedHosts
[I
].IP
> 0) and not NetBannedHosts
[I
].Perm
then
2108 NetBannedHosts
[I
].IP
:= 0;
2109 NetBannedHosts
[I
].Perm
:= True;
2113 function g_Net_UnbanHost(IP
: string): Boolean; overload
;
2117 Result
:= StrToIp(IP
, a
);
2119 Result
:= g_Net_UnbanHost(a
);
2122 function g_Net_UnbanHost(IP
: LongWord): Boolean; overload
;
2129 if NetBannedHosts
= nil then
2131 for I
:= 0 to High(NetBannedHosts
) do
2132 if NetBannedHosts
[I
].IP
= IP
then
2134 NetBannedHosts
[I
].IP
:= 0;
2135 NetBannedHosts
[I
].Perm
:= True;
2137 // no break here to clear all bans of this host, perm and non-perm
2141 procedure g_Net_SaveBanList();
2146 Assign(F
, DataDir
+ BANLIST_FILENAME
);
2148 if NetBannedHosts
<> nil then
2149 for I
:= 0 to High(NetBannedHosts
) do
2150 if NetBannedHosts
[I
].Perm
and (NetBannedHosts
[I
].IP
> 0) then
2151 Writeln(F
, IpToStr(NetBannedHosts
[I
].IP
));
2155 procedure g_Net_DumpStart();
2157 if NetMode
= NET_SERVER
then
2158 NetDumpFile
:= createDiskFile(NETDUMP_FILENAME
+ '_server')
2160 NetDumpFile
:= createDiskFile(NETDUMP_FILENAME
+ '_client');
2163 procedure g_Net_DumpSendBuffer();
2165 writeInt(NetDumpFile
, gTime
);
2166 writeInt(NetDumpFile
, LongWord(NetOut
.CurSize
));
2167 writeInt(NetDumpFile
, Byte(1));
2168 NetDumpFile
.WriteBuffer(NetOut
.Data
^, NetOut
.CurSize
);
2171 procedure g_Net_DumpRecvBuffer(Buf
: penet_uint8
; Len
: LongWord);
2173 if (Buf
= nil) or (Len
= 0) then Exit
;
2174 writeInt(NetDumpFile
, gTime
);
2175 writeInt(NetDumpFile
, Len
);
2176 writeInt(NetDumpFile
, Byte(0));
2177 NetDumpFile
.WriteBuffer(Buf
^, Len
);
2180 procedure g_Net_DumpEnd();
2186 function g_Net_ForwardPorts(ForwardPongPort
: Boolean = True): Boolean;
2187 {$IFDEF USE_MINIUPNPC}
2192 LanAddr
: array [0..255] of Char;
2193 StrPort
: AnsiString;
2198 if NetPortForwarded
= NetPort
then
2204 NetPongForwarded
:= False;
2205 NetPortForwarded
:= 0;
2207 DevList
:= upnpDiscover(1000, nil, nil, 0, 0, 2, Addr(Err
));
2208 if DevList
= nil then
2210 conwritefln('port forwarding failed: upnpDiscover() failed: %d', [Err
]);
2214 I
:= UPNP_GetValidIGD(DevList
, @Urls
, @Data
, Addr(LanAddr
[0]), 256);
2218 conwriteln('port forwarding failed: could not find an IGD device on this LAN');
2219 FreeUPNPDevList(DevList
);
2220 FreeUPNPUrls(@Urls
);
2224 StrPort
:= IntToStr(NetPort
);
2225 I
:= UPNP_AddPortMapping(
2226 Urls
.controlURL
, Addr(data
.first
.servicetype
[1]),
2227 PChar(StrPort
), PChar(StrPort
), Addr(LanAddr
[0]), PChar('D2DF'),
2228 PChar('UDP'), nil, PChar('0')
2233 conwritefln('forwarding port %d failed: error %d', [NetPort
, I
]);
2234 FreeUPNPDevList(DevList
);
2235 FreeUPNPUrls(@Urls
);
2239 if ForwardPongPort
then
2241 StrPort
:= IntToStr(NET_PING_PORT
);
2242 I
:= UPNP_AddPortMapping(
2243 Urls
.controlURL
, Addr(data
.first
.servicetype
[1]),
2244 PChar(StrPort
), PChar(StrPort
), Addr(LanAddr
[0]), PChar('D2DF'),
2245 PChar('UDP'), nil, PChar('0')
2250 conwritefln('forwarding port %d failed: error %d', [NetPort
+ 1, I
]);
2251 NetPongForwarded
:= False;
2255 conwritefln('forwarded port %d successfully', [NetPort
+ 1]);
2256 NetPongForwarded
:= True;
2260 conwritefln('forwarded port %d successfully', [NetPort
]);
2261 NetIGDControl
:= AnsiString(Urls
.controlURL
);
2262 NetIGDService
:= data
.first
.servicetype
;
2263 NetPortForwarded
:= NetPort
;
2265 FreeUPNPDevList(DevList
);
2266 FreeUPNPUrls(@Urls
);
2275 procedure g_Net_UnforwardPorts();
2276 {$IFDEF USE_MINIUPNPC}
2279 StrPort
: AnsiString;
2281 if NetPortForwarded
= 0 then Exit
;
2283 conwriteln('unforwarding ports...');
2285 StrPort
:= IntToStr(NetPortForwarded
);
2286 I
:= UPNP_DeletePortMapping(
2287 PChar(NetIGDControl
), Addr(NetIGDService
[1]),
2288 PChar(StrPort
), PChar('UDP'), nil
2290 conwritefln(' port %d: %d', [NetPortForwarded
, I
]);
2292 if NetPongForwarded
then
2294 NetPongForwarded
:= False;
2295 StrPort
:= IntToStr(NetPortForwarded
+ 1);
2296 I
:= UPNP_DeletePortMapping(
2297 PChar(NetIGDControl
), Addr(NetIGDService
[1]),
2298 PChar(StrPort
), PChar('UDP'), nil
2300 conwritefln(' port %d: %d', [NetPortForwarded
+ 1, I
]);
2303 NetPortForwarded
:= 0;
2312 conRegVar('cl_downloadtimeout', @g_Net_DownloadTimeout
, 0.0, 1000000.0, '', 'timeout in seconds, 0 to disable it');
2313 SetLength(NetClients
, 0);
2314 g_Net_DownloadTimeout
:= 60;
2315 NetIn
.Alloc(NET_BUFSIZE
);
2316 NetOut
.Alloc(NET_BUFSIZE
);
2317 NetBuf
[NET_UNRELIABLE
].Alloc(NET_BUFSIZE
*2);
2318 NetBuf
[NET_RELIABLE
].Alloc(NET_BUFSIZE
*2);
2319 trans_omsg
.Alloc(NET_BUFSIZE
);
2323 NetBuf
[NET_UNRELIABLE
].Free();
2324 NetBuf
[NET_RELIABLE
].Free();