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 TNetFileTransfer
= record
86 size
: Integer; // file size in bytes
88 lastSentChunk
: Integer;
89 lastAckChunk
: Integer;
90 lastAckTime
: Int64; // msecs; if not "in progress", we're waiting for the first ack
92 diskBuffer
: PChar; // of `chunkSize` bytes
102 RequestedFullUpdate
: Boolean;
105 Transfer
: TNetFileTransfer
; // only one transfer may be active
106 NetOut
: array [0..1] of TMsg
;
112 pTNetClient
= ^TNetClient
;
114 AByte
= array of Byte;
117 NetInitDone
: Boolean = False;
118 NetMode
: Byte = NET_NONE
;
119 NetDump
: Boolean = False;
121 NetServerName
: string = 'Unnamed Server';
122 NetPassword
: string = '';
123 NetPort
: Word = 25666;
125 NetAllowRCON
: Boolean = False;
126 NetRCONPassword
: string = '';
128 NetTimeToUpdate
: Cardinal = 0;
129 NetTimeToReliable
: Cardinal = 0;
130 NetTimeToMaster
: Cardinal = 0;
132 NetHost
: pENetHost
= nil;
133 NetPeer
: pENetPeer
= nil;
135 NetAddr
: ENetAddress
;
137 NetPongAddr
: ENetAddress
;
138 NetPongSock
: ENetSocket
= ENET_SOCKET_NULL
;
140 NetUseMaster
: Boolean = True;
141 NetSlistAddr
: ENetAddress
;
142 NetSlistIP
: string = 'mpms.doom2d.org';
143 NetSlistPort
: Word = 25665;
145 NetClientIP
: string = '127.0.0.1';
146 NetClientPort
: Word = 25666;
149 NetBuf
: array [0..1] of TMsg
;
151 NetClients
: array of TNetClient
;
152 NetClientCount
: Byte = 0;
153 NetMaxClients
: Byte = 255;
154 NetBannedHosts
: array of TBanRecord
;
156 NetState
: Integer = NET_STATE_NONE
;
158 NetMyID
: Integer = -1;
159 NetPlrUID1
: Integer = -1;
160 NetPlrUID2
: Integer = -1;
162 NetInterpLevel
: Integer = 1;
163 NetUpdateRate
: Cardinal = 0; // as soon as possible
164 NetRelupdRate
: Cardinal = 18; // around two times a second
165 NetMasterRate
: Cardinal = 60000;
167 NetForcePlayerUpdate
: Boolean = False;
168 NetPredictSelf
: Boolean = True;
169 NetForwardPorts
: Boolean = False;
171 NetGotEverything
: Boolean = False;
172 NetGotKeys
: Boolean = False;
174 {$IFDEF USE_MINIUPNPC}
175 NetPortForwarded
: Word = 0;
176 NetPongForwarded
: Boolean = False;
177 NetIGDControl
: AnsiString;
178 NetIGDService
: TURLStr
;
181 NetPortThread
: TThreadID
= NilThreadId
;
183 NetDumpFile
: TStream
;
185 g_Res_received_map_start
: Integer = 0; // set if we received "map change" event
188 function g_Net_Init(): Boolean;
189 procedure g_Net_Cleanup();
190 procedure g_Net_Free();
191 procedure g_Net_Flush();
193 function g_Net_Host(IPAddr
: LongWord; Port
: enet_uint16
; MaxClients
: Cardinal = 16): Boolean;
194 procedure g_Net_Host_Die();
195 procedure g_Net_Host_Send(ID
: Integer; Reliable
: Boolean; Chan
: Byte = NET_CHAN_GAME
);
196 function g_Net_Host_Update(): enet_size_t
;
198 function g_Net_Connect(IP
: string; Port
: enet_uint16
): Boolean;
199 procedure g_Net_Disconnect(Forced
: Boolean = False);
200 procedure g_Net_Client_Send(Reliable
: Boolean; Chan
: Byte = NET_CHAN_GAME
);
201 function g_Net_Client_Update(): enet_size_t
;
202 function g_Net_Client_UpdateWhileLoading(): enet_size_t
;
204 function g_Net_Client_ByName(Name
: string): pTNetClient
;
205 function g_Net_Client_ByPlayer(PID
: Word): pTNetClient
;
206 function g_Net_ClientName_ByID(ID
: Integer): string;
208 procedure g_Net_SendData(Data
: AByte
; peer
: pENetPeer
; Reliable
: Boolean; Chan
: Byte = NET_CHAN_DOWNLOAD
);
209 //function g_Net_Wait_Event(msgId: Word): TMemoryStream;
210 //function g_Net_Wait_FileInfo (var tf: TNetFileTransfer; asMap: Boolean; out resList: TStringList): Integer;
212 function IpToStr(IP
: LongWord): string;
213 function StrToIp(IPstr
: string; var IP
: LongWord): Boolean;
215 function g_Net_IsHostBanned(IP
: LongWord; Perm
: Boolean = False): Boolean;
216 procedure g_Net_BanHost(IP
: LongWord; Perm
: Boolean = True); overload
;
217 procedure g_Net_BanHost(IP
: string; Perm
: Boolean = True); overload
;
218 function g_Net_UnbanHost(IP
: string): Boolean; overload
;
219 function g_Net_UnbanHost(IP
: LongWord): Boolean; overload
;
220 procedure g_Net_UnbanNonPermHosts();
221 procedure g_Net_SaveBanList();
223 procedure g_Net_DumpStart();
224 procedure g_Net_DumpSendBuffer();
225 procedure g_Net_DumpRecvBuffer(Buf
: penet_uint8
; Len
: LongWord);
226 procedure g_Net_DumpEnd();
228 function g_Net_ForwardPorts(ForwardPongPort
: Boolean = True): Boolean;
229 procedure g_Net_UnforwardPorts();
231 function g_Net_UserRequestExit
: Boolean;
233 function g_Net_SendMapRequest (): Boolean;
234 function g_Net_Wait_MapInfo (var tf
: TNetFileTransfer
; resList
: TStringList
): Integer;
235 function g_Net_RequestResFileInfo (resIndex
: LongInt; out tf
: TNetFileTransfer
): Integer;
236 function g_Net_AbortResTransfer (var tf
: TNetFileTransfer
): Boolean;
237 function g_Net_ReceiveResourceFile (resIndex
: LongInt; var tf
: TNetFileTransfer
; strm
: TStream
): Integer;
244 e_input
, g_nethandler
, g_netmsg
, g_netmaster
, g_player
, g_window
, g_console
,
245 g_main
, g_game
, g_language
, g_weapons
, utils
, ctypes
,
249 FILE_CHUNK_SIZE
= 8192;
252 g_Net_DownloadTimeout
: Single;
256 { /// SERVICE FUNCTIONS /// }
257 procedure clearNetClientTransfers (var nc
: TNetClient
);
259 nc
.Transfer
.stream
.Free
;
260 nc
.Transfer
.diskName
:= ''; // just in case
261 if (nc
.Transfer
.diskBuffer
<> nil) then FreeMem(nc
.Transfer
.diskBuffer
);
262 nc
.Transfer
.stream
:= nil;
263 nc
.Transfer
.diskBuffer
:= nil;
267 procedure clearNetClient (var nc
: TNetClient
);
269 clearNetClientTransfers(nc
);
272 procedure clearNetClients (clearArray
: Boolean);
276 for f
:= Low(NetClients
) to High(NetClients
) do clearNetClient(NetClients
[f
]);
277 if (clearArray
) then SetLength(NetClients
, 0);
281 function g_Net_FindSlot(): Integer;
290 for I
:= Low(NetClients
) to High(NetClients
) do
292 if NetClients
[I
].Used
then
301 if C
>= NetMaxClients
then
309 if (Length(NetClients
) >= NetMaxClients
) then
313 SetLength(NetClients
, Length(NetClients
) + 1);
314 N
:= High(NetClients
);
320 NetClients
[N
].Used
:= True;
321 NetClients
[N
].ID
:= N
;
322 NetClients
[N
].RequestedFullUpdate
:= False;
323 NetClients
[N
].RCONAuth
:= False;
324 NetClients
[N
].Voted
:= False;
325 NetClients
[N
].Player
:= 0;
326 clearNetClientTransfers(NetClients
[N
]); // just in case
332 function g_Net_Init(): Boolean;
340 NetBuf
[NET_UNRELIABLE
].Clear();
341 NetBuf
[NET_RELIABLE
].Clear();
342 //SetLength(NetClients, 0);
343 clearNetClients(true); // clear array
349 NetAddr
.port
:= 25666;
350 SetLength(NetBannedHosts
, 0);
351 if FileExists(DataDir
+ BANLIST_FILENAME
) then
353 Assign(F
, DataDir
+ BANLIST_FILENAME
);
358 if StrToIp(IPstr
, IP
) then
365 Result
:= (enet_initialize() = 0);
368 procedure g_Net_Flush();
372 F
, Chan
: enet_uint32
;
376 Chan
:= NET_CHAN_GAME
;
378 if NetMode
= NET_SERVER
then
379 for T
:= NET_UNRELIABLE
to NET_RELIABLE
do
381 if NetBuf
[T
].CurSize
> 0 then
383 P
:= enet_packet_create(NetBuf
[T
].Data
, NetBuf
[T
].CurSize
, F
);
384 if not Assigned(P
) then continue
;
385 enet_host_broadcast(NetHost
, Chan
, P
);
389 for I
:= Low(NetClients
) to High(NetClients
) do
391 if not NetClients
[I
].Used
then continue
;
392 if NetClients
[I
].NetOut
[T
].CurSize
<= 0 then continue
;
393 P
:= enet_packet_create(NetClients
[I
].NetOut
[T
].Data
, NetClients
[I
].NetOut
[T
].CurSize
, F
);
394 if not Assigned(P
) then continue
;
395 enet_peer_send(NetClients
[I
].Peer
, Chan
, P
);
396 NetClients
[I
].NetOut
[T
].Clear();
399 // next and last iteration is always RELIABLE
400 F
:= LongWord(ENET_PACKET_FLAG_RELIABLE
);
401 Chan
:= NET_CHAN_IMPORTANT
;
403 else if NetMode
= NET_CLIENT
then
404 for T
:= NET_UNRELIABLE
to NET_RELIABLE
do
406 if NetBuf
[T
].CurSize
> 0 then
408 P
:= enet_packet_create(NetBuf
[T
].Data
, NetBuf
[T
].CurSize
, F
);
409 if not Assigned(P
) then continue
;
410 enet_peer_send(NetPeer
, Chan
, P
);
413 // next and last iteration is always RELIABLE
414 F
:= LongWord(ENET_PACKET_FLAG_RELIABLE
);
415 Chan
:= NET_CHAN_IMPORTANT
;
419 procedure g_Net_Cleanup();
423 NetBuf
[NET_UNRELIABLE
].Clear();
424 NetBuf
[NET_RELIABLE
].Clear();
426 //SetLength(NetClients, 0);
427 clearNetClients(true); // clear array
437 NetState
:= NET_STATE_NONE
;
439 NetPongSock
:= ENET_SOCKET_NULL
;
441 NetTimeToMaster
:= 0;
442 NetTimeToUpdate
:= 0;
443 NetTimeToReliable
:= 0;
447 if NetPortThread
<> NilThreadId
then
448 WaitForThreadTerminate(NetPortThread
, 66666);
450 NetPortThread
:= NilThreadId
;
451 g_Net_UnforwardPorts();
457 procedure g_Net_Free();
462 NetInitDone
:= False;
466 { /// SERVER FUNCTIONS /// }
469 function ForwardThread(Param
: Pointer): PtrInt
;
472 if not g_Net_ForwardPorts() then Result
:= -1;
475 function g_Net_Host(IPAddr
: LongWord; Port
: enet_uint16
; MaxClients
: Cardinal = 16): Boolean;
477 if NetMode
<> NET_NONE
then
479 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_INGAME
]);
486 g_Console_Add(_lc
[I_NET_MSG
] + Format(_lc
[I_NET_MSG_HOST
], [Port
]));
487 if not NetInitDone
then
489 if (not g_Net_Init()) then
491 g_Console_Add(_lc
[I_NET_MSG_FERROR
] + _lc
[I_NET_ERR_ENET
]);
499 NetAddr
.host
:= IPAddr
;
500 NetAddr
.port
:= Port
;
502 if NetForwardPorts
then NetPortThread
:= BeginThread(ForwardThread
);
504 NetHost
:= enet_host_create(@NetAddr
, NET_MAXCLIENTS
, NET_CHANS
, 0, 0);
506 if (NetHost
= nil) then
508 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + Format(_lc
[I_NET_ERR_HOST
], [Port
]));
514 NetPongSock
:= enet_socket_create(ENET_SOCKET_TYPE_DATAGRAM
);
515 if NetPongSock
<> ENET_SOCKET_NULL
then
517 NetPongAddr
.host
:= IPAddr
;
518 NetPongAddr
.port
:= NET_PING_PORT
;
519 if enet_socket_bind(NetPongSock
, @NetPongAddr
) < 0 then
521 enet_socket_destroy(NetPongSock
);
522 NetPongSock
:= ENET_SOCKET_NULL
;
525 enet_socket_set_option(NetPongSock
, ENET_SOCKOPT_NONBLOCK
, 1);
528 NetMode
:= NET_SERVER
;
530 NetBuf
[NET_UNRELIABLE
].Clear();
531 NetBuf
[NET_RELIABLE
].Clear();
537 procedure g_Net_Host_Die();
541 if NetMode
<> NET_SERVER
then Exit
;
543 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_HOST_DISCALL
]);
544 for I
:= 0 to High(NetClients
) do
545 if NetClients
[I
].Used
then
546 enet_peer_disconnect(NetClients
[I
].Peer
, NET_DISC_DOWN
);
548 while enet_host_service(NetHost
, @NetEvent
, 1000) > 0 do
549 if NetEvent
.kind
= ENET_EVENT_TYPE_RECEIVE
then
550 enet_packet_destroy(NetEvent
.packet
);
552 for I
:= 0 to High(NetClients
) do
553 if NetClients
[I
].Used
then
555 FreeMemory(NetClients
[I
].Peer
^.data
);
556 NetClients
[I
].Peer
^.data
:= nil;
557 enet_peer_reset(NetClients
[I
].Peer
);
558 NetClients
[I
].Peer
:= nil;
559 NetClients
[I
].Used
:= False;
560 NetClients
[I
].NetOut
[NET_UNRELIABLE
].Free();
561 NetClients
[I
].NetOut
[NET_RELIABLE
].Free();
564 clearNetClients(false); // don't clear array
565 if (NetMPeer
<> nil) and (NetMHost
<> nil) then g_Net_Slist_Disconnect
;
566 if NetPongSock
<> ENET_SOCKET_NULL
then
567 enet_socket_destroy(NetPongSock
);
569 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_HOST_DIE
]);
570 enet_host_destroy(NetHost
);
575 e_WriteLog('NET: Server stopped', TMsgType
.Notify
);
579 procedure g_Net_Host_Send(ID
: Integer; Reliable
: Boolean; Chan
: Byte = NET_CHAN_GAME
);
590 if ID
> High(NetClients
) then Exit
;
591 if NetClients
[ID
].Peer
= nil then Exit
;
593 NetClients
[ID
].NetOut
[T
].Write(Integer(NetOut
.CurSize
));
594 NetClients
[ID
].NetOut
[T
].Write(NetOut
);
599 NetBuf
[T
].Write(Integer(NetOut
.CurSize
));
600 NetBuf
[T
].Write(NetOut
);
603 if NetDump
then g_Net_DumpSendBuffer();
607 procedure g_Net_Host_CheckPings();
613 Ping
: array [0..9] of Byte;
616 if NetPongSock
= ENET_SOCKET_NULL
then Exit
;
618 Buf
.data
:= Addr(Ping
[0]);
619 Buf
.dataLength
:= 2+8;
623 Len
:= enet_socket_receive(NetPongSock
, @ClAddr
, @Buf
, 1);
624 if Len
< 0 then Exit
;
626 if (Ping
[0] = Ord('D')) and (Ping
[1] = Ord('F')) then
628 ClTime
:= Int64(Addr(Ping
[2])^);
631 NetOut
.Write(Byte(Ord('D')));
632 NetOut
.Write(Byte(Ord('F')));
633 NetOut
.Write(NetPort
);
634 NetOut
.Write(ClTime
);
635 g_Net_Slist_WriteInfo();
637 if gPlayer1
<> nil then Inc(NPl
);
638 if gPlayer2
<> nil then Inc(NPl
);
640 NetOut
.Write(gNumBots
);
642 Buf
.data
:= NetOut
.Data
;
643 Buf
.dataLength
:= NetOut
.CurSize
;
644 enet_socket_send(NetPongSock
, @ClAddr
, @Buf
, 1);
652 // server packet type
653 NTF_SERVER_DONE
= 10; // done with this file
654 NTF_SERVER_FILE_INFO
= 11; // sent after client request
655 NTF_SERVER_CHUNK
= 12; // next chunk; chunk number follows
656 NTF_SERVER_ABORT
= 13; // server abort
657 NTF_SERVER_MAP_INFO
= 14;
659 // client packet type
660 NTF_CLIENT_MAP_REQUEST
= 100; // map file request; also, returns list of additional wads to download
661 NTF_CLIENT_FILE_REQUEST
= 101; // resource file request (by index)
662 NTF_CLIENT_ABORT
= 102; // do not send requested file, or abort current transfer
663 NTF_CLIENT_START
= 103; // start transfer; client may resume download by sending non-zero starting chunk
664 NTF_CLIENT_ACK
= 104; // chunk ack; chunk number follows
667 procedure KillClientByFT (var nc
: TNetClient
);
669 e_LogWritefln('disconnected client #%d due to file transfer error', [nc
.ID
], TMsgType
.Warning
);
670 enet_peer_disconnect(nc
.Peer
, NET_DISC_FILE_TIMEOUT
);
671 clearNetClientTransfers(nc
);
675 function ftransSendServerMsg (var nc
: TNetClient
; var m
: TMsg
): Boolean;
680 if (m
.CurSize
< 1) then exit
;
681 pkt
:= enet_packet_create(m
.Data
, m
.CurSize
, ENET_PACKET_FLAG_RELIABLE
);
682 if not Assigned(pkt
) then begin KillClientByFT(nc
); exit
; end;
683 if (enet_peer_send(nc
.Peer
, NET_CHAN_DOWNLOAD_EX
, pkt
) <> 0) then begin KillClientByFT(nc
); exit
; end;
688 function ftransSendClientMsg (var m
: TMsg
): Boolean;
693 if (m
.CurSize
< 1) then exit
;
694 pkt
:= enet_packet_create(m
.Data
, m
.CurSize
, ENET_PACKET_FLAG_RELIABLE
);
695 if not Assigned(pkt
) then exit
;
696 if (enet_peer_send(NetPeer
, NET_CHAN_DOWNLOAD_EX
, pkt
) <> 0) then exit
;
701 procedure ProcessChunkSend (var nc
: TNetClient
);
703 tf
: ^TNetFileTransfer
;
709 if (tf
.stream
= nil) then exit
;
711 // arbitrary timeout number
712 if (ct
-tf
.lastAckTime
>= 5000) then
717 // check if we need to send something
718 if (not tf
.inProgress
) then exit
; // waiting for the initial ack
719 // ok, we're sending chunks
720 if (tf
.lastAckChunk
<> tf
.lastSentChunk
) then exit
;
721 Inc(tf
.lastSentChunk
);
722 // do it one chunk at a time; client ack will advance our chunk counter
723 chunks
:= (tf
.size
+tf
.chunkSize
-1) div tf
.chunkSize
;
725 if (tf
.lastSentChunk
> chunks
) then
732 if (tf
.lastSentChunk
= chunks
) then
734 // we're done with this file
735 e_LogWritefln('download: client #%d, DONE sending chunks #%d/#%d', [nc
.ID
, tf
.lastSentChunk
, chunks
]);
736 trans_omsg
.Write(Byte(NTF_SERVER_DONE
));
737 clearNetClientTransfers(nc
);
742 trans_omsg
.Write(Byte(NTF_SERVER_CHUNK
));
743 trans_omsg
.Write(LongInt(tf
.lastSentChunk
));
745 rd
:= tf
.size
-(tf
.lastSentChunk
*tf
.chunkSize
);
746 if (rd
> tf
.chunkSize
) then rd
:= tf
.chunkSize
;
747 trans_omsg
.Write(LongInt(rd
));
748 //e_LogWritefln('download: client #%d, sending chunk #%d/#%d (%d bytes)', [nc.ID, tf.lastSentChunk, chunks, rd]);
749 //FIXME: check for errors here
751 tf
.stream
.Seek(tf
.lastSentChunk
*tf
.chunkSize
, soFromBeginning
);
752 tf
.stream
.ReadBuffer(tf
.diskBuffer
^, rd
);
753 trans_omsg
.WriteData(tf
.diskBuffer
, rd
);
760 ftransSendServerMsg(nc
, trans_omsg
);
764 // received packet is in `NetEvent`
765 procedure ProcessDownloadExPacket ();
772 tf
: ^TNetFileTransfer
;
781 // find client index by peer
782 for f
:= Low(NetClients
) to High(NetClients
) do
784 if (not NetClients
[f
].Used
) then continue
;
785 if (NetClients
[f
].Peer
= NetEvent
.peer
) then
791 //e_LogWritefln('RECEIVE: dlpacket; client=%d (datalen=%u)', [nid, NetEvent.packet^.dataLength]);
793 if (nid
< 0) then exit
; // wtf?!
794 nc
:= @NetClients
[nid
];
796 if (NetEvent
.packet
^.dataLength
= 0) then
802 tf
:= @NetClients
[nid
].Transfer
;
803 tf
.lastAckTime
:= GetTimerMS();
805 cmd
:= Byte(NetEvent
.packet
^.data
^);
806 //e_LogWritefln('RECEIVE: nid=%d; cmd=%u', [nid, cmd]);
808 NTF_CLIENT_FILE_REQUEST
: // file request
810 if (tf
.stream
<> nil) then
815 if (NetEvent
.packet
^.dataLength
< 2) then
820 // new transfer request; build packet
821 if not msg
.Init(NetEvent
.packet
^.data
+1, NetEvent
.packet
^.dataLength
-1, True) then
826 // get resource index
827 ridx
:= msg
.ReadLongInt();
828 if (ridx
< -1) or (ridx
>= gExternalResources
.Count
) then
830 e_LogWritefln('Invalid resource index %d', [ridx
], TMsgType
.Warning
);
834 if (ridx
< 0) then fname
:= MapsDir
+gGameSettings
.WAD
else fname
:= GameDir
+'/wads/'+gExternalResources
[ridx
];
835 if (length(fname
) = 0) then
837 e_WriteLog('Invalid filename: '+fname
, TMsgType
.Warning
);
841 tf
.diskName
:= findDiskWad(fname
);
842 //if (length(tf.diskName) = 0) then tf.diskName := findDiskWad(GameDir+'/wads/'+fname);
843 if (length(tf
.diskName
) = 0) then
845 e_LogWritefln('NETWORK: file "%s" not found!', [fname
], TMsgType
.Fatal
);
851 tf
.hash
:= MD5File(tf
.diskName
);
852 // create file stream
853 tf
.diskName
:= findDiskWad(fname
);
855 tf
.stream
:= openDiskFileRO(tf
.diskName
);
859 if (tf
.stream
= nil) then
861 e_WriteLog(Format('NETWORK: file "%s" not found!', [fname
]), TMsgType
.Fatal
);
865 e_LogWritefln('client #%d requested resource #%d (file is `%s` : `%s`)', [nc
.ID
, ridx
, fname
, tf
.diskName
]);
866 tf
.size
:= tf
.stream
.size
;
867 tf
.chunkSize
:= FILE_CHUNK_SIZE
; // arbitrary
868 tf
.lastSentChunk
:= -1;
869 tf
.lastAckChunk
:= -1;
870 tf
.lastAckTime
:= GetTimerMS();
871 tf
.inProgress
:= False; // waiting for the first ACK or for the cancel
872 GetMem(tf
.diskBuffer
, tf
.chunkSize
);
873 // sent file info message
875 trans_omsg
.Write(Byte(NTF_SERVER_FILE_INFO
));
876 trans_omsg
.Write(tf
.hash
);
877 trans_omsg
.Write(tf
.size
);
878 trans_omsg
.Write(tf
.chunkSize
);
879 trans_omsg
.Write(ExtractFileName(fname
));
880 if not ftransSendServerMsg(nc
^, trans_omsg
) then exit
;
882 NTF_CLIENT_ABORT
: // do not send requested file, or abort current transfer
884 e_LogWritefln('client #%d aborted file transfer', [nc
.ID
]);
885 clearNetClientTransfers(nc
^);
887 NTF_CLIENT_START
: // start transfer; client may resume download by sending non-zero starting chunk
889 if not Assigned(tf
.stream
) then
894 if (tf
.lastSentChunk
<> -1) or (tf
.lastAckChunk
<> -1) or (tf
.inProgress
) then
896 // double ack, get lost
900 if (NetEvent
.packet
^.dataLength
< 2) then
906 if not msg
.Init(NetEvent
.packet
^.data
+1, NetEvent
.packet
^.dataLength
-1, True) then
911 chunk
:= msg
.ReadLongInt();
912 if (chunk
< 0) or (chunk
> (tf
.size
+tf
.chunkSize
-1) div tf
.chunkSize
) then
917 e_LogWritefln('client #%d started file transfer from chunk %d', [nc
.ID
, chunk
]);
918 // start sending chunks
919 tf
.inProgress
:= True;
920 tf
.lastSentChunk
:= chunk
-1;
921 tf
.lastAckChunk
:= chunk
-1;
922 ProcessChunkSend(nc
^);
924 NTF_CLIENT_ACK
: // chunk ack; chunk number follows
926 if not Assigned(tf
.stream
) then
931 if (tf
.lastSentChunk
< 0) or (not tf
.inProgress
) then
933 // double ack, get lost
937 if (NetEvent
.packet
^.dataLength
< 2) then
943 if not msg
.Init(NetEvent
.packet
^.data
+1, NetEvent
.packet
^.dataLength
-1, True) then
948 chunk
:= msg
.ReadLongInt();
949 if (chunk
< 0) or (chunk
> (tf
.size
+tf
.chunkSize
-1) div tf
.chunkSize
) then
954 // do it this way, so client may seek, or request retransfers for some reason
955 tf
.lastAckChunk
:= chunk
;
956 tf
.lastSentChunk
:= chunk
;
957 //e_LogWritefln('client #%d acked file transfer chunk %d', [nc.ID, chunk]);
958 ProcessChunkSend(nc
^);
960 NTF_CLIENT_MAP_REQUEST
:
962 e_LogWritefln('client #%d requested map info', [nc
.ID
]);
964 dfn
:= findDiskWad(MapsDir
+gGameSettings
.WAD
);
965 if (dfn
= '') then dfn
:= '!wad_not_found!.wad'; //FIXME
967 st
:= openDiskFileRO(dfn
);
968 if not assigned(st
) then exit
; //wtf?!
972 trans_omsg
.Write(Byte(NTF_SERVER_MAP_INFO
));
974 trans_omsg
.Write(gGameSettings
.WAD
);
976 trans_omsg
.Write(md5
);
978 trans_omsg
.Write(size
);
979 // number of external resources for map
980 trans_omsg
.Write(LongInt(gExternalResources
.Count
));
981 // external resource names
982 for f
:= 0 to gExternalResources
.Count
-1 do
984 trans_omsg
.Write(ExtractFileName(gExternalResources
[f
])); // GameDir+'/wads/'+ResList.Strings[i]
987 if not ftransSendServerMsg(nc
^, trans_omsg
) then exit
;
998 function g_Net_Host_Update(): enet_size_t
;
1011 if NetUseMaster
then g_Net_Slist_Check
;
1012 g_Net_Host_CheckPings
;
1014 //ctt := -GetTimerMS();
1015 // process file transfers
1017 for f := Low(NetClients) to High(NetClients) do
1019 if (not NetClients[f].Used) then continue;
1020 if (NetClients[f].Transfer.stream = nil) then continue;
1021 ProcessChunkSend(NetClients[f]);
1025 ctt := ctt+GetTimerMS();
1026 if (ctt > 1) then e_LogWritefln('all transfers: [%d]', [Integer(ctt)]);
1029 while (enet_host_service(NetHost
, @NetEvent
, 0) > 0) do
1031 case (NetEvent
.kind
) of
1032 ENET_EVENT_TYPE_CONNECT
:
1034 IP
:= IpToStr(NetEvent
.Peer
^.address
.host
);
1035 Port
:= NetEvent
.Peer
^.address
.port
;
1036 g_Console_Add(_lc
[I_NET_MSG
] +
1037 Format(_lc
[I_NET_MSG_HOST_CONN
], [IP
, Port
]));
1039 if (NetEvent
.data
<> NET_PROTOCOL_VER
) then
1041 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_HOST_REJECT
] +
1042 _lc
[I_NET_DISC_PROTOCOL
]);
1043 NetEvent
.peer
^.data
:= GetMemory(SizeOf(Byte));
1044 Byte(NetEvent
.peer
^.data
^) := 255;
1045 enet_peer_disconnect(NetEvent
.peer
, NET_DISC_PROTOCOL
);
1046 enet_host_flush(NetHost
);
1050 ID
:= g_Net_FindSlot();
1054 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_HOST_REJECT
] +
1055 _lc
[I_NET_DISC_FULL
]);
1056 NetEvent
.Peer
^.data
:= GetMemory(SizeOf(Byte));
1057 Byte(NetEvent
.peer
^.data
^) := 255;
1058 enet_peer_disconnect(NetEvent
.peer
, NET_DISC_FULL
);
1059 enet_host_flush(NetHost
);
1063 NetClients
[ID
].Peer
:= NetEvent
.peer
;
1064 NetClients
[ID
].Peer
^.data
:= GetMemory(SizeOf(Byte));
1065 Byte(NetClients
[ID
].Peer
^.data
^) := ID
;
1066 NetClients
[ID
].State
:= NET_STATE_AUTH
;
1067 NetClients
[ID
].RCONAuth
:= False;
1068 NetClients
[ID
].NetOut
[NET_UNRELIABLE
].Alloc(NET_BUFSIZE
*2);
1069 NetClients
[ID
].NetOut
[NET_RELIABLE
].Alloc(NET_BUFSIZE
*2);
1070 clearNetClientTransfers(NetClients
[ID
]); // just in case
1072 enet_peer_timeout(NetEvent
.peer
, ENET_PEER_TIMEOUT_LIMIT
* 2, ENET_PEER_TIMEOUT_MINIMUM
* 2, ENET_PEER_TIMEOUT_MAXIMUM
* 2);
1074 Inc(NetClientCount
);
1075 g_Console_Add(_lc
[I_NET_MSG
] + Format(_lc
[I_NET_MSG_HOST_ADD
], [ID
]));
1078 ENET_EVENT_TYPE_RECEIVE
:
1080 //e_LogWritefln('RECEIVE: chan=%u', [NetEvent.channelID]);
1081 if (NetEvent
.channelID
= NET_CHAN_DOWNLOAD_EX
) then
1083 ProcessDownloadExPacket();
1087 ID
:= Byte(NetEvent
.peer
^.data
^);
1088 if ID
> High(NetClients
) then Exit
;
1089 TC
:= @NetClients
[ID
];
1091 if NetDump
then g_Net_DumpRecvBuffer(NetEvent
.packet
^.data
, NetEvent
.packet
^.dataLength
);
1092 g_Net_Host_HandlePacket(TC
, NetEvent
.packet
, g_Net_HostMsgHandler
);
1096 ENET_EVENT_TYPE_DISCONNECT
:
1098 ID
:= Byte(NetEvent
.peer
^.data
^);
1099 if ID
> High(NetClients
) then Exit
;
1100 clearNetClient(NetClients
[ID
]);
1101 TC
:= @NetClients
[ID
];
1102 if TC
= nil then Exit
;
1104 if not (TC
^.Used
) then Exit
;
1106 TP
:= g_Player_Get(TC
^.Player
);
1111 TP
.Kill(K_SIMPLEKILL
, 0, HIT_DISCON
);
1112 g_Console_Add(Format(_lc
[I_PLAYER_LEAVE
], [TP
.Name
]), True);
1113 e_WriteLog('NET: Client ' + TP
.Name
+ ' [' + IntToStr(ID
) + '] disconnected.', TMsgType
.Notify
);
1114 g_Player_Remove(TP
.UID
);
1118 TC
^.State
:= NET_STATE_NONE
;
1121 TC
^.RequestedFullUpdate
:= False;
1122 TC
^.NetOut
[NET_UNRELIABLE
].Free();
1123 TC
^.NetOut
[NET_RELIABLE
].Free();
1125 FreeMemory(NetEvent
.peer
^.data
);
1126 NetEvent
.peer
^.data
:= nil;
1127 g_Console_Add(_lc
[I_NET_MSG
] + Format(_lc
[I_NET_MSG_HOST_DISC
], [ID
]));
1128 Dec(NetClientCount
);
1130 if NetUseMaster
then g_Net_Slist_Update
;
1137 { /// CLIENT FUNCTIONS /// }
1140 procedure g_Net_Disconnect(Forced
: Boolean = False);
1142 if NetMode
<> NET_CLIENT
then Exit
;
1143 if (NetHost
= nil) or (NetPeer
= nil) then Exit
;
1147 enet_peer_disconnect(NetPeer
, NET_DISC_NONE
);
1149 while (enet_host_service(NetHost
, @NetEvent
, 1500) > 0) do
1151 if (NetEvent
.kind
= ENET_EVENT_TYPE_DISCONNECT
) then
1157 if (NetEvent
.kind
= ENET_EVENT_TYPE_RECEIVE
) then
1158 enet_packet_destroy(NetEvent
.packet
);
1161 if NetPeer
<> nil then
1163 enet_peer_reset(NetPeer
);
1169 e_WriteLog('NET: Kicked from server: ' + IntToStr(NetEvent
.data
), TMsgType
.Notify
);
1170 if (NetEvent
.data
<= NET_DISC_MAX
) then
1171 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_KICK
] +
1172 _lc
[TStrings_Locale(Cardinal(I_NET_DISC_NONE
) + NetEvent
.data
)], True);
1175 if NetHost
<> nil then
1177 enet_host_destroy(NetHost
);
1180 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_CLIENT_DISC
]);
1183 e_WriteLog('NET: Disconnected', TMsgType
.Notify
);
1186 procedure g_Net_Client_Send(Reliable
: Boolean; Chan
: Byte = NET_CHAN_GAME
);
1193 T
:= NET_UNRELIABLE
;
1196 NetBuf
[T
].Write(Integer(NetOut
.CurSize
));
1197 NetBuf
[T
].Write(NetOut
);
1199 if NetDump
then g_Net_DumpSendBuffer();
1201 g_Net_Flush(); // FIXME: for now, send immediately
1204 function g_Net_Client_Update(): enet_size_t
;
1207 while (enet_host_service(NetHost
, @NetEvent
, 0) > 0) do
1209 case NetEvent
.kind
of
1210 ENET_EVENT_TYPE_RECEIVE
:
1212 if (NetEvent
.channelID
= NET_CHAN_DOWNLOAD_EX
) then continue
; // ignore all download packets, they're processed by separate code
1213 if NetDump
then g_Net_DumpRecvBuffer(NetEvent
.packet
^.data
, NetEvent
.packet
^.dataLength
);
1214 g_Net_Client_HandlePacket(NetEvent
.packet
, g_Net_ClientMsgHandler
);
1217 ENET_EVENT_TYPE_DISCONNECT
:
1219 g_Net_Disconnect(True);
1227 function g_Net_Client_UpdateWhileLoading(): enet_size_t
;
1230 while (enet_host_service(NetHost
, @NetEvent
, 0) > 0) do
1232 case NetEvent
.kind
of
1233 ENET_EVENT_TYPE_RECEIVE
:
1235 if (NetEvent
.channelID
= NET_CHAN_DOWNLOAD_EX
) then continue
; // ignore all download packets, they're processed by separate code
1236 if NetDump
then g_Net_DumpRecvBuffer(NetEvent
.packet
^.data
, NetEvent
.packet
^.dataLength
);
1237 g_Net_Client_HandlePacket(NetEvent
.packet
, g_Net_ClientLightMsgHandler
);
1240 ENET_EVENT_TYPE_DISCONNECT
:
1242 g_Net_Disconnect(True);
1251 function g_Net_Connect(IP
: string; Port
: enet_uint16
): Boolean;
1254 TimeoutTime
, T
: Int64;
1256 if NetMode
<> NET_NONE
then
1258 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_ERR_INGAME
], True);
1265 g_Console_Add(_lc
[I_NET_MSG
] + Format(_lc
[I_NET_MSG_CLIENT_CONN
],
1267 if not NetInitDone
then
1269 if (not g_Net_Init()) then
1271 g_Console_Add(_lc
[I_NET_MSG_FERROR
] + _lc
[I_NET_ERR_ENET
], True);
1276 NetInitDone
:= True;
1279 NetHost
:= enet_host_create(nil, 1, NET_CHANS
, 0, 0);
1281 if (NetHost
= nil) then
1283 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CLIENT
], True);
1289 enet_address_set_host(@NetAddr
, PChar(Addr(IP
[1])));
1290 NetAddr
.port
:= Port
;
1292 NetPeer
:= enet_host_connect(NetHost
, @NetAddr
, NET_CHANS
, NET_PROTOCOL_VER
);
1294 if (NetPeer
= nil) then
1296 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CLIENT
], True);
1297 enet_host_destroy(NetHost
);
1303 // предупредить что ждем слишком долго через N секунд
1304 TimeoutTime
:= GetTimer() + NET_CONNECT_TIMEOUT
;
1309 while (enet_host_service(NetHost
, @NetEvent
, 0) > 0) do
1311 if (NetEvent
.kind
= ENET_EVENT_TYPE_CONNECT
) then
1313 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_CLIENT_DONE
]);
1314 NetMode
:= NET_CLIENT
;
1316 enet_peer_timeout(NetPeer
, ENET_PEER_TIMEOUT_LIMIT
* 2, ENET_PEER_TIMEOUT_MINIMUM
* 2, ENET_PEER_TIMEOUT_MAXIMUM
* 2);
1318 NetClientPort
:= Port
;
1326 if T
> TimeoutTime
then
1328 TimeoutTime
:= T
+ NET_CONNECT_TIMEOUT
* 100; // одного предупреждения хватит
1329 g_Console_Add(_lc
[I_NET_MSG_TIMEOUT_WARN
], True);
1330 g_Console_Add(Format(_lc
[I_NET_MSG_PORTS
], [Integer(Port
), Integer(NET_PING_PORT
)]), True);
1333 ProcessLoading(true);
1335 if e_KeyPressed(IK_SPACE
) or e_KeyPressed(IK_ESCAPE
) or e_KeyPressed(VK_ESCAPE
) or
1336 e_KeyPressed(JOY0_JUMP
) or e_KeyPressed(JOY1_JUMP
) or e_KeyPressed(JOY2_JUMP
) or e_KeyPressed(JOY3_JUMP
) then
1340 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_TIMEOUT
], True);
1341 g_Console_Add(Format(_lc
[I_NET_MSG_PORTS
], [Integer(Port
), Integer(NET_PING_PORT
)]), True);
1342 if NetPeer
<> nil then enet_peer_reset(NetPeer
);
1343 if NetHost
<> nil then
1345 enet_host_destroy(NetHost
);
1352 function IpToStr(IP
: LongWord): string;
1357 Result
:= IntToStr(PByte(Ptr
+ 0)^) + '.';
1358 Result
:= Result
+ IntToStr(PByte(Ptr
+ 1)^) + '.';
1359 Result
:= Result
+ IntToStr(PByte(Ptr
+ 2)^) + '.';
1360 Result
:= Result
+ IntToStr(PByte(Ptr
+ 3)^);
1363 function StrToIp(IPstr
: string; var IP
: LongWord): Boolean;
1367 Result
:= enet_address_set_host(@EAddr
, PChar(@IPstr
[1])) = 0;
1371 function g_Net_Client_ByName(Name
: string): pTNetClient
;
1377 for a
:= Low(NetClients
) to High(NetClients
) do
1378 if (NetClients
[a
].Used
) and (NetClients
[a
].State
= NET_STATE_GAME
) then
1380 pl
:= g_Player_Get(NetClients
[a
].Player
);
1381 if pl
= nil then continue
;
1382 if Copy(LowerCase(pl
.Name
), 1, Length(Name
)) <> LowerCase(Name
) then continue
;
1383 if NetClients
[a
].Peer
<> nil then
1385 Result
:= @NetClients
[a
];
1391 function g_Net_Client_ByPlayer(PID
: Word): pTNetClient
;
1396 for a
:= Low(NetClients
) to High(NetClients
) do
1397 if (NetClients
[a
].Used
) and (NetClients
[a
].State
= NET_STATE_GAME
) then
1398 if NetClients
[a
].Player
= PID
then
1400 Result
:= @NetClients
[a
];
1405 function g_Net_ClientName_ByID(ID
: Integer): string;
1411 if ID
= NET_EVERYONE
then
1413 for a
:= Low(NetClients
) to High(NetClients
) do
1414 if (NetClients
[a
].ID
= ID
) and (NetClients
[a
].Used
) and (NetClients
[a
].State
= NET_STATE_GAME
) then
1416 pl
:= g_Player_Get(NetClients
[a
].Player
);
1417 if pl
= nil then Exit
;
1422 procedure g_Net_SendData(Data
: AByte
; peer
: pENetPeer
; Reliable
: Boolean; Chan
: Byte = NET_CHAN_DOWNLOAD
);
1426 dataLength
: Cardinal;
1428 dataLength
:= Length(Data
);
1431 F
:= LongWord(ENET_PACKET_FLAG_RELIABLE
)
1435 if (peer
<> nil) then
1437 P
:= enet_packet_create(@Data
[0], dataLength
, F
);
1438 if not Assigned(P
) then Exit
;
1439 enet_peer_send(peer
, Chan
, P
);
1443 P
:= enet_packet_create(@Data
[0], dataLength
, F
);
1444 if not Assigned(P
) then Exit
;
1445 enet_host_broadcast(NetHost
, Chan
, P
);
1448 enet_host_flush(NetHost
);
1451 function g_Net_UserRequestExit
: Boolean;
1453 Result
:= e_KeyPressed(IK_SPACE
) or
1454 e_KeyPressed(IK_ESCAPE
) or
1455 e_KeyPressed(VK_ESCAPE
) or
1456 e_KeyPressed(JOY0_JUMP
) or
1457 e_KeyPressed(JOY1_JUMP
) or
1458 e_KeyPressed(JOY2_JUMP
) or
1459 e_KeyPressed(JOY3_JUMP
)
1463 function g_Net_Wait_Event(msgId: Word): TMemoryStream;
1468 stream: TMemoryStream;
1471 FillChar(ev, SizeOf(ev), 0);
1474 status := enet_host_service(NetHost, @ev, Trunc(g_Net_DownloadTimeout * 1000));
1478 ENET_EVENT_TYPE_RECEIVE:
1480 Ptr := ev.packet^.data;
1481 rMsgId := Byte(Ptr^);
1482 if rMsgId = msgId then
1484 stream := TMemoryStream.Create;
1485 stream.SetSize(ev.packet^.dataLength);
1486 stream.WriteBuffer(Ptr^, ev.packet^.dataLength);
1487 stream.Seek(0, soFromBeginning);
1488 status := 1 (* received *)
1492 (* looks that game state always received, so ignore it *)
1493 e_LogWritefln('g_Net_Wait_Event(%s): skip message %s', [msgId, rMsgId]);
1494 status := 2 (* continue *)
1497 ENET_EVENT_TYPE_DISCONNECT:
1499 if (ev.data <= NET_DISC_MAX) then
1500 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' ' + _lc[TStrings_Locale(Cardinal(I_NET_DISC_NONE) + ev.data)], True);
1501 status := -2 (* error: disconnected *)
1504 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' unknown ENet event ' + IntToStr(Ord(ev.kind)), True);
1505 status := -3 (* error: unknown event *)
1507 enet_packet_destroy(ev.packet)
1511 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' timeout reached', True);
1512 status := 0 (* error: timeout *)
1514 ProcessLoading(true);
1515 until (status <> 2) or g_Net_UserRequestExit();
1521 function getNewTimeoutEnd (): Int64;
1523 result
:= GetTimerMS();
1524 if (g_Net_DownloadTimeout
<= 0) then
1526 result
:= result
+1000*60*3; // 3 minutes
1530 result
:= result
+trunc(g_Net_DownloadTimeout
*1000);
1535 function g_Net_SendMapRequest (): Boolean;
1538 e_LogWritefln('sending map request...', []);
1541 trans_omsg
.Write(Byte(NTF_CLIENT_MAP_REQUEST
));
1542 e_LogWritefln(' request size is %d', [trans_omsg
.CurSize
]);
1543 result
:= ftransSendClientMsg(trans_omsg
);
1544 if result
then enet_host_flush(NetHost
);
1548 // returns `false` on error or user abort
1557 // 2 on server abort
1558 // for maps, first `tf.diskName` name will be map wad name, and `tf.hash`/`tf.size` will contain map info
1559 function g_Net_Wait_MapInfo (var tf
: TNetFileTransfer
; resList
: TStringList
): Integer;
1565 freePacket
: Boolean = false;
1571 FillChar(ev
, SizeOf(ev
), 0);
1574 ett
:= getNewTimeoutEnd();
1576 status
:= enet_host_service(NetHost
, @ev
, 300);
1577 if (status
< 0) then
1579 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' network error', True);
1583 if (status
= 0) then
1585 // check for timeout
1589 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' timeout reached', True);
1598 ENET_EVENT_TYPE_RECEIVE
:
1601 if (ev
.channelID
<> NET_CHAN_DOWNLOAD_EX
) then
1603 //e_LogWritefln('g_Net_Wait_MapInfo: skip message from non-transfer channel', []);
1604 freePacket
:= false;
1605 g_Net_Client_HandlePacket(ev
.packet
, g_Net_ClientLightMsgHandler
);
1606 if (g_Res_received_map_start
< 0) then begin result
:= -666; exit
; end;
1610 ett
:= getNewTimeoutEnd();
1611 if (ev
.packet
.dataLength
< 1) then
1613 e_LogWritefln('g_Net_Wait_MapInfo: invalid server packet (no data)', []);
1617 Ptr
:= ev
.packet
^.data
;
1618 rMsgId
:= Byte(Ptr
^);
1619 e_LogWritefln('g_Net_Wait_MapInfo: got message %u from server (dataLength=%u)', [rMsgId
, ev
.packet
^.dataLength
]);
1620 if (rMsgId
= NTF_SERVER_FILE_INFO
) then
1622 e_LogWritefln('g_Net_Wait_MapInfo: waiting for map info reply, but got file info reply', []);
1626 else if (rMsgId
= NTF_SERVER_ABORT
) then
1628 e_LogWritefln('g_Net_Wait_MapInfo: server aborted transfer', []);
1632 else if (rMsgId
= NTF_SERVER_MAP_INFO
) then
1634 e_LogWritefln('g_Net_Wait_MapInfo: creating map info packet...', []);
1635 if not msg
.Init(ev
.packet
^.data
+1, ev
.packet
^.dataLength
-1, True) then exit
;
1636 e_LogWritefln('g_Net_Wait_MapInfo: parsing map info packet (rd=%d; max=%d)...', [msg
.ReadCount
, msg
.MaxSize
]);
1639 tf
.diskName
:= msg
.ReadString();
1640 e_LogWritefln('g_Net_Wait_MapInfo: map wad is `%s`', [tf
.diskName
]);
1642 tf
.hash
:= msg
.ReadMD5();
1644 tf
.size
:= msg
.ReadLongInt();
1645 e_LogWritefln('g_Net_Wait_MapInfo: map wad size is %d', [tf
.size
]);
1646 // number of external resources for map
1647 rc
:= msg
.ReadLongInt();
1648 if (rc
< 0) or (rc
> 1024) then
1650 e_LogWritefln('g_Net_Wait_Event: invalid number of map external resources (%d)', [rc
]);
1654 e_LogWritefln('g_Net_Wait_MapInfo: map external resource count is %d', [rc
]);
1655 // external resource names
1656 for f
:= 0 to rc
-1 do
1658 s
:= ExtractFileName(msg
.ReadString());
1659 if (length(s
) = 0) then
1666 e_LogWritefln('g_Net_Wait_MapInfo: got map info', []);
1667 Result
:= 0; // success
1672 e_LogWritefln('g_Net_Wait_Event: invalid server packet type', []);
1678 ENET_EVENT_TYPE_DISCONNECT
:
1680 if (ev
.data
<= NET_DISC_MAX
) then
1681 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' ' + _lc
[TStrings_Locale(Cardinal(I_NET_DISC_NONE
) + ev
.data
)], True);
1687 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' unknown ENet event ' + IntToStr(Ord(ev
.kind
)), True);
1692 if (freePacket
) then begin freePacket
:= false; enet_packet_destroy(ev
.packet
); end;
1695 if g_Net_UserRequestExit() then
1697 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' user abort', True);
1703 if (freePacket
) then enet_packet_destroy(ev
.packet
);
1708 // returns `false` on error or user abort
1710 // diskName (actually, base name)
1718 // 2 on server abort
1719 // for maps, first `tf.diskName` name will be map wad name, and `tf.hash`/`tf.size` will contain map info
1720 function g_Net_RequestResFileInfo (resIndex
: LongInt; out tf
: TNetFileTransfer
): Integer;
1726 freePacket
: Boolean = false;
1732 trans_omsg
.Write(Byte(NTF_CLIENT_FILE_REQUEST
));
1733 trans_omsg
.Write(resIndex
);
1734 if not ftransSendClientMsg(trans_omsg
) then begin result
:= -1; exit
; end;
1736 FillChar(ev
, SizeOf(ev
), 0);
1739 ett
:= getNewTimeoutEnd();
1741 status
:= enet_host_service(NetHost
, @ev
, 300);
1742 if (status
< 0) then
1744 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' network error', True);
1748 if (status
= 0) then
1750 // check for timeout
1754 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' timeout reached', True);
1763 ENET_EVENT_TYPE_RECEIVE
:
1766 if (ev
.channelID
<> NET_CHAN_DOWNLOAD_EX
) then
1768 //e_LogWriteln('g_Net_Wait_Event: skip message from non-transfer channel');
1769 freePacket
:= false;
1770 g_Net_Client_HandlePacket(ev
.packet
, g_Net_ClientLightMsgHandler
);
1771 if (g_Res_received_map_start
< 0) then begin result
:= -666; exit
; end;
1775 ett
:= getNewTimeoutEnd();
1776 if (ev
.packet
.dataLength
< 1) then
1778 e_LogWriteln('g_Net_Wait_Event: invalid server packet (no data)');
1782 Ptr
:= ev
.packet
^.data
;
1783 rMsgId
:= Byte(Ptr
^);
1784 e_LogWritefln('received transfer packet with id %d (%u bytes)', [rMsgId
, ev
.packet
^.dataLength
]);
1785 if (rMsgId
= NTF_SERVER_FILE_INFO
) then
1787 if not msg
.Init(ev
.packet
^.data
+1, ev
.packet
^.dataLength
-1, True) then exit
;
1788 tf
.hash
:= msg
.ReadMD5();
1789 tf
.size
:= msg
.ReadLongInt();
1790 tf
.chunkSize
:= msg
.ReadLongInt();
1791 tf
.diskName
:= ExtractFileName(msg
.readString());
1792 if (tf
.size
< 0) or (tf
.chunkSize
<> FILE_CHUNK_SIZE
) or (length(tf
.diskName
) = 0) then
1794 e_LogWritefln('g_Net_RequestResFileInfo: invalid file info packet', []);
1798 e_LogWritefln('got file info for resource #%d: size=%d; name=%s', [resIndex
, tf
.size
, tf
.diskName
]);
1799 Result
:= 0; // success
1802 else if (rMsgId
= NTF_SERVER_ABORT
) then
1804 e_LogWriteln('g_Net_RequestResFileInfo: server aborted transfer');
1808 else if (rMsgId
= NTF_SERVER_MAP_INFO
) then
1810 e_LogWriteln('g_Net_RequestResFileInfo: waiting for map info reply, but got file info reply');
1816 e_LogWriteln('g_Net_RequestResFileInfo: invalid server packet type');
1822 ENET_EVENT_TYPE_DISCONNECT
:
1824 if (ev
.data
<= NET_DISC_MAX
) then
1825 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' ' + _lc
[TStrings_Locale(Cardinal(I_NET_DISC_NONE
) + ev
.data
)], True);
1831 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' unknown ENet event ' + IntToStr(Ord(ev
.kind
)), True);
1836 if (freePacket
) then begin freePacket
:= false; enet_packet_destroy(ev
.packet
); end;
1839 if g_Net_UserRequestExit() then
1841 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' user abort', True);
1847 if (freePacket
) then enet_packet_destroy(ev
.packet
);
1852 function g_Net_AbortResTransfer (var tf
: TNetFileTransfer
): Boolean;
1855 e_LogWritefln('aborting file transfer...', []);
1858 trans_omsg
.Write(Byte(NTF_CLIENT_ABORT
));
1859 result
:= ftransSendClientMsg(trans_omsg
);
1860 if result
then enet_host_flush(NetHost
);
1864 // returns `false` on error or user abort
1873 // 2 on server abort
1874 // for maps, first `tf.diskName` name will be map wad name, and `tf.hash`/`tf.size` will contain map info
1875 function g_Net_ReceiveResourceFile (resIndex
: LongInt; var tf
: TNetFileTransfer
; strm
: TStream
): Integer;
1881 freePacket
: Boolean = false;
1884 nextChunk
: Integer = 0;
1885 chunkTotal
: Integer;
1892 tf
.resumed
:= false;
1893 e_LogWritefln('file `%s`, size=%d (%d)', [tf
.diskName
, Integer(strm
.size
), tf
.size
], TMsgType
.Notify
);
1894 // check if we should resume downloading
1895 resumed
:= (strm
.size
> tf
.chunkSize
) and (strm
.size
< tf
.size
);
1898 trans_omsg
.Write(Byte(NTF_CLIENT_START
));
1899 if resumed
then chunk
:= strm
.size
div tf
.chunkSize
else chunk
:= 0;
1900 trans_omsg
.Write(LongInt(chunk
));
1901 if not ftransSendClientMsg(trans_omsg
) then begin result
:= -1; exit
; end;
1903 strm
.Seek(chunk
*tf
.chunkSize
, soFromBeginning
);
1904 chunkTotal
:= (tf
.size
+tf
.chunkSize
-1) div tf
.chunkSize
;
1905 e_LogWritefln('receiving file `%s` (%d chunks)', [tf
.diskName
, chunkTotal
], TMsgType
.Notify
);
1906 g_Game_SetLoadingText('downloading "'+ExtractFileName(tf
.diskName
)+'"', chunkTotal
, False);
1907 tf
.resumed
:= resumed
;
1909 if (chunk
> 0) then g_Game_StepLoading(chunk
);
1912 // wait for reply data
1913 FillChar(ev
, SizeOf(ev
), 0);
1915 GetMem(buf
, tf
.chunkSize
);
1917 ett
:= getNewTimeoutEnd();
1919 //stx := -GetTimerMS();
1920 status
:= enet_host_service(NetHost
, @ev
, 300);
1921 if (status
< 0) then
1923 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' network error', True);
1927 if (status
= 0) then
1929 // check for timeout
1933 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' timeout reached', True);
1942 ENET_EVENT_TYPE_RECEIVE
:
1945 if (ev
.channelID
<> NET_CHAN_DOWNLOAD_EX
) then
1947 //e_LogWritefln('g_Net_Wait_Event: skip message from non-transfer channel', []);
1948 freePacket
:= false;
1949 g_Net_Client_HandlePacket(ev
.packet
, g_Net_ClientLightMsgHandler
);
1950 if (g_Res_received_map_start
< 0) then begin result
:= -666; exit
; end;
1954 //stx := stx+GetTimerMS();
1955 //e_LogWritefln('g_Net_ReceiveResourceFile: stx=%d', [Integer(stx)]);
1956 //stx := -GetTimerMS();
1957 ett
:= getNewTimeoutEnd();
1958 if (ev
.packet
.dataLength
< 1) then
1960 e_LogWritefln('g_Net_ReceiveResourceFile: invalid server packet (no data)', []);
1964 Ptr
:= ev
.packet
^.data
;
1965 rMsgId
:= Byte(Ptr
^);
1966 if (rMsgId
= NTF_SERVER_DONE
) then
1968 e_LogWritefln('file transfer complete.', []);
1972 else if (rMsgId
= NTF_SERVER_CHUNK
) then
1974 if not msg
.Init(ev
.packet
^.data
+1, ev
.packet
^.dataLength
-1, True) then exit
;
1975 chunk
:= msg
.ReadLongInt();
1976 csize
:= msg
.ReadLongInt();
1977 if (chunk
<> nextChunk
) then
1979 e_LogWritefln('received chunk %d, but expected chunk %d', [chunk
, nextChunk
]);
1983 if (csize
< 0) or (csize
> tf
.chunkSize
) then
1985 e_LogWritefln('received chunk with size %d, but expected chunk size is %d', [csize
, tf
.chunkSize
]);
1989 //e_LogWritefln('got chunk #%d of #%d (csize=%d)', [chunk, (tf.size+tf.chunkSize-1) div tf.chunkSize, csize]);
1990 msg
.ReadData(buf
, csize
);
1991 strm
.WriteBuffer(buf
^, csize
);
1992 nextChunk
:= chunk
+1;
1993 g_Game_StepLoading();
1996 trans_omsg
.Write(Byte(NTF_CLIENT_ACK
));
1997 trans_omsg
.Write(LongInt(chunk
));
1998 if not ftransSendClientMsg(trans_omsg
) then begin result
:= -1; exit
; end;
2000 else if (rMsgId
= NTF_SERVER_ABORT
) then
2002 e_LogWritefln('g_Net_ReceiveResourceFile: server aborted transfer', []);
2008 e_LogWritefln('g_Net_ReceiveResourceFile: invalid server packet type', []);
2012 //stx := stx+GetTimerMS();
2013 //e_LogWritefln('g_Net_ReceiveResourceFile: process stx=%d', [Integer(stx)]);
2016 ENET_EVENT_TYPE_DISCONNECT
:
2018 if (ev
.data
<= NET_DISC_MAX
) then
2019 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' ' + _lc
[TStrings_Locale(Cardinal(I_NET_DISC_NONE
) + ev
.data
)], True);
2025 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' unknown ENet event ' + IntToStr(Ord(ev
.kind
)), True);
2030 if (freePacket
) then begin freePacket
:= false; enet_packet_destroy(ev
.packet
); end;
2033 if g_Net_UserRequestExit() then
2035 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' user abort', True);
2042 if (freePacket
) then enet_packet_destroy(ev
.packet
);
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;
2311 conRegVar('cl_downloadtimeout', @g_Net_DownloadTimeout
, 0.0, 1000000.0, '', 'timeout in seconds, 0 to disable it');
2312 SetLength(NetClients
, 0);
2313 g_Net_DownloadTimeout
:= 60;
2314 NetIn
.Alloc(NET_BUFSIZE
);
2315 NetOut
.Alloc(NET_BUFSIZE
);
2316 NetBuf
[NET_UNRELIABLE
].Alloc(NET_BUFSIZE
*2);
2317 NetBuf
[NET_RELIABLE
].Alloc(NET_BUFSIZE
*2);
2318 trans_omsg
.Alloc(NET_BUFSIZE
);
2322 NetBuf
[NET_UNRELIABLE
].Free();
2323 NetBuf
[NET_RELIABLE
].Free();