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
= 181;
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
101 RequestedFullUpdate
: Boolean;
104 Transfer
: TNetFileTransfer
; // only one transfer may be active
105 NetOut
: array [0..1] of TMsg
;
111 pTNetClient
= ^TNetClient
;
113 AByte
= array of Byte;
116 NetInitDone
: Boolean = False;
117 NetMode
: Byte = NET_NONE
;
118 NetDump
: Boolean = False;
120 NetServerName
: string = 'Unnamed Server';
121 NetPassword
: string = '';
122 NetPort
: Word = 25666;
124 NetAllowRCON
: Boolean = False;
125 NetRCONPassword
: string = '';
127 NetTimeToUpdate
: Cardinal = 0;
128 NetTimeToReliable
: Cardinal = 0;
129 NetTimeToMaster
: Cardinal = 0;
131 NetHost
: pENetHost
= nil;
132 NetPeer
: pENetPeer
= nil;
134 NetAddr
: ENetAddress
;
136 NetPongAddr
: ENetAddress
;
137 NetPongSock
: ENetSocket
= ENET_SOCKET_NULL
;
139 NetUseMaster
: Boolean = True;
140 NetSlistAddr
: ENetAddress
;
141 NetSlistIP
: string = 'mpms.doom2d.org';
142 NetSlistPort
: Word = 25665;
144 NetClientIP
: string = '127.0.0.1';
145 NetClientPort
: Word = 25666;
148 NetBuf
: array [0..1] of TMsg
;
150 NetClients
: array of TNetClient
;
151 NetClientCount
: Byte = 0;
152 NetMaxClients
: Byte = 255;
153 NetBannedHosts
: array of TBanRecord
;
155 NetState
: Integer = NET_STATE_NONE
;
157 NetMyID
: Integer = -1;
158 NetPlrUID1
: Integer = -1;
159 NetPlrUID2
: Integer = -1;
161 NetInterpLevel
: Integer = 1;
162 NetUpdateRate
: Cardinal = 0; // as soon as possible
163 NetRelupdRate
: Cardinal = 18; // around two times a second
164 NetMasterRate
: Cardinal = 60000;
166 NetForcePlayerUpdate
: Boolean = False;
167 NetPredictSelf
: Boolean = True;
168 NetForwardPorts
: Boolean = False;
170 NetGotEverything
: Boolean = False;
171 NetGotKeys
: Boolean = False;
173 {$IFDEF USE_MINIUPNPC}
174 NetPortForwarded
: Word = 0;
175 NetPongForwarded
: Boolean = False;
176 NetIGDControl
: AnsiString;
177 NetIGDService
: TURLStr
;
180 NetPortThread
: TThreadID
= NilThreadId
;
182 NetDumpFile
: TStream
;
184 g_Res_received_map_start
: Boolean = false; // set if we received "map change" event
187 function g_Net_Init(): Boolean;
188 procedure g_Net_Cleanup();
189 procedure g_Net_Free();
190 procedure g_Net_Flush();
192 function g_Net_Host(IPAddr
: LongWord; Port
: enet_uint16
; MaxClients
: Cardinal = 16): Boolean;
193 procedure g_Net_Host_Die();
194 procedure g_Net_Host_Send(ID
: Integer; Reliable
: Boolean; Chan
: Byte = NET_CHAN_GAME
);
195 function g_Net_Host_Update(): enet_size_t
;
197 function g_Net_Connect(IP
: string; Port
: enet_uint16
): Boolean;
198 procedure g_Net_Disconnect(Forced
: Boolean = False);
199 procedure g_Net_Client_Send(Reliable
: Boolean; Chan
: Byte = NET_CHAN_GAME
);
200 function g_Net_Client_Update(): enet_size_t
;
201 function g_Net_Client_UpdateWhileLoading(): enet_size_t
;
203 function g_Net_Client_ByName(Name
: string): pTNetClient
;
204 function g_Net_Client_ByPlayer(PID
: Word): pTNetClient
;
205 function g_Net_ClientName_ByID(ID
: Integer): string;
207 procedure g_Net_SendData(Data
: AByte
; peer
: pENetPeer
; Reliable
: Boolean; Chan
: Byte = NET_CHAN_DOWNLOAD
);
208 //function g_Net_Wait_Event(msgId: Word): TMemoryStream;
209 //function g_Net_Wait_FileInfo (var tf: TNetFileTransfer; asMap: Boolean; out resList: TStringList): Integer;
211 function IpToStr(IP
: LongWord): string;
212 function StrToIp(IPstr
: string; var IP
: LongWord): Boolean;
214 function g_Net_IsHostBanned(IP
: LongWord; Perm
: Boolean = False): Boolean;
215 procedure g_Net_BanHost(IP
: LongWord; Perm
: Boolean = True); overload
;
216 procedure g_Net_BanHost(IP
: string; Perm
: Boolean = True); overload
;
217 function g_Net_UnbanHost(IP
: string): Boolean; overload
;
218 function g_Net_UnbanHost(IP
: LongWord): Boolean; overload
;
219 procedure g_Net_UnbanNonPermHosts();
220 procedure g_Net_SaveBanList();
222 procedure g_Net_DumpStart();
223 procedure g_Net_DumpSendBuffer();
224 procedure g_Net_DumpRecvBuffer(Buf
: penet_uint8
; Len
: LongWord);
225 procedure g_Net_DumpEnd();
227 function g_Net_ForwardPorts(ForwardPongPort
: Boolean = True): Boolean;
228 procedure g_Net_UnforwardPorts();
230 function g_Net_UserRequestExit
: Boolean;
232 function g_Net_SendMapRequest (): Boolean;
233 function g_Net_Wait_MapInfo (var tf
: TNetFileTransfer
; resList
: TStringList
): Integer;
234 function g_Net_RequestResFileInfo (resIndex
: LongInt; out tf
: TNetFileTransfer
): Integer;
235 function g_Net_AbortResTransfer (var tf
: TNetFileTransfer
): Boolean;
236 function g_Net_ReceiveResourceFile (resIndex
: LongInt; var tf
: TNetFileTransfer
; strm
: TStream
): Integer;
243 e_input
, g_nethandler
, g_netmsg
, g_netmaster
, g_player
, g_window
, g_console
,
244 g_main
, g_game
, g_language
, g_weapons
, utils
, ctypes
,
248 FILE_CHUNK_SIZE
= 8192;
251 g_Net_DownloadTimeout
: Single;
254 { /// SERVICE FUNCTIONS /// }
255 procedure clearNetClientTransfers (var nc
: TNetClient
);
257 nc
.Transfer
.stream
.Free
;
258 nc
.Transfer
.diskName
:= ''; // just in case
259 if (nc
.Transfer
.diskBuffer
<> nil) then FreeMem(nc
.Transfer
.diskBuffer
);
260 nc
.Transfer
.stream
:= nil;
261 nc
.Transfer
.diskBuffer
:= nil;
265 procedure clearNetClient (var nc
: TNetClient
);
267 clearNetClientTransfers(nc
);
270 procedure clearNetClients (clearArray
: Boolean);
274 for f
:= Low(NetClients
) to High(NetClients
) do clearNetClient(NetClients
[f
]);
275 if (clearArray
) then SetLength(NetClients
, 0);
279 function g_Net_FindSlot(): Integer;
288 for I
:= Low(NetClients
) to High(NetClients
) do
290 if NetClients
[I
].Used
then
299 if C
>= NetMaxClients
then
307 if (Length(NetClients
) >= NetMaxClients
) then
311 SetLength(NetClients
, Length(NetClients
) + 1);
312 N
:= High(NetClients
);
318 NetClients
[N
].Used
:= True;
319 NetClients
[N
].ID
:= N
;
320 NetClients
[N
].RequestedFullUpdate
:= False;
321 NetClients
[N
].RCONAuth
:= False;
322 NetClients
[N
].Voted
:= False;
323 NetClients
[N
].Player
:= 0;
324 clearNetClientTransfers(NetClients
[N
]); // just in case
330 function g_Net_Init(): Boolean;
338 NetBuf
[NET_UNRELIABLE
].Clear();
339 NetBuf
[NET_RELIABLE
].Clear();
340 //SetLength(NetClients, 0);
341 clearNetClients(true); // clear array
347 NetAddr
.port
:= 25666;
348 SetLength(NetBannedHosts
, 0);
349 if FileExists(DataDir
+ BANLIST_FILENAME
) then
351 Assign(F
, DataDir
+ BANLIST_FILENAME
);
356 if StrToIp(IPstr
, IP
) then
363 Result
:= (enet_initialize() = 0);
366 procedure g_Net_Flush();
370 F
, Chan
: enet_uint32
;
374 Chan
:= NET_CHAN_GAME
;
376 if NetMode
= NET_SERVER
then
377 for T
:= NET_UNRELIABLE
to NET_RELIABLE
do
379 if NetBuf
[T
].CurSize
> 0 then
381 P
:= enet_packet_create(NetBuf
[T
].Data
, NetBuf
[T
].CurSize
, F
);
382 if not Assigned(P
) then continue
;
383 enet_host_broadcast(NetHost
, Chan
, P
);
387 for I
:= Low(NetClients
) to High(NetClients
) do
389 if not NetClients
[I
].Used
then continue
;
390 if NetClients
[I
].NetOut
[T
].CurSize
<= 0 then continue
;
391 P
:= enet_packet_create(NetClients
[I
].NetOut
[T
].Data
, NetClients
[I
].NetOut
[T
].CurSize
, F
);
392 if not Assigned(P
) then continue
;
393 enet_peer_send(NetClients
[I
].Peer
, Chan
, P
);
394 NetClients
[I
].NetOut
[T
].Clear();
397 // next and last iteration is always RELIABLE
398 F
:= LongWord(ENET_PACKET_FLAG_RELIABLE
);
399 Chan
:= NET_CHAN_IMPORTANT
;
401 else if NetMode
= NET_CLIENT
then
402 for T
:= NET_UNRELIABLE
to NET_RELIABLE
do
404 if NetBuf
[T
].CurSize
> 0 then
406 P
:= enet_packet_create(NetBuf
[T
].Data
, NetBuf
[T
].CurSize
, F
);
407 if not Assigned(P
) then continue
;
408 enet_peer_send(NetPeer
, Chan
, P
);
411 // next and last iteration is always RELIABLE
412 F
:= LongWord(ENET_PACKET_FLAG_RELIABLE
);
413 Chan
:= NET_CHAN_IMPORTANT
;
417 procedure g_Net_Cleanup();
421 NetBuf
[NET_UNRELIABLE
].Clear();
422 NetBuf
[NET_RELIABLE
].Clear();
424 //SetLength(NetClients, 0);
425 clearNetClients(true); // clear array
435 NetState
:= NET_STATE_NONE
;
437 NetPongSock
:= ENET_SOCKET_NULL
;
439 NetTimeToMaster
:= 0;
440 NetTimeToUpdate
:= 0;
441 NetTimeToReliable
:= 0;
445 if NetPortThread
<> NilThreadId
then
446 WaitForThreadTerminate(NetPortThread
, 66666);
448 NetPortThread
:= NilThreadId
;
449 g_Net_UnforwardPorts();
455 procedure g_Net_Free();
460 NetInitDone
:= False;
464 { /// SERVER FUNCTIONS /// }
467 function ForwardThread(Param
: Pointer): PtrInt
;
470 if not g_Net_ForwardPorts() then Result
:= -1;
473 function g_Net_Host(IPAddr
: LongWord; Port
: enet_uint16
; MaxClients
: Cardinal = 16): Boolean;
475 if NetMode
<> NET_NONE
then
477 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_INGAME
]);
484 g_Console_Add(_lc
[I_NET_MSG
] + Format(_lc
[I_NET_MSG_HOST
], [Port
]));
485 if not NetInitDone
then
487 if (not g_Net_Init()) then
489 g_Console_Add(_lc
[I_NET_MSG_FERROR
] + _lc
[I_NET_ERR_ENET
]);
497 NetAddr
.host
:= IPAddr
;
498 NetAddr
.port
:= Port
;
500 if NetForwardPorts
then NetPortThread
:= BeginThread(ForwardThread
);
502 NetHost
:= enet_host_create(@NetAddr
, NET_MAXCLIENTS
, NET_CHANS
, 0, 0);
504 if (NetHost
= nil) then
506 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + Format(_lc
[I_NET_ERR_HOST
], [Port
]));
512 NetPongSock
:= enet_socket_create(ENET_SOCKET_TYPE_DATAGRAM
);
513 if NetPongSock
<> ENET_SOCKET_NULL
then
515 NetPongAddr
.host
:= IPAddr
;
516 NetPongAddr
.port
:= NET_PING_PORT
;
517 if enet_socket_bind(NetPongSock
, @NetPongAddr
) < 0 then
519 enet_socket_destroy(NetPongSock
);
520 NetPongSock
:= ENET_SOCKET_NULL
;
523 enet_socket_set_option(NetPongSock
, ENET_SOCKOPT_NONBLOCK
, 1);
526 NetMode
:= NET_SERVER
;
528 NetBuf
[NET_UNRELIABLE
].Clear();
529 NetBuf
[NET_RELIABLE
].Clear();
535 procedure g_Net_Host_Die();
539 if NetMode
<> NET_SERVER
then Exit
;
541 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_HOST_DISCALL
]);
542 for I
:= 0 to High(NetClients
) do
543 if NetClients
[I
].Used
then
544 enet_peer_disconnect(NetClients
[I
].Peer
, NET_DISC_DOWN
);
546 while enet_host_service(NetHost
, @NetEvent
, 1000) > 0 do
547 if NetEvent
.kind
= ENET_EVENT_TYPE_RECEIVE
then
548 enet_packet_destroy(NetEvent
.packet
);
550 for I
:= 0 to High(NetClients
) do
551 if NetClients
[I
].Used
then
553 FreeMemory(NetClients
[I
].Peer
^.data
);
554 NetClients
[I
].Peer
^.data
:= nil;
555 enet_peer_reset(NetClients
[I
].Peer
);
556 NetClients
[I
].Peer
:= nil;
557 NetClients
[I
].Used
:= False;
558 NetClients
[I
].NetOut
[NET_UNRELIABLE
].Free();
559 NetClients
[I
].NetOut
[NET_RELIABLE
].Free();
562 clearNetClients(false); // don't clear array
563 if (NetMPeer
<> nil) and (NetMHost
<> nil) then g_Net_Slist_Disconnect
;
564 if NetPongSock
<> ENET_SOCKET_NULL
then
565 enet_socket_destroy(NetPongSock
);
567 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_HOST_DIE
]);
568 enet_host_destroy(NetHost
);
573 e_WriteLog('NET: Server stopped', TMsgType
.Notify
);
577 procedure g_Net_Host_Send(ID
: Integer; Reliable
: Boolean; Chan
: Byte = NET_CHAN_GAME
);
588 if ID
> High(NetClients
) then Exit
;
589 if NetClients
[ID
].Peer
= nil then Exit
;
591 NetClients
[ID
].NetOut
[T
].Write(Integer(NetOut
.CurSize
));
592 NetClients
[ID
].NetOut
[T
].Write(NetOut
);
597 NetBuf
[T
].Write(Integer(NetOut
.CurSize
));
598 NetBuf
[T
].Write(NetOut
);
601 if NetDump
then g_Net_DumpSendBuffer();
605 procedure g_Net_Host_CheckPings();
611 Ping
: array [0..9] of Byte;
614 if NetPongSock
= ENET_SOCKET_NULL
then Exit
;
616 Buf
.data
:= Addr(Ping
[0]);
617 Buf
.dataLength
:= 2+8;
621 Len
:= enet_socket_receive(NetPongSock
, @ClAddr
, @Buf
, 1);
622 if Len
< 0 then Exit
;
624 if (Ping
[0] = Ord('D')) and (Ping
[1] = Ord('F')) then
626 ClTime
:= Int64(Addr(Ping
[2])^);
629 NetOut
.Write(Byte(Ord('D')));
630 NetOut
.Write(Byte(Ord('F')));
631 NetOut
.Write(NetPort
);
632 NetOut
.Write(ClTime
);
633 g_Net_Slist_WriteInfo();
635 if gPlayer1
<> nil then Inc(NPl
);
636 if gPlayer2
<> nil then Inc(NPl
);
638 NetOut
.Write(gNumBots
);
640 Buf
.data
:= NetOut
.Data
;
641 Buf
.dataLength
:= NetOut
.CurSize
;
642 enet_socket_send(NetPongSock
, @ClAddr
, @Buf
, 1);
650 // server packet type
651 NTF_SERVER_DONE
= 10; // done with this file
652 NTF_SERVER_FILE_INFO
= 11; // sent after client request
653 NTF_SERVER_CHUNK
= 12; // next chunk; chunk number follows
654 NTF_SERVER_ABORT
= 13; // server abort
655 NTF_SERVER_MAP_INFO
= 14;
657 // client packet type
658 NTF_CLIENT_MAP_REQUEST
= 100; // map file request; also, returns list of additional wads to download
659 NTF_CLIENT_FILE_REQUEST
= 101; // resource file request (by index)
660 NTF_CLIENT_ABORT
= 102; // do not send requested file, or abort current transfer
661 NTF_CLIENT_START
= 103; // start transfer; client may resume download by sending non-zero starting chunk
662 NTF_CLIENT_ACK
= 104; // chunk ack; chunk number follows
665 procedure KillClientByFT (var nc
: TNetClient
);
667 e_LogWritefln('disconnected client #%d due to file transfer error', [nc
.ID
], TMsgType
.Warning
);
668 enet_peer_disconnect(nc
.Peer
, NET_DISC_FILE_TIMEOUT
);
669 clearNetClientTransfers(nc
);
673 procedure ProcessHostFileTransfers (var nc
: TNetClient
);
675 tf
: ^TNetFileTransfer
;
683 if (tf
.stream
= nil) then exit
;;
685 // arbitrary timeout number
686 if (ct
-tf
.lastAckTime
>= 5000) then
691 // check if we need to send something
692 if (not tf
.inProgress
) then exit
; // waiting for the initial ack
693 // ok, we're sending chunks
694 if (tf
.lastAckChunk
<> tf
.lastSentChunk
) then exit
;
695 Inc(tf
.lastSentChunk
);
696 // do it one chunk at a time; client ack will advance our chunk counter
697 chunks
:= (tf
.size
+tf
.chunkSize
-1) div tf
.chunkSize
;
699 if (tf
.lastSentChunk
> chunks
) then
705 omsg
.Alloc(NET_BUFSIZE
);
708 if (tf
.lastSentChunk
= chunks
) then
710 // we're done with this file
711 e_LogWritefln('download: client #%d, DONE sending chunks #%d/#%d', [nc
.ID
, tf
.lastSentChunk
, chunks
]);
712 omsg
.Write(Byte(NTF_SERVER_DONE
));
713 clearNetClientTransfers(nc
);
718 omsg
.Write(Byte(NTF_SERVER_CHUNK
));
719 omsg
.Write(LongInt(tf
.lastSentChunk
));
721 rd
:= tf
.size
-(tf
.lastSentChunk
*tf
.chunkSize
);
722 if (rd
> tf
.chunkSize
) then rd
:= tf
.chunkSize
;
723 omsg
.Write(LongInt(rd
));
724 //e_LogWritefln('download: client #%d, sending chunk #%d/#%d (%d bytes)', [nc.ID, tf.lastSentChunk, chunks, rd]);
725 //FIXME: check for errors here
727 tf
.stream
.Seek(tf
.lastSentChunk
*tf
.chunkSize
, soFromBeginning
);
728 tf
.stream
.ReadBuffer(tf
.diskBuffer
^, rd
);
729 omsg
.WriteData(tf
.diskBuffer
, rd
);
736 pkt
:= enet_packet_create(omsg
.Data
, omsg
.CurSize
, ENET_PACKET_FLAG_RELIABLE
);
737 if not Assigned(pkt
) then
742 if (enet_peer_send(nc
.Peer
, NET_CHAN_DOWNLOAD_EX
, pkt
) <> 0) then
753 // received packet is in `NetEvent`
754 procedure ProcessDownloadExPacket ();
762 tf
: ^TNetFileTransfer
;
772 // find client index by peer
773 for f
:= Low(NetClients
) to High(NetClients
) do
775 if (not NetClients
[f
].Used
) then continue
;
776 if (NetClients
[f
].Peer
= NetEvent
.peer
) then
782 //e_LogWritefln('RECEIVE: dlpacket; client=%d (datalen=%u)', [nid, NetEvent.packet^.dataLength]);
784 if (nid
< 0) then exit
; // wtf?!
785 nc
:= @NetClients
[nid
];
787 if (NetEvent
.packet
^.dataLength
= 0) then
793 tf
:= @NetClients
[nid
].Transfer
;
794 tf
.lastAckTime
:= GetTimerMS();
796 cmd
:= Byte(NetEvent
.packet
^.data
^);
797 //e_LogWritefln('RECEIVE: nid=%d; cmd=%u', [nid, cmd]);
799 NTF_CLIENT_FILE_REQUEST
: // file request
801 if (tf
.stream
<> nil) then
806 if (NetEvent
.packet
^.dataLength
< 2) then
811 // new transfer request; build packet
812 if not msg
.Init(NetEvent
.packet
^.data
+1, NetEvent
.packet
^.dataLength
-1, True) then
817 // get resource index
818 ridx
:= msg
.ReadLongInt();
819 if (ridx
< -1) or (ridx
>= gExternalResources
.Count
) then
821 e_LogWritefln('Invalid resource index %d', [ridx
], TMsgType
.Warning
);
825 if (ridx
< 0) then fname
:= MapsDir
+gGameSettings
.WAD
else fname
:= GameDir
+'/wads/'+gExternalResources
[ridx
];
826 if (length(fname
) = 0) then
828 e_WriteLog('Invalid filename: '+fname
, TMsgType
.Warning
);
832 tf
.diskName
:= findDiskWad(fname
);
833 //if (length(tf.diskName) = 0) then tf.diskName := findDiskWad(GameDir+'/wads/'+fname);
834 if (length(tf
.diskName
) = 0) then
836 e_LogWritefln('NETWORK: file "%s" not found!', [fname
], TMsgType
.Fatal
);
842 tf
.hash
:= MD5File(tf
.diskName
);
843 // create file stream
844 tf
.diskName
:= findDiskWad(fname
);
846 tf
.stream
:= openDiskFileRO(tf
.diskName
);
850 if (tf
.stream
= nil) then
852 e_WriteLog(Format('NETWORK: file "%s" not found!', [fname
]), TMsgType
.Fatal
);
856 e_LogWritefln('client #%d requested resource #%d (file is `%s` : `%s`)', [nc
.ID
, ridx
, fname
, tf
.diskName
]);
857 tf
.size
:= tf
.stream
.size
;
858 tf
.chunkSize
:= FILE_CHUNK_SIZE
; // arbitrary
859 tf
.lastSentChunk
:= -1;
860 tf
.lastAckChunk
:= -1;
861 tf
.lastAckTime
:= GetTimerMS();
862 tf
.inProgress
:= False; // waiting for the first ACK or for the cancel
863 GetMem(tf
.diskBuffer
, tf
.chunkSize
);
864 // sent file info message
865 omsg
.Alloc(NET_BUFSIZE
);
868 omsg
.Write(Byte(NTF_SERVER_FILE_INFO
));
871 omsg
.Write(tf
.chunkSize
);
872 omsg
.Write(ExtractFileName(fname
));
873 pkt
:= enet_packet_create(omsg
.Data
, omsg
.CurSize
, ENET_PACKET_FLAG_RELIABLE
);
874 if not Assigned(pkt
) then
879 if (enet_peer_send(nc
.Peer
, NET_CHAN_DOWNLOAD_EX
, pkt
) <> 0) then
888 NTF_CLIENT_ABORT
: // do not send requested file, or abort current transfer
890 e_LogWritefln('client #%d aborted file transfer', [nc
.ID
]);
891 clearNetClientTransfers(nc
^);
893 NTF_CLIENT_START
: // start transfer; client may resume download by sending non-zero starting chunk
895 if not Assigned(tf
.stream
) then
900 if (tf
.lastSentChunk
<> -1) or (tf
.lastAckChunk
<> -1) or (tf
.inProgress
) then
902 // double ack, get lost
906 if (NetEvent
.packet
^.dataLength
< 2) then
912 if not msg
.Init(NetEvent
.packet
^.data
+1, NetEvent
.packet
^.dataLength
-1, True) then
917 chunk
:= msg
.ReadLongInt();
918 if (chunk
< 0) or (chunk
> (tf
.size
+tf
.chunkSize
-1) div tf
.chunkSize
) then
923 e_LogWritefln('client #%d started file transfer from chunk %d', [nc
.ID
, chunk
]);
924 // start sending chunks
925 tf
.inProgress
:= True;
926 tf
.lastSentChunk
:= chunk
-1;
927 tf
.lastAckChunk
:= chunk
-1;
929 NTF_CLIENT_ACK
: // chunk ack; chunk number follows
931 if not Assigned(tf
.stream
) then
936 if (tf
.lastSentChunk
< 0) or (not tf
.inProgress
) then
938 // double ack, get lost
942 if (NetEvent
.packet
^.dataLength
< 2) then
948 if not msg
.Init(NetEvent
.packet
^.data
+1, NetEvent
.packet
^.dataLength
-1, True) then
953 chunk
:= msg
.ReadLongInt();
954 if (chunk
< 0) or (chunk
> (tf
.size
+tf
.chunkSize
-1) div tf
.chunkSize
) then
959 // do it this way, so client may seek, or request retransfers for some reason
960 tf
.lastAckChunk
:= chunk
;
961 tf
.lastSentChunk
:= chunk
;
962 //e_LogWritefln('client #%d acked file transfer chunk %d', [nc.ID, chunk]);
964 NTF_CLIENT_MAP_REQUEST
:
966 e_LogWritefln('client #%d requested map info', [nc
.ID
]);
967 omsg
.Alloc(NET_BUFSIZE
);
970 dfn
:= findDiskWad(MapsDir
+gGameSettings
.WAD
);
971 if (dfn
= '') then dfn
:= '!wad_not_found!.wad'; //FIXME
973 st
:= openDiskFileRO(dfn
);
974 if not assigned(st
) then exit
; //wtf?!
978 omsg
.Write(Byte(NTF_SERVER_MAP_INFO
));
980 omsg
.Write(gGameSettings
.WAD
);
985 // number of external resources for map
986 omsg
.Write(LongInt(gExternalResources
.Count
));
987 // external resource names
988 for f
:= 0 to gExternalResources
.Count
-1 do
990 omsg
.Write(ExtractFileName(gExternalResources
[f
])); // GameDir+'/wads/'+ResList.Strings[i]
993 pkt
:= enet_packet_create(omsg
.Data
, omsg
.CurSize
, ENET_PACKET_FLAG_RELIABLE
);
994 if not Assigned(pkt
) then exit
;
995 if (enet_peer_send(nc
.Peer
, NET_CHAN_DOWNLOAD_EX
, pkt
) <> 0) then exit
;
1002 KillClientByFT(NetClients
[nid
]);
1009 function g_Net_Host_Update(): enet_size_t
;
1022 if NetUseMaster
then g_Net_Slist_Check
;
1023 g_Net_Host_CheckPings
;
1025 //ctt := -GetTimerMS();
1026 // process file transfers
1027 for f
:= Low(NetClients
) to High(NetClients
) do
1029 if (not NetClients
[f
].Used
) then continue
;
1030 if (NetClients
[f
].Transfer
.stream
= nil) then continue
;
1031 ProcessHostFileTransfers(NetClients
[f
]);
1034 ctt := ctt+GetTimerMS();
1035 if (ctt > 1) then e_LogWritefln('all transfers: [%d]', [Integer(ctt)]);
1038 while (enet_host_service(NetHost
, @NetEvent
, 0) > 0) do
1040 case (NetEvent
.kind
) of
1041 ENET_EVENT_TYPE_CONNECT
:
1043 IP
:= IpToStr(NetEvent
.Peer
^.address
.host
);
1044 Port
:= NetEvent
.Peer
^.address
.port
;
1045 g_Console_Add(_lc
[I_NET_MSG
] +
1046 Format(_lc
[I_NET_MSG_HOST_CONN
], [IP
, Port
]));
1048 if (NetEvent
.data
<> NET_PROTOCOL_VER
) then
1050 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_HOST_REJECT
] +
1051 _lc
[I_NET_DISC_PROTOCOL
]);
1052 NetEvent
.peer
^.data
:= GetMemory(SizeOf(Byte));
1053 Byte(NetEvent
.peer
^.data
^) := 255;
1054 enet_peer_disconnect(NetEvent
.peer
, NET_DISC_PROTOCOL
);
1055 enet_host_flush(NetHost
);
1059 ID
:= g_Net_FindSlot();
1063 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_HOST_REJECT
] +
1064 _lc
[I_NET_DISC_FULL
]);
1065 NetEvent
.Peer
^.data
:= GetMemory(SizeOf(Byte));
1066 Byte(NetEvent
.peer
^.data
^) := 255;
1067 enet_peer_disconnect(NetEvent
.peer
, NET_DISC_FULL
);
1068 enet_host_flush(NetHost
);
1072 NetClients
[ID
].Peer
:= NetEvent
.peer
;
1073 NetClients
[ID
].Peer
^.data
:= GetMemory(SizeOf(Byte));
1074 Byte(NetClients
[ID
].Peer
^.data
^) := ID
;
1075 NetClients
[ID
].State
:= NET_STATE_AUTH
;
1076 NetClients
[ID
].RCONAuth
:= False;
1077 NetClients
[ID
].NetOut
[NET_UNRELIABLE
].Alloc(NET_BUFSIZE
*2);
1078 NetClients
[ID
].NetOut
[NET_RELIABLE
].Alloc(NET_BUFSIZE
*2);
1079 clearNetClientTransfers(NetClients
[ID
]); // just in case
1081 enet_peer_timeout(NetEvent
.peer
, ENET_PEER_TIMEOUT_LIMIT
* 2, ENET_PEER_TIMEOUT_MINIMUM
* 2, ENET_PEER_TIMEOUT_MAXIMUM
* 2);
1083 Inc(NetClientCount
);
1084 g_Console_Add(_lc
[I_NET_MSG
] + Format(_lc
[I_NET_MSG_HOST_ADD
], [ID
]));
1087 ENET_EVENT_TYPE_RECEIVE
:
1089 //e_LogWritefln('RECEIVE: chan=%u', [NetEvent.channelID]);
1090 if (NetEvent
.channelID
= NET_CHAN_DOWNLOAD_EX
) then
1092 ProcessDownloadExPacket();
1096 ID
:= Byte(NetEvent
.peer
^.data
^);
1097 if ID
> High(NetClients
) then Exit
;
1098 TC
:= @NetClients
[ID
];
1100 if NetDump
then g_Net_DumpRecvBuffer(NetEvent
.packet
^.data
, NetEvent
.packet
^.dataLength
);
1101 g_Net_Host_HandlePacket(TC
, NetEvent
.packet
, g_Net_HostMsgHandler
);
1105 ENET_EVENT_TYPE_DISCONNECT
:
1107 ID
:= Byte(NetEvent
.peer
^.data
^);
1108 if ID
> High(NetClients
) then Exit
;
1109 clearNetClient(NetClients
[ID
]);
1110 TC
:= @NetClients
[ID
];
1111 if TC
= nil then Exit
;
1113 if not (TC
^.Used
) then Exit
;
1115 TP
:= g_Player_Get(TC
^.Player
);
1120 TP
.Kill(K_SIMPLEKILL
, 0, HIT_DISCON
);
1121 g_Console_Add(Format(_lc
[I_PLAYER_LEAVE
], [TP
.Name
]), True);
1122 e_WriteLog('NET: Client ' + TP
.Name
+ ' [' + IntToStr(ID
) + '] disconnected.', TMsgType
.Notify
);
1123 g_Player_Remove(TP
.UID
);
1127 TC
^.State
:= NET_STATE_NONE
;
1130 TC
^.RequestedFullUpdate
:= False;
1131 TC
^.NetOut
[NET_UNRELIABLE
].Free();
1132 TC
^.NetOut
[NET_RELIABLE
].Free();
1134 FreeMemory(NetEvent
.peer
^.data
);
1135 NetEvent
.peer
^.data
:= nil;
1136 g_Console_Add(_lc
[I_NET_MSG
] + Format(_lc
[I_NET_MSG_HOST_DISC
], [ID
]));
1137 Dec(NetClientCount
);
1139 if NetUseMaster
then g_Net_Slist_Update
;
1146 { /// CLIENT FUNCTIONS /// }
1149 procedure g_Net_Disconnect(Forced
: Boolean = False);
1151 if NetMode
<> NET_CLIENT
then Exit
;
1152 if (NetHost
= nil) or (NetPeer
= nil) then Exit
;
1156 enet_peer_disconnect(NetPeer
, NET_DISC_NONE
);
1158 while (enet_host_service(NetHost
, @NetEvent
, 1500) > 0) do
1160 if (NetEvent
.kind
= ENET_EVENT_TYPE_DISCONNECT
) then
1166 if (NetEvent
.kind
= ENET_EVENT_TYPE_RECEIVE
) then
1167 enet_packet_destroy(NetEvent
.packet
);
1170 if NetPeer
<> nil then
1172 enet_peer_reset(NetPeer
);
1178 e_WriteLog('NET: Kicked from server: ' + IntToStr(NetEvent
.data
), TMsgType
.Notify
);
1179 if (NetEvent
.data
<= NET_DISC_MAX
) then
1180 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_KICK
] +
1181 _lc
[TStrings_Locale(Cardinal(I_NET_DISC_NONE
) + NetEvent
.data
)], True);
1184 if NetHost
<> nil then
1186 enet_host_destroy(NetHost
);
1189 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_CLIENT_DISC
]);
1192 e_WriteLog('NET: Disconnected', TMsgType
.Notify
);
1195 procedure g_Net_Client_Send(Reliable
: Boolean; Chan
: Byte = NET_CHAN_GAME
);
1202 T
:= NET_UNRELIABLE
;
1205 NetBuf
[T
].Write(Integer(NetOut
.CurSize
));
1206 NetBuf
[T
].Write(NetOut
);
1208 if NetDump
then g_Net_DumpSendBuffer();
1210 g_Net_Flush(); // FIXME: for now, send immediately
1213 function g_Net_Client_Update(): enet_size_t
;
1216 while (enet_host_service(NetHost
, @NetEvent
, 0) > 0) do
1218 case NetEvent
.kind
of
1219 ENET_EVENT_TYPE_RECEIVE
:
1221 if (NetEvent
.channelID
= NET_CHAN_DOWNLOAD_EX
) then continue
; // ignore all download packets, they're processed by separate code
1222 if NetDump
then g_Net_DumpRecvBuffer(NetEvent
.packet
^.data
, NetEvent
.packet
^.dataLength
);
1223 g_Net_Client_HandlePacket(NetEvent
.packet
, g_Net_ClientMsgHandler
);
1226 ENET_EVENT_TYPE_DISCONNECT
:
1228 g_Net_Disconnect(True);
1236 function g_Net_Client_UpdateWhileLoading(): enet_size_t
;
1239 while (enet_host_service(NetHost
, @NetEvent
, 0) > 0) do
1241 case NetEvent
.kind
of
1242 ENET_EVENT_TYPE_RECEIVE
:
1244 if (NetEvent
.channelID
= NET_CHAN_DOWNLOAD_EX
) then continue
; // ignore all download packets, they're processed by separate code
1245 if NetDump
then g_Net_DumpRecvBuffer(NetEvent
.packet
^.data
, NetEvent
.packet
^.dataLength
);
1246 g_Net_Client_HandlePacket(NetEvent
.packet
, g_Net_ClientLightMsgHandler
);
1249 ENET_EVENT_TYPE_DISCONNECT
:
1251 g_Net_Disconnect(True);
1260 function g_Net_Connect(IP
: string; Port
: enet_uint16
): Boolean;
1263 TimeoutTime
, T
: Int64;
1265 if NetMode
<> NET_NONE
then
1267 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_ERR_INGAME
], True);
1274 g_Console_Add(_lc
[I_NET_MSG
] + Format(_lc
[I_NET_MSG_CLIENT_CONN
],
1276 if not NetInitDone
then
1278 if (not g_Net_Init()) then
1280 g_Console_Add(_lc
[I_NET_MSG_FERROR
] + _lc
[I_NET_ERR_ENET
], True);
1285 NetInitDone
:= True;
1288 NetHost
:= enet_host_create(nil, 1, NET_CHANS
, 0, 0);
1290 if (NetHost
= nil) then
1292 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CLIENT
], True);
1298 enet_address_set_host(@NetAddr
, PChar(Addr(IP
[1])));
1299 NetAddr
.port
:= Port
;
1301 NetPeer
:= enet_host_connect(NetHost
, @NetAddr
, NET_CHANS
, NET_PROTOCOL_VER
);
1303 if (NetPeer
= nil) then
1305 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CLIENT
], True);
1306 enet_host_destroy(NetHost
);
1312 // предупредить что ждем слишком долго через N секунд
1313 TimeoutTime
:= GetTimer() + NET_CONNECT_TIMEOUT
;
1318 while (enet_host_service(NetHost
, @NetEvent
, 0) > 0) do
1320 if (NetEvent
.kind
= ENET_EVENT_TYPE_CONNECT
) then
1322 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_CLIENT_DONE
]);
1323 NetMode
:= NET_CLIENT
;
1325 enet_peer_timeout(NetPeer
, ENET_PEER_TIMEOUT_LIMIT
* 2, ENET_PEER_TIMEOUT_MINIMUM
* 2, ENET_PEER_TIMEOUT_MAXIMUM
* 2);
1327 NetClientPort
:= Port
;
1335 if T
> TimeoutTime
then
1337 TimeoutTime
:= T
+ NET_CONNECT_TIMEOUT
* 100; // одного предупреждения хватит
1338 g_Console_Add(_lc
[I_NET_MSG_TIMEOUT_WARN
], True);
1339 g_Console_Add(Format(_lc
[I_NET_MSG_PORTS
], [Integer(Port
), Integer(NET_PING_PORT
)]), True);
1342 ProcessLoading(true);
1344 if e_KeyPressed(IK_SPACE
) or e_KeyPressed(IK_ESCAPE
) or e_KeyPressed(VK_ESCAPE
) or
1345 e_KeyPressed(JOY0_JUMP
) or e_KeyPressed(JOY1_JUMP
) or e_KeyPressed(JOY2_JUMP
) or e_KeyPressed(JOY3_JUMP
) then
1349 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_TIMEOUT
], True);
1350 g_Console_Add(Format(_lc
[I_NET_MSG_PORTS
], [Integer(Port
), Integer(NET_PING_PORT
)]), True);
1351 if NetPeer
<> nil then enet_peer_reset(NetPeer
);
1352 if NetHost
<> nil then
1354 enet_host_destroy(NetHost
);
1361 function IpToStr(IP
: LongWord): string;
1366 Result
:= IntToStr(PByte(Ptr
+ 0)^) + '.';
1367 Result
:= Result
+ IntToStr(PByte(Ptr
+ 1)^) + '.';
1368 Result
:= Result
+ IntToStr(PByte(Ptr
+ 2)^) + '.';
1369 Result
:= Result
+ IntToStr(PByte(Ptr
+ 3)^);
1372 function StrToIp(IPstr
: string; var IP
: LongWord): Boolean;
1376 Result
:= enet_address_set_host(@EAddr
, PChar(@IPstr
[1])) = 0;
1380 function g_Net_Client_ByName(Name
: string): pTNetClient
;
1386 for a
:= Low(NetClients
) to High(NetClients
) do
1387 if (NetClients
[a
].Used
) and (NetClients
[a
].State
= NET_STATE_GAME
) then
1389 pl
:= g_Player_Get(NetClients
[a
].Player
);
1390 if pl
= nil then continue
;
1391 if Copy(LowerCase(pl
.Name
), 1, Length(Name
)) <> LowerCase(Name
) then continue
;
1392 if NetClients
[a
].Peer
<> nil then
1394 Result
:= @NetClients
[a
];
1400 function g_Net_Client_ByPlayer(PID
: Word): pTNetClient
;
1405 for a
:= Low(NetClients
) to High(NetClients
) do
1406 if (NetClients
[a
].Used
) and (NetClients
[a
].State
= NET_STATE_GAME
) then
1407 if NetClients
[a
].Player
= PID
then
1409 Result
:= @NetClients
[a
];
1414 function g_Net_ClientName_ByID(ID
: Integer): string;
1420 if ID
= NET_EVERYONE
then
1422 for a
:= Low(NetClients
) to High(NetClients
) do
1423 if (NetClients
[a
].ID
= ID
) and (NetClients
[a
].Used
) and (NetClients
[a
].State
= NET_STATE_GAME
) then
1425 pl
:= g_Player_Get(NetClients
[a
].Player
);
1426 if pl
= nil then Exit
;
1431 procedure g_Net_SendData(Data
: AByte
; peer
: pENetPeer
; Reliable
: Boolean; Chan
: Byte = NET_CHAN_DOWNLOAD
);
1435 dataLength
: Cardinal;
1437 dataLength
:= Length(Data
);
1440 F
:= LongWord(ENET_PACKET_FLAG_RELIABLE
)
1444 if (peer
<> nil) then
1446 P
:= enet_packet_create(@Data
[0], dataLength
, F
);
1447 if not Assigned(P
) then Exit
;
1448 enet_peer_send(peer
, Chan
, P
);
1452 P
:= enet_packet_create(@Data
[0], dataLength
, F
);
1453 if not Assigned(P
) then Exit
;
1454 enet_host_broadcast(NetHost
, Chan
, P
);
1457 enet_host_flush(NetHost
);
1460 function g_Net_UserRequestExit
: Boolean;
1462 Result
:= e_KeyPressed(IK_SPACE
) or
1463 e_KeyPressed(IK_ESCAPE
) or
1464 e_KeyPressed(VK_ESCAPE
) or
1465 e_KeyPressed(JOY0_JUMP
) or
1466 e_KeyPressed(JOY1_JUMP
) or
1467 e_KeyPressed(JOY2_JUMP
) or
1468 e_KeyPressed(JOY3_JUMP
)
1472 function g_Net_Wait_Event(msgId: Word): TMemoryStream;
1477 stream: TMemoryStream;
1480 FillChar(ev, SizeOf(ev), 0);
1483 status := enet_host_service(NetHost, @ev, Trunc(g_Net_DownloadTimeout * 1000));
1487 ENET_EVENT_TYPE_RECEIVE:
1489 Ptr := ev.packet^.data;
1490 rMsgId := Byte(Ptr^);
1491 if rMsgId = msgId then
1493 stream := TMemoryStream.Create;
1494 stream.SetSize(ev.packet^.dataLength);
1495 stream.WriteBuffer(Ptr^, ev.packet^.dataLength);
1496 stream.Seek(0, soFromBeginning);
1497 status := 1 (* received *)
1501 (* looks that game state always received, so ignore it *)
1502 e_LogWritefln('g_Net_Wait_Event(%s): skip message %s', [msgId, rMsgId]);
1503 status := 2 (* continue *)
1506 ENET_EVENT_TYPE_DISCONNECT:
1508 if (ev.data <= NET_DISC_MAX) then
1509 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' ' + _lc[TStrings_Locale(Cardinal(I_NET_DISC_NONE) + ev.data)], True);
1510 status := -2 (* error: disconnected *)
1513 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' unknown ENet event ' + IntToStr(Ord(ev.kind)), True);
1514 status := -3 (* error: unknown event *)
1516 enet_packet_destroy(ev.packet)
1520 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' timeout reached', True);
1521 status := 0 (* error: timeout *)
1523 ProcessLoading(true);
1524 until (status <> 2) or g_Net_UserRequestExit();
1530 function getNewTimeoutEnd (): Int64;
1532 result
:= GetTimerMS();
1533 if (g_Net_DownloadTimeout
<= 0) then
1535 result
:= result
+1000*60*3; // 3 minutes
1539 result
:= result
+trunc(g_Net_DownloadTimeout
*1000);
1544 function g_Net_SendMapRequest (): Boolean;
1550 e_LogWritefln('sending map request...', []);
1552 msg
.Alloc(NET_BUFSIZE
);
1555 msg
.Write(Byte(NTF_CLIENT_MAP_REQUEST
));
1556 e_LogWritefln(' request size is %d', [msg
.CurSize
]);
1557 pkt
:= enet_packet_create(msg
.Data
, msg
.CurSize
, ENET_PACKET_FLAG_RELIABLE
);
1558 if not Assigned(pkt
) then exit
;
1559 if (enet_peer_send(NetPeer
, NET_CHAN_DOWNLOAD_EX
, pkt
) <> 0) then exit
;
1560 enet_host_flush(NetHost
);
1568 // returns `false` on error or user abort
1577 // 2 on server abort
1578 // for maps, first `tf.diskName` name will be map wad name, and `tf.hash`/`tf.size` will contain map info
1579 function g_Net_Wait_MapInfo (var tf
: TNetFileTransfer
; resList
: TStringList
): Integer;
1585 freePacket
: Boolean = false;
1591 FillChar(ev
, SizeOf(ev
), 0);
1594 ett
:= getNewTimeoutEnd();
1596 status
:= enet_host_service(NetHost
, @ev
, 300);
1597 if (status
< 0) then
1599 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' network error', True);
1603 if (status
= 0) then
1605 // check for timeout
1609 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' timeout reached', True);
1618 ENET_EVENT_TYPE_RECEIVE
:
1621 if (ev
.channelID
<> NET_CHAN_DOWNLOAD_EX
) then
1623 //e_LogWritefln('g_Net_Wait_MapInfo: skip message from non-transfer channel', []);
1624 freePacket
:= false;
1625 g_Net_Client_HandlePacket(ev
.packet
, g_Net_ClientLightMsgHandler
);
1626 if (g_Res_received_map_start
) then begin result
:= -666; exit
; end;
1630 ett
:= getNewTimeoutEnd();
1631 if (ev
.packet
.dataLength
< 1) then
1633 e_LogWritefln('g_Net_Wait_MapInfo: invalid server packet (no data)', []);
1637 Ptr
:= ev
.packet
^.data
;
1638 rMsgId
:= Byte(Ptr
^);
1639 e_LogWritefln('g_Net_Wait_MapInfo: got message %u from server (dataLength=%u)', [rMsgId
, ev
.packet
^.dataLength
]);
1640 if (rMsgId
= NTF_SERVER_FILE_INFO
) then
1642 e_LogWritefln('g_Net_Wait_MapInfo: waiting for map info reply, but got file info reply', []);
1646 else if (rMsgId
= NTF_SERVER_ABORT
) then
1648 e_LogWritefln('g_Net_Wait_MapInfo: server aborted transfer', []);
1652 else if (rMsgId
= NTF_SERVER_MAP_INFO
) then
1654 e_LogWritefln('g_Net_Wait_MapInfo: creating map info packet...', []);
1655 if not msg
.Init(ev
.packet
^.data
+1, ev
.packet
^.dataLength
-1, True) then exit
;
1656 e_LogWritefln('g_Net_Wait_MapInfo: parsing map info packet (rd=%d; max=%d)...', [msg
.ReadCount
, msg
.MaxSize
]);
1659 tf
.diskName
:= msg
.ReadString();
1660 e_LogWritefln('g_Net_Wait_MapInfo: map wad is `%s`', [tf
.diskName
]);
1662 tf
.hash
:= msg
.ReadMD5();
1664 tf
.size
:= msg
.ReadLongInt();
1665 e_LogWritefln('g_Net_Wait_MapInfo: map wad size is %d', [tf
.size
]);
1666 // number of external resources for map
1667 rc
:= msg
.ReadLongInt();
1668 if (rc
< 0) or (rc
> 1024) then
1670 e_LogWritefln('g_Net_Wait_Event: invalid number of map external resources (%d)', [rc
]);
1674 e_LogWritefln('g_Net_Wait_MapInfo: map external resource count is %d', [rc
]);
1675 // external resource names
1676 for f
:= 0 to rc
-1 do
1678 s
:= ExtractFileName(msg
.ReadString());
1679 if (length(s
) = 0) then
1686 e_LogWritefln('g_Net_Wait_MapInfo: got map info', []);
1687 Result
:= 0; // success
1692 e_LogWritefln('g_Net_Wait_Event: invalid server packet type', []);
1698 ENET_EVENT_TYPE_DISCONNECT
:
1700 if (ev
.data
<= NET_DISC_MAX
) then
1701 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' ' + _lc
[TStrings_Locale(Cardinal(I_NET_DISC_NONE
) + ev
.data
)], True);
1707 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' unknown ENet event ' + IntToStr(Ord(ev
.kind
)), True);
1712 if (freePacket
) then begin freePacket
:= false; enet_packet_destroy(ev
.packet
); end;
1714 ProcessLoading(true);
1715 if g_Net_UserRequestExit() then
1717 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' user abort', True);
1723 if (freePacket
) then enet_packet_destroy(ev
.packet
);
1728 // returns `false` on error or user abort
1730 // diskName (actually, base name)
1738 // 2 on server abort
1739 // for maps, first `tf.diskName` name will be map wad name, and `tf.hash`/`tf.size` will contain map info
1740 function g_Net_RequestResFileInfo (resIndex
: LongInt; out tf
: TNetFileTransfer
): Integer;
1746 freePacket
: Boolean = false;
1752 msg
.Alloc(NET_BUFSIZE
);
1755 msg
.Write(Byte(NTF_CLIENT_FILE_REQUEST
));
1756 msg
.Write(resIndex
);
1757 pkt
:= enet_packet_create(msg
.Data
, msg
.CurSize
, ENET_PACKET_FLAG_RELIABLE
);
1758 if not Assigned(pkt
) then
1763 if (enet_peer_send(NetPeer
, NET_CHAN_DOWNLOAD_EX
, pkt
) <> 0) then
1772 FillChar(ev
, SizeOf(ev
), 0);
1775 ett
:= getNewTimeoutEnd();
1777 status
:= enet_host_service(NetHost
, @ev
, 300);
1778 if (status
< 0) then
1780 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' network error', True);
1784 if (status
= 0) then
1786 // check for timeout
1790 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' timeout reached', True);
1799 ENET_EVENT_TYPE_RECEIVE
:
1802 if (ev
.channelID
<> NET_CHAN_DOWNLOAD_EX
) then
1804 //e_LogWriteln('g_Net_Wait_Event: skip message from non-transfer channel');
1805 freePacket
:= false;
1806 g_Net_Client_HandlePacket(ev
.packet
, g_Net_ClientLightMsgHandler
);
1807 if (g_Res_received_map_start
) then begin result
:= -666; exit
; end;
1811 ett
:= getNewTimeoutEnd();
1812 if (ev
.packet
.dataLength
< 1) then
1814 e_LogWriteln('g_Net_Wait_Event: invalid server packet (no data)');
1818 Ptr
:= ev
.packet
^.data
;
1819 rMsgId
:= Byte(Ptr
^);
1820 e_LogWritefln('received transfer packet with id %d (%u bytes)', [rMsgId
, ev
.packet
^.dataLength
]);
1821 if (rMsgId
= NTF_SERVER_FILE_INFO
) then
1823 if not msg
.Init(ev
.packet
^.data
+1, ev
.packet
^.dataLength
-1, True) then exit
;
1824 tf
.hash
:= msg
.ReadMD5();
1825 tf
.size
:= msg
.ReadLongInt();
1826 tf
.chunkSize
:= msg
.ReadLongInt();
1827 tf
.diskName
:= ExtractFileName(msg
.readString());
1828 if (tf
.size
< 0) or (tf
.chunkSize
<> FILE_CHUNK_SIZE
) or (length(tf
.diskName
) = 0) then
1830 e_LogWritefln('g_Net_RequestResFileInfo: invalid file info packet', []);
1834 e_LogWritefln('got file info for resource #%d: size=%d; name=%s', [resIndex
, tf
.size
, tf
.diskName
]);
1835 Result
:= 0; // success
1838 else if (rMsgId
= NTF_SERVER_ABORT
) then
1840 e_LogWriteln('g_Net_RequestResFileInfo: server aborted transfer');
1844 else if (rMsgId
= NTF_SERVER_MAP_INFO
) then
1846 e_LogWriteln('g_Net_RequestResFileInfo: waiting for map info reply, but got file info reply');
1852 e_LogWriteln('g_Net_RequestResFileInfo: invalid server packet type');
1858 ENET_EVENT_TYPE_DISCONNECT
:
1860 if (ev
.data
<= NET_DISC_MAX
) then
1861 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' ' + _lc
[TStrings_Locale(Cardinal(I_NET_DISC_NONE
) + ev
.data
)], True);
1867 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' unknown ENet event ' + IntToStr(Ord(ev
.kind
)), True);
1872 if (freePacket
) then begin freePacket
:= false; enet_packet_destroy(ev
.packet
); end;
1874 ProcessLoading(true);
1875 if g_Net_UserRequestExit() then
1877 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' user abort', True);
1883 if (freePacket
) then enet_packet_destroy(ev
.packet
);
1888 function g_Net_AbortResTransfer (var tf
: TNetFileTransfer
): Boolean;
1894 e_LogWritefln('aborting file transfer...', []);
1896 msg
.Alloc(NET_BUFSIZE
);
1899 msg
.Write(Byte(NTF_CLIENT_ABORT
));
1900 pkt
:= enet_packet_create(msg
.Data
, msg
.CurSize
, ENET_PACKET_FLAG_RELIABLE
);
1901 if not Assigned(pkt
) then exit
;
1902 if (enet_peer_send(NetPeer
, NET_CHAN_DOWNLOAD_EX
, pkt
) <> 0) then exit
;
1903 enet_host_flush(NetHost
);
1911 // returns `false` on error or user abort
1920 // 2 on server abort
1921 // for maps, first `tf.diskName` name will be map wad name, and `tf.hash`/`tf.size` will contain map info
1922 function g_Net_ReceiveResourceFile (resIndex
: LongInt; var tf
: TNetFileTransfer
; strm
: TStream
): Integer;
1929 freePacket
: Boolean = false;
1932 nextChunk
: Integer = 0;
1933 chunkTotal
: Integer;
1941 msg
.Alloc(NET_BUFSIZE
);
1944 msg
.Write(Byte(NTF_CLIENT_START
));
1945 msg
.Write(LongInt(0));
1946 pkt
:= enet_packet_create(msg
.Data
, msg
.CurSize
, ENET_PACKET_FLAG_RELIABLE
);
1947 if not Assigned(pkt
) then exit
;
1948 if (enet_peer_send(NetPeer
, NET_CHAN_DOWNLOAD_EX
, pkt
) <> 0) then exit
;
1953 chunkTotal
:= (tf
.size
+tf
.chunkSize
-1) div tf
.chunkSize
;
1954 e_LogWritefln('receiving file `%s` (%d chunks)', [tf
.diskName
, chunkTotal
], TMsgType
.Notify
);
1955 g_Game_SetLoadingText('downloading "'+ExtractFileName(tf
.diskName
)+'"', chunkTotal
, False);
1957 // wait for reply data
1958 FillChar(ev
, SizeOf(ev
), 0);
1960 GetMem(buf
, tf
.chunkSize
);
1962 ett
:= getNewTimeoutEnd();
1964 //stx := -GetTimerMS();
1965 status
:= enet_host_service(NetHost
, @ev
, 300);
1966 if (status
< 0) then
1968 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' network error', True);
1972 if (status
= 0) then
1974 // check for timeout
1978 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' timeout reached', True);
1987 ENET_EVENT_TYPE_RECEIVE
:
1990 if (ev
.channelID
<> NET_CHAN_DOWNLOAD_EX
) then
1992 //e_LogWritefln('g_Net_Wait_Event: skip message from non-transfer channel', []);
1993 freePacket
:= false;
1994 g_Net_Client_HandlePacket(ev
.packet
, g_Net_ClientLightMsgHandler
);
1995 if (g_Res_received_map_start
) then begin result
:= -666; exit
; end;
1999 //stx := stx+GetTimerMS();
2000 //e_LogWritefln('g_Net_ReceiveResourceFile: stx=%d', [Integer(stx)]);
2001 //stx := -GetTimerMS();
2002 ett
:= getNewTimeoutEnd();
2003 if (ev
.packet
.dataLength
< 1) then
2005 e_LogWritefln('g_Net_ReceiveResourceFile: invalid server packet (no data)', []);
2009 Ptr
:= ev
.packet
^.data
;
2010 rMsgId
:= Byte(Ptr
^);
2011 if (rMsgId
= NTF_SERVER_DONE
) then
2013 e_LogWritefln('file transfer complete.', []);
2017 else if (rMsgId
= NTF_SERVER_CHUNK
) then
2019 if not msg
.Init(ev
.packet
^.data
+1, ev
.packet
^.dataLength
-1, True) then exit
;
2020 chunk
:= msg
.ReadLongInt();
2021 csize
:= msg
.ReadLongInt();
2022 if (chunk
<> nextChunk
) then
2024 e_LogWritefln('received chunk %d, but expected chunk %d', [chunk
, nextChunk
]);
2028 if (csize
< 0) or (csize
> tf
.chunkSize
) then
2030 e_LogWritefln('received chunk with size %d, but expected chunk size is %d', [csize
, tf
.chunkSize
]);
2034 //e_LogWritefln('got chunk #%d of #%d (csize=%d)', [chunk, (tf.size+tf.chunkSize-1) div tf.chunkSize, csize]);
2035 msg
.ReadData(buf
, csize
);
2036 strm
.WriteBuffer(buf
^, csize
);
2037 nextChunk
:= chunk
+1;
2038 g_Game_StepLoading();
2040 omsg
.Alloc(NET_BUFSIZE
);
2043 omsg
.Write(Byte(NTF_CLIENT_ACK
));
2044 omsg
.Write(LongInt(chunk
));
2045 pkt
:= enet_packet_create(omsg
.Data
, omsg
.CurSize
, ENET_PACKET_FLAG_RELIABLE
);
2046 if not Assigned(pkt
) then exit
;
2047 if (enet_peer_send(NetPeer
, NET_CHAN_DOWNLOAD_EX
, pkt
) <> 0) then exit
;
2052 else if (rMsgId
= NTF_SERVER_ABORT
) then
2054 e_LogWritefln('g_Net_ReceiveResourceFile: server aborted transfer', []);
2060 e_LogWritefln('g_Net_ReceiveResourceFile: invalid server packet type', []);
2064 //stx := stx+GetTimerMS();
2065 //e_LogWritefln('g_Net_ReceiveResourceFile: process stx=%d', [Integer(stx)]);
2068 ENET_EVENT_TYPE_DISCONNECT
:
2070 if (ev
.data
<= NET_DISC_MAX
) then
2071 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' ' + _lc
[TStrings_Locale(Cardinal(I_NET_DISC_NONE
) + ev
.data
)], True);
2077 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' unknown ENet event ' + IntToStr(Ord(ev
.kind
)), True);
2082 if (freePacket
) then begin freePacket
:= false; enet_packet_destroy(ev
.packet
); end;
2084 ProcessLoading(true);
2085 if g_Net_UserRequestExit() then
2087 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' user abort', True);
2094 if (freePacket
) then enet_packet_destroy(ev
.packet
);
2099 function g_Net_IsHostBanned(IP
: LongWord; Perm
: Boolean = False): Boolean;
2104 if NetBannedHosts
= nil then
2106 for I
:= 0 to High(NetBannedHosts
) do
2107 if (NetBannedHosts
[I
].IP
= IP
) and ((not Perm
) or (NetBannedHosts
[I
].Perm
)) then
2114 procedure g_Net_BanHost(IP
: LongWord; Perm
: Boolean = True); overload
;
2120 if g_Net_IsHostBanned(IP
, Perm
) then
2124 for I
:= Low(NetBannedHosts
) to High(NetBannedHosts
) do
2125 if NetBannedHosts
[I
].IP
= 0 then
2133 SetLength(NetBannedHosts
, Length(NetBannedHosts
) + 1);
2134 P
:= High(NetBannedHosts
);
2137 NetBannedHosts
[P
].IP
:= IP
;
2138 NetBannedHosts
[P
].Perm
:= Perm
;
2141 procedure g_Net_BanHost(IP
: string; Perm
: Boolean = True); overload
;
2146 b
:= StrToIp(IP
, a
);
2148 g_Net_BanHost(a
, Perm
);
2151 procedure g_Net_UnbanNonPermHosts();
2155 if NetBannedHosts
= nil then
2157 for I
:= Low(NetBannedHosts
) to High(NetBannedHosts
) do
2158 if (NetBannedHosts
[I
].IP
> 0) and not NetBannedHosts
[I
].Perm
then
2160 NetBannedHosts
[I
].IP
:= 0;
2161 NetBannedHosts
[I
].Perm
:= True;
2165 function g_Net_UnbanHost(IP
: string): Boolean; overload
;
2169 Result
:= StrToIp(IP
, a
);
2171 Result
:= g_Net_UnbanHost(a
);
2174 function g_Net_UnbanHost(IP
: LongWord): Boolean; overload
;
2181 if NetBannedHosts
= nil then
2183 for I
:= 0 to High(NetBannedHosts
) do
2184 if NetBannedHosts
[I
].IP
= IP
then
2186 NetBannedHosts
[I
].IP
:= 0;
2187 NetBannedHosts
[I
].Perm
:= True;
2189 // no break here to clear all bans of this host, perm and non-perm
2193 procedure g_Net_SaveBanList();
2198 Assign(F
, DataDir
+ BANLIST_FILENAME
);
2200 if NetBannedHosts
<> nil then
2201 for I
:= 0 to High(NetBannedHosts
) do
2202 if NetBannedHosts
[I
].Perm
and (NetBannedHosts
[I
].IP
> 0) then
2203 Writeln(F
, IpToStr(NetBannedHosts
[I
].IP
));
2207 procedure g_Net_DumpStart();
2209 if NetMode
= NET_SERVER
then
2210 NetDumpFile
:= createDiskFile(NETDUMP_FILENAME
+ '_server')
2212 NetDumpFile
:= createDiskFile(NETDUMP_FILENAME
+ '_client');
2215 procedure g_Net_DumpSendBuffer();
2217 writeInt(NetDumpFile
, gTime
);
2218 writeInt(NetDumpFile
, LongWord(NetOut
.CurSize
));
2219 writeInt(NetDumpFile
, Byte(1));
2220 NetDumpFile
.WriteBuffer(NetOut
.Data
^, NetOut
.CurSize
);
2223 procedure g_Net_DumpRecvBuffer(Buf
: penet_uint8
; Len
: LongWord);
2225 if (Buf
= nil) or (Len
= 0) then Exit
;
2226 writeInt(NetDumpFile
, gTime
);
2227 writeInt(NetDumpFile
, Len
);
2228 writeInt(NetDumpFile
, Byte(0));
2229 NetDumpFile
.WriteBuffer(Buf
^, Len
);
2232 procedure g_Net_DumpEnd();
2238 function g_Net_ForwardPorts(ForwardPongPort
: Boolean = True): Boolean;
2239 {$IFDEF USE_MINIUPNPC}
2244 LanAddr
: array [0..255] of Char;
2245 StrPort
: AnsiString;
2250 if NetPortForwarded
= NetPort
then
2256 NetPongForwarded
:= False;
2257 NetPortForwarded
:= 0;
2259 DevList
:= upnpDiscover(1000, nil, nil, 0, 0, 2, Addr(Err
));
2260 if DevList
= nil then
2262 conwritefln('port forwarding failed: upnpDiscover() failed: %d', [Err
]);
2266 I
:= UPNP_GetValidIGD(DevList
, @Urls
, @Data
, Addr(LanAddr
[0]), 256);
2270 conwriteln('port forwarding failed: could not find an IGD device on this LAN');
2271 FreeUPNPDevList(DevList
);
2272 FreeUPNPUrls(@Urls
);
2276 StrPort
:= IntToStr(NetPort
);
2277 I
:= UPNP_AddPortMapping(
2278 Urls
.controlURL
, Addr(data
.first
.servicetype
[1]),
2279 PChar(StrPort
), PChar(StrPort
), Addr(LanAddr
[0]), PChar('D2DF'),
2280 PChar('UDP'), nil, PChar('0')
2285 conwritefln('forwarding port %d failed: error %d', [NetPort
, I
]);
2286 FreeUPNPDevList(DevList
);
2287 FreeUPNPUrls(@Urls
);
2291 if ForwardPongPort
then
2293 StrPort
:= IntToStr(NET_PING_PORT
);
2294 I
:= UPNP_AddPortMapping(
2295 Urls
.controlURL
, Addr(data
.first
.servicetype
[1]),
2296 PChar(StrPort
), PChar(StrPort
), Addr(LanAddr
[0]), PChar('D2DF'),
2297 PChar('UDP'), nil, PChar('0')
2302 conwritefln('forwarding port %d failed: error %d', [NetPort
+ 1, I
]);
2303 NetPongForwarded
:= False;
2307 conwritefln('forwarded port %d successfully', [NetPort
+ 1]);
2308 NetPongForwarded
:= True;
2312 conwritefln('forwarded port %d successfully', [NetPort
]);
2313 NetIGDControl
:= AnsiString(Urls
.controlURL
);
2314 NetIGDService
:= data
.first
.servicetype
;
2315 NetPortForwarded
:= NetPort
;
2317 FreeUPNPDevList(DevList
);
2318 FreeUPNPUrls(@Urls
);
2327 procedure g_Net_UnforwardPorts();
2328 {$IFDEF USE_MINIUPNPC}
2331 StrPort
: AnsiString;
2333 if NetPortForwarded
= 0 then Exit
;
2335 conwriteln('unforwarding ports...');
2337 StrPort
:= IntToStr(NetPortForwarded
);
2338 I
:= UPNP_DeletePortMapping(
2339 PChar(NetIGDControl
), Addr(NetIGDService
[1]),
2340 PChar(StrPort
), PChar('UDP'), nil
2342 conwritefln(' port %d: %d', [NetPortForwarded
, I
]);
2344 if NetPongForwarded
then
2346 NetPongForwarded
:= False;
2347 StrPort
:= IntToStr(NetPortForwarded
+ 1);
2348 I
:= UPNP_DeletePortMapping(
2349 PChar(NetIGDControl
), Addr(NetIGDService
[1]),
2350 PChar(StrPort
), PChar('UDP'), nil
2352 conwritefln(' port %d: %d', [NetPortForwarded
+ 1, I
]);
2355 NetPortForwarded
:= 0;
2363 conRegVar('cl_downloadtimeout', @g_Net_DownloadTimeout
, 0.0, 1000000.0, '', 'timeout in seconds, 0 to disable it');
2364 SetLength(NetClients
, 0);
2365 g_Net_DownloadTimeout
:= 60;
2366 NetIn
.Alloc(NET_BUFSIZE
);
2367 NetOut
.Alloc(NET_BUFSIZE
);
2368 NetBuf
[NET_UNRELIABLE
].Alloc(NET_BUFSIZE
*2);
2369 NetBuf
[NET_RELIABLE
].Alloc(NET_BUFSIZE
*2);
2373 NetBuf
[NET_UNRELIABLE
].Free();
2374 NetBuf
[NET_RELIABLE
].Free();