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
, 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;
46 NET_PING_PORT
= $DF2D;
53 NET_DISC_NONE
: enet_uint32
= 0;
54 NET_DISC_PROTOCOL
: enet_uint32
= 1;
55 NET_DISC_VERSION
: enet_uint32
= 2;
56 NET_DISC_FULL
: enet_uint32
= 3;
57 NET_DISC_KICK
: enet_uint32
= 4;
58 NET_DISC_DOWN
: enet_uint32
= 5;
59 NET_DISC_PASSWORD
: enet_uint32
= 6;
60 NET_DISC_TEMPBAN
: enet_uint32
= 7;
61 NET_DISC_BAN
: enet_uint32
= 8;
62 NET_DISC_MAX
: enet_uint32
= 8;
68 NET_CONNECT_TIMEOUT
= 1000 * 10;
70 BANLIST_FILENAME
= 'banlist.txt';
71 NETDUMP_FILENAME
= 'netdump';
86 RequestedFullUpdate
: Boolean;
89 NetOut
: array [0..1] of TMsg
;
95 pTNetClient
= ^TNetClient
;
97 AByte
= array of Byte;
100 NetInitDone
: Boolean = False;
101 NetMode
: Byte = NET_NONE
;
102 NetDump
: Boolean = False;
104 NetServerName
: string = 'Unnamed Server';
105 NetPassword
: string = '';
106 NetPort
: Word = 25666;
108 NetAllowRCON
: Boolean = False;
109 NetRCONPassword
: string = '';
111 NetTimeToUpdate
: Cardinal = 0;
112 NetTimeToReliable
: Cardinal = 0;
113 NetTimeToMaster
: Cardinal = 0;
115 NetHost
: pENetHost
= nil;
116 NetPeer
: pENetPeer
= nil;
118 NetAddr
: ENetAddress
;
120 NetPongAddr
: ENetAddress
;
121 NetPongSock
: ENetSocket
= ENET_SOCKET_NULL
;
123 NetUseMaster
: Boolean = True;
124 NetSlistAddr
: ENetAddress
;
125 NetSlistIP
: string = 'mpms.doom2d.org';
126 NetSlistPort
: Word = 25665;
128 NetClientIP
: string = '127.0.0.1';
129 NetClientPort
: Word = 25666;
132 NetBuf
: array [0..1] of TMsg
;
134 NetClients
: array of TNetClient
;
135 NetClientCount
: Byte = 0;
136 NetMaxClients
: Byte = 255;
137 NetBannedHosts
: array of TBanRecord
;
139 NetState
: Integer = NET_STATE_NONE
;
141 NetMyID
: Integer = -1;
142 NetPlrUID1
: Integer = -1;
143 NetPlrUID2
: Integer = -1;
145 NetInterpLevel
: Integer = 1;
146 NetUpdateRate
: Cardinal = 0; // as soon as possible
147 NetRelupdRate
: Cardinal = 18; // around two times a second
148 NetMasterRate
: Cardinal = 60000;
150 NetForcePlayerUpdate
: Boolean = False;
151 NetPredictSelf
: Boolean = True;
152 NetForwardPorts
: Boolean = False;
154 NetGotEverything
: Boolean = False;
155 NetGotKeys
: Boolean = False;
157 {$IFDEF USE_MINIUPNPC}
158 NetPortForwarded
: Word = 0;
159 NetPongForwarded
: Boolean = False;
160 NetIGDControl
: AnsiString;
161 NetIGDService
: TURLStr
;
164 NetPortThread
: TThreadID
= NilThreadId
;
166 NetDumpFile
: TStream
;
168 function g_Net_Init(): Boolean;
169 procedure g_Net_Cleanup();
170 procedure g_Net_Free();
171 procedure g_Net_Flush();
173 function g_Net_Host(IPAddr
: LongWord; Port
: enet_uint16
; MaxClients
: Cardinal = 16): Boolean;
174 procedure g_Net_Host_Die();
175 procedure g_Net_Host_Send(ID
: Integer; Reliable
: Boolean; Chan
: Byte = NET_CHAN_GAME
);
176 function g_Net_Host_Update(): enet_size_t
;
178 function g_Net_Connect(IP
: string; Port
: enet_uint16
): Boolean;
179 procedure g_Net_Disconnect(Forced
: Boolean = False);
180 procedure g_Net_Client_Send(Reliable
: Boolean; Chan
: Byte = NET_CHAN_GAME
);
181 function g_Net_Client_Update(): enet_size_t
;
182 function g_Net_Client_UpdateWhileLoading(): enet_size_t
;
184 function g_Net_Client_ByName(Name
: string): pTNetClient
;
185 function g_Net_Client_ByPlayer(PID
: Word): pTNetClient
;
186 function g_Net_ClientName_ByID(ID
: Integer): string;
188 procedure g_Net_SendData(Data
: AByte
; peer
: pENetPeer
; Reliable
: Boolean; Chan
: Byte = NET_CHAN_DOWNLOAD
);
189 function g_Net_Wait_Event(msgId
: Word): TMemoryStream
;
191 function IpToStr(IP
: LongWord): string;
192 function StrToIp(IPstr
: string; var IP
: LongWord): Boolean;
194 function g_Net_IsHostBanned(IP
: LongWord; Perm
: Boolean = False): Boolean;
195 procedure g_Net_BanHost(IP
: LongWord; Perm
: Boolean = True); overload
;
196 procedure g_Net_BanHost(IP
: string; Perm
: Boolean = True); overload
;
197 function g_Net_UnbanHost(IP
: string): Boolean; overload
;
198 function g_Net_UnbanHost(IP
: LongWord): Boolean; overload
;
199 procedure g_Net_UnbanNonPermHosts();
200 procedure g_Net_SaveBanList();
202 procedure g_Net_DumpStart();
203 procedure g_Net_DumpSendBuffer();
204 procedure g_Net_DumpRecvBuffer(Buf
: penet_uint8
; Len
: LongWord);
205 procedure g_Net_DumpEnd();
207 function g_Net_ForwardPorts(ForwardPongPort
: Boolean = True): Boolean;
208 procedure g_Net_UnforwardPorts();
214 e_input
, g_nethandler
, g_netmsg
, g_netmaster
, g_player
, g_window
, g_console
,
215 g_main
, g_game
, g_language
, g_weapons
, utils
, ctypes
;
218 g_Net_DownloadTimeout
: Single;
221 { /// SERVICE FUNCTIONS /// }
224 function g_Net_FindSlot(): Integer;
233 for I
:= Low(NetClients
) to High(NetClients
) do
235 if NetClients
[I
].Used
then
244 if C
>= NetMaxClients
then
252 if (Length(NetClients
) >= NetMaxClients
) then
256 SetLength(NetClients
, Length(NetClients
) + 1);
257 N
:= High(NetClients
);
263 NetClients
[N
].Used
:= True;
264 NetClients
[N
].ID
:= N
;
265 NetClients
[N
].RequestedFullUpdate
:= False;
266 NetClients
[N
].RCONAuth
:= False;
267 NetClients
[N
].Voted
:= False;
268 NetClients
[N
].Player
:= 0;
274 function g_Net_Init(): Boolean;
282 NetBuf
[NET_UNRELIABLE
].Clear();
283 NetBuf
[NET_RELIABLE
].Clear();
284 SetLength(NetClients
, 0);
290 NetAddr
.port
:= 25666;
291 SetLength(NetBannedHosts
, 0);
292 if FileExists(DataDir
+ BANLIST_FILENAME
) then
294 Assign(F
, DataDir
+ BANLIST_FILENAME
);
299 if StrToIp(IPstr
, IP
) then
306 Result
:= (enet_initialize() = 0);
309 procedure g_Net_Flush();
313 F
, Chan
: enet_uint32
;
317 Chan
:= NET_CHAN_GAME
;
319 if NetMode
= NET_SERVER
then
320 for T
:= NET_UNRELIABLE
to NET_RELIABLE
do
322 if NetBuf
[T
].CurSize
> 0 then
324 P
:= enet_packet_create(NetBuf
[T
].Data
, NetBuf
[T
].CurSize
, F
);
325 if not Assigned(P
) then continue
;
326 enet_host_broadcast(NetHost
, Chan
, P
);
330 for I
:= Low(NetClients
) to High(NetClients
) do
332 if not NetClients
[I
].Used
then continue
;
333 if NetClients
[I
].NetOut
[T
].CurSize
<= 0 then continue
;
334 P
:= enet_packet_create(NetClients
[I
].NetOut
[T
].Data
, NetClients
[I
].NetOut
[T
].CurSize
, F
);
335 if not Assigned(P
) then continue
;
336 enet_peer_send(NetClients
[I
].Peer
, Chan
, P
);
337 NetClients
[I
].NetOut
[T
].Clear();
340 // next and last iteration is always RELIABLE
341 F
:= LongWord(ENET_PACKET_FLAG_RELIABLE
);
342 Chan
:= NET_CHAN_IMPORTANT
;
344 else if NetMode
= NET_CLIENT
then
345 for T
:= NET_UNRELIABLE
to NET_RELIABLE
do
347 if NetBuf
[T
].CurSize
> 0 then
349 P
:= enet_packet_create(NetBuf
[T
].Data
, NetBuf
[T
].CurSize
, F
);
350 if not Assigned(P
) then continue
;
351 enet_peer_send(NetPeer
, Chan
, P
);
354 // next and last iteration is always RELIABLE
355 F
:= LongWord(ENET_PACKET_FLAG_RELIABLE
);
356 Chan
:= NET_CHAN_IMPORTANT
;
360 procedure g_Net_Cleanup();
364 NetBuf
[NET_UNRELIABLE
].Clear();
365 NetBuf
[NET_RELIABLE
].Clear();
367 SetLength(NetClients
, 0);
377 NetState
:= NET_STATE_NONE
;
379 NetPongSock
:= ENET_SOCKET_NULL
;
381 NetTimeToMaster
:= 0;
382 NetTimeToUpdate
:= 0;
383 NetTimeToReliable
:= 0;
387 if NetPortThread
<> NilThreadId
then
388 WaitForThreadTerminate(NetPortThread
, 66666);
390 NetPortThread
:= NilThreadId
;
391 g_Net_UnforwardPorts();
397 procedure g_Net_Free();
402 NetInitDone
:= False;
406 { /// SERVER FUNCTIONS /// }
409 function ForwardThread(Param
: Pointer): PtrInt
;
412 if not g_Net_ForwardPorts() then Result
:= -1;
415 function g_Net_Host(IPAddr
: LongWord; Port
: enet_uint16
; MaxClients
: Cardinal = 16): Boolean;
417 if NetMode
<> NET_NONE
then
419 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_INGAME
]);
426 g_Console_Add(_lc
[I_NET_MSG
] + Format(_lc
[I_NET_MSG_HOST
], [Port
]));
427 if not NetInitDone
then
429 if (not g_Net_Init()) then
431 g_Console_Add(_lc
[I_NET_MSG_FERROR
] + _lc
[I_NET_ERR_ENET
]);
439 NetAddr
.host
:= IPAddr
;
440 NetAddr
.port
:= Port
;
442 if NetForwardPorts
then NetPortThread
:= BeginThread(ForwardThread
);
444 NetHost
:= enet_host_create(@NetAddr
, NET_MAXCLIENTS
, NET_CHANS
, 0, 0);
446 if (NetHost
= nil) then
448 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + Format(_lc
[I_NET_ERR_HOST
], [Port
]));
454 NetPongSock
:= enet_socket_create(ENET_SOCKET_TYPE_DATAGRAM
);
455 if NetPongSock
<> ENET_SOCKET_NULL
then
457 NetPongAddr
.host
:= IPAddr
;
458 NetPongAddr
.port
:= NET_PING_PORT
;
459 if enet_socket_bind(NetPongSock
, @NetPongAddr
) < 0 then
461 enet_socket_destroy(NetPongSock
);
462 NetPongSock
:= ENET_SOCKET_NULL
;
465 enet_socket_set_option(NetPongSock
, ENET_SOCKOPT_NONBLOCK
, 1);
468 NetMode
:= NET_SERVER
;
470 NetBuf
[NET_UNRELIABLE
].Clear();
471 NetBuf
[NET_RELIABLE
].Clear();
477 procedure g_Net_Host_Die();
481 if NetMode
<> NET_SERVER
then Exit
;
483 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_HOST_DISCALL
]);
484 for I
:= 0 to High(NetClients
) do
485 if NetClients
[I
].Used
then
486 enet_peer_disconnect(NetClients
[I
].Peer
, NET_DISC_DOWN
);
488 while enet_host_service(NetHost
, @NetEvent
, 1000) > 0 do
489 if NetEvent
.kind
= ENET_EVENT_TYPE_RECEIVE
then
490 enet_packet_destroy(NetEvent
.packet
);
492 for I
:= 0 to High(NetClients
) do
493 if NetClients
[I
].Used
then
495 FreeMemory(NetClients
[I
].Peer
^.data
);
496 NetClients
[I
].Peer
^.data
:= nil;
497 enet_peer_reset(NetClients
[I
].Peer
);
498 NetClients
[I
].Peer
:= nil;
499 NetClients
[I
].Used
:= False;
500 NetClients
[I
].NetOut
[NET_UNRELIABLE
].Free();
501 NetClients
[I
].NetOut
[NET_RELIABLE
].Free();
504 if (NetMPeer
<> nil) and (NetMHost
<> nil) then g_Net_Slist_Disconnect
;
505 if NetPongSock
<> ENET_SOCKET_NULL
then
506 enet_socket_destroy(NetPongSock
);
508 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_HOST_DIE
]);
509 enet_host_destroy(NetHost
);
514 e_WriteLog('NET: Server stopped', TMsgType
.Notify
);
518 procedure g_Net_Host_Send(ID
: Integer; Reliable
: Boolean; Chan
: Byte = NET_CHAN_GAME
);
529 if ID
> High(NetClients
) then Exit
;
530 if NetClients
[ID
].Peer
= nil then Exit
;
532 NetClients
[ID
].NetOut
[T
].Write(Integer(NetOut
.CurSize
));
533 NetClients
[ID
].NetOut
[T
].Write(NetOut
);
538 NetBuf
[T
].Write(Integer(NetOut
.CurSize
));
539 NetBuf
[T
].Write(NetOut
);
542 if NetDump
then g_Net_DumpSendBuffer();
546 procedure g_Net_Host_CheckPings();
552 Ping
: array [0..9] of Byte;
555 if NetPongSock
= ENET_SOCKET_NULL
then Exit
;
557 Buf
.data
:= Addr(Ping
[0]);
558 Buf
.dataLength
:= 2+8;
562 Len
:= enet_socket_receive(NetPongSock
, @ClAddr
, @Buf
, 1);
563 if Len
< 0 then Exit
;
565 if (Ping
[0] = Ord('D')) and (Ping
[1] = Ord('F')) then
567 ClTime
:= Int64(Addr(Ping
[2])^);
570 NetOut
.Write(Byte(Ord('D')));
571 NetOut
.Write(Byte(Ord('F')));
572 NetOut
.Write(NetPort
);
573 NetOut
.Write(ClTime
);
574 g_Net_Slist_WriteInfo();
576 if gPlayer1
<> nil then Inc(NPl
);
577 if gPlayer2
<> nil then Inc(NPl
);
579 NetOut
.Write(gNumBots
);
581 Buf
.data
:= NetOut
.Data
;
582 Buf
.dataLength
:= NetOut
.CurSize
;
583 enet_socket_send(NetPongSock
, @ClAddr
, @Buf
, 1);
589 function g_Net_Host_Update(): enet_size_t
;
602 g_Net_Host_CheckPings
;
604 while (enet_host_service(NetHost
, @NetEvent
, 0) > 0) do
606 case (NetEvent
.kind
) of
607 ENET_EVENT_TYPE_CONNECT
:
609 IP
:= IpToStr(NetEvent
.Peer
^.address
.host
);
610 Port
:= NetEvent
.Peer
^.address
.port
;
611 g_Console_Add(_lc
[I_NET_MSG
] +
612 Format(_lc
[I_NET_MSG_HOST_CONN
], [IP
, Port
]));
614 if (NetEvent
.data
<> NET_PROTOCOL_VER
) then
616 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_HOST_REJECT
] +
617 _lc
[I_NET_DISC_PROTOCOL
]);
618 NetEvent
.peer
^.data
:= GetMemory(SizeOf(Byte));
619 Byte(NetEvent
.peer
^.data
^) := 255;
620 enet_peer_disconnect(NetEvent
.peer
, NET_DISC_PROTOCOL
);
621 enet_host_flush(NetHost
);
625 ID
:= g_Net_FindSlot();
629 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_HOST_REJECT
] +
630 _lc
[I_NET_DISC_FULL
]);
631 NetEvent
.Peer
^.data
:= GetMemory(SizeOf(Byte));
632 Byte(NetEvent
.peer
^.data
^) := 255;
633 enet_peer_disconnect(NetEvent
.peer
, NET_DISC_FULL
);
634 enet_host_flush(NetHost
);
638 NetClients
[ID
].Peer
:= NetEvent
.peer
;
639 NetClients
[ID
].Peer
^.data
:= GetMemory(SizeOf(Byte));
640 Byte(NetClients
[ID
].Peer
^.data
^) := ID
;
641 NetClients
[ID
].State
:= NET_STATE_AUTH
;
642 NetClients
[ID
].RCONAuth
:= False;
643 NetClients
[ID
].NetOut
[NET_UNRELIABLE
].Alloc(NET_BUFSIZE
*2);
644 NetClients
[ID
].NetOut
[NET_RELIABLE
].Alloc(NET_BUFSIZE
*2);
646 enet_peer_timeout(NetEvent
.peer
, ENET_PEER_TIMEOUT_LIMIT
* 2, ENET_PEER_TIMEOUT_MINIMUM
* 2, ENET_PEER_TIMEOUT_MAXIMUM
* 2);
649 g_Console_Add(_lc
[I_NET_MSG
] + Format(_lc
[I_NET_MSG_HOST_ADD
], [ID
]));
652 ENET_EVENT_TYPE_RECEIVE
:
654 ID
:= Byte(NetEvent
.peer
^.data
^);
655 if ID
> High(NetClients
) then Exit
;
656 TC
:= @NetClients
[ID
];
658 if NetDump
then g_Net_DumpRecvBuffer(NetEvent
.packet
^.data
, NetEvent
.packet
^.dataLength
);
659 g_Net_Host_HandlePacket(TC
, NetEvent
.packet
, g_Net_HostMsgHandler
);
662 ENET_EVENT_TYPE_DISCONNECT
:
664 ID
:= Byte(NetEvent
.peer
^.data
^);
665 if ID
> High(NetClients
) then Exit
;
666 TC
:= @NetClients
[ID
];
667 if TC
= nil then Exit
;
669 if not (TC
^.Used
) then Exit
;
671 TP
:= g_Player_Get(TC
^.Player
);
676 TP
.Kill(K_SIMPLEKILL
, 0, HIT_DISCON
);
677 g_Console_Add(Format(_lc
[I_PLAYER_LEAVE
], [TP
.Name
]), True);
678 e_WriteLog('NET: Client ' + TP
.Name
+ ' [' + IntToStr(ID
) + '] disconnected.', TMsgType
.Notify
);
679 g_Player_Remove(TP
.UID
);
683 TC
^.State
:= NET_STATE_NONE
;
686 TC
^.RequestedFullUpdate
:= False;
687 TC
^.NetOut
[NET_UNRELIABLE
].Free();
688 TC
^.NetOut
[NET_RELIABLE
].Free();
690 FreeMemory(NetEvent
.peer
^.data
);
691 NetEvent
.peer
^.data
:= nil;
692 g_Console_Add(_lc
[I_NET_MSG
] + Format(_lc
[I_NET_MSG_HOST_DISC
], [ID
]));
695 if NetUseMaster
then g_Net_Slist_Update
;
702 { /// CLIENT FUNCTIONS /// }
705 procedure g_Net_Disconnect(Forced
: Boolean = False);
707 if NetMode
<> NET_CLIENT
then Exit
;
708 if (NetHost
= nil) or (NetPeer
= nil) then Exit
;
712 enet_peer_disconnect(NetPeer
, NET_DISC_NONE
);
714 while (enet_host_service(NetHost
, @NetEvent
, 1500) > 0) do
716 if (NetEvent
.kind
= ENET_EVENT_TYPE_DISCONNECT
) then
722 if (NetEvent
.kind
= ENET_EVENT_TYPE_RECEIVE
) then
723 enet_packet_destroy(NetEvent
.packet
);
726 if NetPeer
<> nil then
728 enet_peer_reset(NetPeer
);
734 e_WriteLog('NET: Kicked from server: ' + IntToStr(NetEvent
.data
), TMsgType
.Notify
);
735 if (NetEvent
.data
<= NET_DISC_MAX
) then
736 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_KICK
] +
737 _lc
[TStrings_Locale(Cardinal(I_NET_DISC_NONE
) + NetEvent
.data
)], True);
740 if NetHost
<> nil then
742 enet_host_destroy(NetHost
);
745 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_CLIENT_DISC
]);
748 e_WriteLog('NET: Disconnected', TMsgType
.Notify
);
751 procedure g_Net_Client_Send(Reliable
: Boolean; Chan
: Byte = NET_CHAN_GAME
);
761 NetBuf
[T
].Write(Integer(NetOut
.CurSize
));
762 NetBuf
[T
].Write(NetOut
);
764 if NetDump
then g_Net_DumpSendBuffer();
766 g_Net_Flush(); // FIXME: for now, send immediately
769 function g_Net_Client_Update(): enet_size_t
;
772 while (enet_host_service(NetHost
, @NetEvent
, 0) > 0) do
774 case NetEvent
.kind
of
775 ENET_EVENT_TYPE_RECEIVE
:
777 if NetDump
then g_Net_DumpRecvBuffer(NetEvent
.packet
^.data
, NetEvent
.packet
^.dataLength
);
778 g_Net_Client_HandlePacket(NetEvent
.packet
, g_Net_ClientMsgHandler
);
781 ENET_EVENT_TYPE_DISCONNECT
:
783 g_Net_Disconnect(True);
791 function g_Net_Client_UpdateWhileLoading(): enet_size_t
;
794 while (enet_host_service(NetHost
, @NetEvent
, 0) > 0) do
796 case NetEvent
.kind
of
797 ENET_EVENT_TYPE_RECEIVE
:
799 if NetDump
then g_Net_DumpRecvBuffer(NetEvent
.packet
^.data
, NetEvent
.packet
^.dataLength
);
800 g_Net_Client_HandlePacket(NetEvent
.packet
, g_Net_ClientLightMsgHandler
);
803 ENET_EVENT_TYPE_DISCONNECT
:
805 g_Net_Disconnect(True);
814 function g_Net_Connect(IP
: string; Port
: enet_uint16
): Boolean;
817 TimeoutTime
, T
: Int64;
819 if NetMode
<> NET_NONE
then
821 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_ERR_INGAME
], True);
828 g_Console_Add(_lc
[I_NET_MSG
] + Format(_lc
[I_NET_MSG_CLIENT_CONN
],
830 if not NetInitDone
then
832 if (not g_Net_Init()) then
834 g_Console_Add(_lc
[I_NET_MSG_FERROR
] + _lc
[I_NET_ERR_ENET
], True);
842 NetHost
:= enet_host_create(nil, 1, NET_CHANS
, 0, 0);
844 if (NetHost
= nil) then
846 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CLIENT
], True);
852 enet_address_set_host(@NetAddr
, PChar(Addr(IP
[1])));
853 NetAddr
.port
:= Port
;
855 NetPeer
:= enet_host_connect(NetHost
, @NetAddr
, NET_CHANS
, NET_PROTOCOL_VER
);
857 if (NetPeer
= nil) then
859 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CLIENT
], True);
860 enet_host_destroy(NetHost
);
866 // предупредить что ждем слишком долго через N секунд
867 TimeoutTime
:= GetTimer() + NET_CONNECT_TIMEOUT
;
872 while (enet_host_service(NetHost
, @NetEvent
, 0) > 0) do
874 if (NetEvent
.kind
= ENET_EVENT_TYPE_CONNECT
) then
876 g_Console_Add(_lc
[I_NET_MSG
] + _lc
[I_NET_MSG_CLIENT_DONE
]);
877 NetMode
:= NET_CLIENT
;
879 enet_peer_timeout(NetPeer
, ENET_PEER_TIMEOUT_LIMIT
* 2, ENET_PEER_TIMEOUT_MINIMUM
* 2, ENET_PEER_TIMEOUT_MAXIMUM
* 2);
881 NetClientPort
:= Port
;
889 if T
> TimeoutTime
then
891 TimeoutTime
:= T
+ NET_CONNECT_TIMEOUT
* 100; // одного предупреждения хватит
892 g_Console_Add(_lc
[I_NET_MSG_TIMEOUT_WARN
], True);
893 g_Console_Add(Format(_lc
[I_NET_MSG_PORTS
], [Integer(Port
), Integer(NET_PING_PORT
)]), True);
896 ProcessLoading(true);
898 if e_KeyPressed(IK_SPACE
) or e_KeyPressed(IK_ESCAPE
) or e_KeyPressed(VK_ESCAPE
) or
899 e_KeyPressed(JOY0_JUMP
) or e_KeyPressed(JOY1_JUMP
) or e_KeyPressed(JOY2_JUMP
) or e_KeyPressed(JOY3_JUMP
) then
903 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_TIMEOUT
], True);
904 g_Console_Add(Format(_lc
[I_NET_MSG_PORTS
], [Integer(Port
), Integer(NET_PING_PORT
)]), True);
905 if NetPeer
<> nil then enet_peer_reset(NetPeer
);
906 if NetHost
<> nil then
908 enet_host_destroy(NetHost
);
915 function IpToStr(IP
: LongWord): string;
920 Result
:= IntToStr(PByte(Ptr
+ 0)^) + '.';
921 Result
:= Result
+ IntToStr(PByte(Ptr
+ 1)^) + '.';
922 Result
:= Result
+ IntToStr(PByte(Ptr
+ 2)^) + '.';
923 Result
:= Result
+ IntToStr(PByte(Ptr
+ 3)^);
926 function StrToIp(IPstr
: string; var IP
: LongWord): Boolean;
930 Result
:= enet_address_set_host(@EAddr
, PChar(@IPstr
[1])) = 0;
934 function g_Net_Client_ByName(Name
: string): pTNetClient
;
940 for a
:= Low(NetClients
) to High(NetClients
) do
941 if (NetClients
[a
].Used
) and (NetClients
[a
].State
= NET_STATE_GAME
) then
943 pl
:= g_Player_Get(NetClients
[a
].Player
);
944 if pl
= nil then continue
;
945 if Copy(LowerCase(pl
.Name
), 1, Length(Name
)) <> LowerCase(Name
) then continue
;
946 if NetClients
[a
].Peer
<> nil then
948 Result
:= @NetClients
[a
];
954 function g_Net_Client_ByPlayer(PID
: Word): pTNetClient
;
959 for a
:= Low(NetClients
) to High(NetClients
) do
960 if (NetClients
[a
].Used
) and (NetClients
[a
].State
= NET_STATE_GAME
) then
961 if NetClients
[a
].Player
= PID
then
963 Result
:= @NetClients
[a
];
968 function g_Net_ClientName_ByID(ID
: Integer): string;
974 if ID
= NET_EVERYONE
then
976 for a
:= Low(NetClients
) to High(NetClients
) do
977 if (NetClients
[a
].ID
= ID
) and (NetClients
[a
].Used
) and (NetClients
[a
].State
= NET_STATE_GAME
) then
979 pl
:= g_Player_Get(NetClients
[a
].Player
);
980 if pl
= nil then Exit
;
985 procedure g_Net_SendData(Data
: AByte
; peer
: pENetPeer
; Reliable
: Boolean; Chan
: Byte = NET_CHAN_DOWNLOAD
);
989 dataLength
: Cardinal;
991 dataLength
:= Length(Data
);
994 F
:= LongWord(ENET_PACKET_FLAG_RELIABLE
)
998 if (peer
<> nil) then
1000 P
:= enet_packet_create(@Data
[0], dataLength
, F
);
1001 if not Assigned(P
) then Exit
;
1002 enet_peer_send(peer
, Chan
, P
);
1006 P
:= enet_packet_create(@Data
[0], dataLength
, F
);
1007 if not Assigned(P
) then Exit
;
1008 enet_host_broadcast(NetHost
, Chan
, P
);
1011 enet_host_flush(NetHost
);
1014 function UserRequestExit
: Boolean;
1016 Result
:= e_KeyPressed(IK_SPACE
) or
1017 e_KeyPressed(IK_ESCAPE
) or
1018 e_KeyPressed(VK_ESCAPE
) or
1019 e_KeyPressed(JOY0_JUMP
) or
1020 e_KeyPressed(JOY1_JUMP
) or
1021 e_KeyPressed(JOY2_JUMP
) or
1022 e_KeyPressed(JOY3_JUMP
)
1025 function g_Net_Wait_Event(msgId
: Word): TMemoryStream
;
1030 stream
: TMemoryStream
;
1033 FillChar(ev
, SizeOf(ev
), 0);
1036 status
:= enet_host_service(NetHost
, @ev
, Trunc(g_Net_DownloadTimeout
* 1000));
1040 ENET_EVENT_TYPE_RECEIVE
:
1042 Ptr
:= ev
.packet
^.data
;
1043 rMsgId
:= Byte(Ptr
^);
1044 if rMsgId
= msgId
then
1046 stream
:= TMemoryStream
.Create
;
1047 stream
.SetSize(ev
.packet
^.dataLength
);
1048 stream
.WriteBuffer(Ptr
^, ev
.packet
^.dataLength
);
1049 stream
.Seek(0, soFromBeginning
);
1050 status
:= 1 (* received *)
1054 (* looks that game state always received, so ignore it *)
1055 e_LogWritefln('g_Net_Wait_Event(%s): skip message %s', [msgId
, rMsgId
]);
1056 status
:= 2 (* continue *)
1059 ENET_EVENT_TYPE_DISCONNECT
:
1061 if (ev
.data
<= NET_DISC_MAX
) then
1062 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' ' + _lc
[TStrings_Locale(Cardinal(I_NET_DISC_NONE
) + ev
.data
)], True);
1063 status
:= -2 (* error: disconnected *)
1066 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' unknown ENet event ' + IntToStr(Ord(ev
.kind
)), True);
1067 status
:= -3 (* error: unknown event *)
1069 enet_packet_destroy(ev
.packet
)
1073 g_Console_Add(_lc
[I_NET_MSG_ERROR
] + _lc
[I_NET_ERR_CONN
] + ' timeout reached', True);
1074 status
:= 0 (* error: timeout *)
1076 ProcessLoading(true);
1077 until (status
<> 2) or UserRequestExit();
1081 function g_Net_IsHostBanned(IP
: LongWord; Perm
: Boolean = False): Boolean;
1086 if NetBannedHosts
= nil then
1088 for I
:= 0 to High(NetBannedHosts
) do
1089 if (NetBannedHosts
[I
].IP
= IP
) and ((not Perm
) or (NetBannedHosts
[I
].Perm
)) then
1096 procedure g_Net_BanHost(IP
: LongWord; Perm
: Boolean = True); overload
;
1102 if g_Net_IsHostBanned(IP
, Perm
) then
1106 for I
:= Low(NetBannedHosts
) to High(NetBannedHosts
) do
1107 if NetBannedHosts
[I
].IP
= 0 then
1115 SetLength(NetBannedHosts
, Length(NetBannedHosts
) + 1);
1116 P
:= High(NetBannedHosts
);
1119 NetBannedHosts
[P
].IP
:= IP
;
1120 NetBannedHosts
[P
].Perm
:= Perm
;
1123 procedure g_Net_BanHost(IP
: string; Perm
: Boolean = True); overload
;
1128 b
:= StrToIp(IP
, a
);
1130 g_Net_BanHost(a
, Perm
);
1133 procedure g_Net_UnbanNonPermHosts();
1137 if NetBannedHosts
= nil then
1139 for I
:= Low(NetBannedHosts
) to High(NetBannedHosts
) do
1140 if (NetBannedHosts
[I
].IP
> 0) and not NetBannedHosts
[I
].Perm
then
1142 NetBannedHosts
[I
].IP
:= 0;
1143 NetBannedHosts
[I
].Perm
:= True;
1147 function g_Net_UnbanHost(IP
: string): Boolean; overload
;
1151 Result
:= StrToIp(IP
, a
);
1153 Result
:= g_Net_UnbanHost(a
);
1156 function g_Net_UnbanHost(IP
: LongWord): Boolean; overload
;
1163 if NetBannedHosts
= nil then
1165 for I
:= 0 to High(NetBannedHosts
) do
1166 if NetBannedHosts
[I
].IP
= IP
then
1168 NetBannedHosts
[I
].IP
:= 0;
1169 NetBannedHosts
[I
].Perm
:= True;
1171 // no break here to clear all bans of this host, perm and non-perm
1175 procedure g_Net_SaveBanList();
1180 Assign(F
, DataDir
+ BANLIST_FILENAME
);
1182 if NetBannedHosts
<> nil then
1183 for I
:= 0 to High(NetBannedHosts
) do
1184 if NetBannedHosts
[I
].Perm
and (NetBannedHosts
[I
].IP
> 0) then
1185 Writeln(F
, IpToStr(NetBannedHosts
[I
].IP
));
1189 procedure g_Net_DumpStart();
1191 if NetMode
= NET_SERVER
then
1192 NetDumpFile
:= createDiskFile(NETDUMP_FILENAME
+ '_server')
1194 NetDumpFile
:= createDiskFile(NETDUMP_FILENAME
+ '_client');
1197 procedure g_Net_DumpSendBuffer();
1199 writeInt(NetDumpFile
, gTime
);
1200 writeInt(NetDumpFile
, LongWord(NetOut
.CurSize
));
1201 writeInt(NetDumpFile
, Byte(1));
1202 NetDumpFile
.WriteBuffer(NetOut
.Data
^, NetOut
.CurSize
);
1205 procedure g_Net_DumpRecvBuffer(Buf
: penet_uint8
; Len
: LongWord);
1207 if (Buf
= nil) or (Len
= 0) then Exit
;
1208 writeInt(NetDumpFile
, gTime
);
1209 writeInt(NetDumpFile
, Len
);
1210 writeInt(NetDumpFile
, Byte(0));
1211 NetDumpFile
.WriteBuffer(Buf
^, Len
);
1214 procedure g_Net_DumpEnd();
1220 function g_Net_ForwardPorts(ForwardPongPort
: Boolean = True): Boolean;
1221 {$IFDEF USE_MINIUPNPC}
1226 LanAddr
: array [0..255] of Char;
1227 StrPort
: AnsiString;
1232 if NetPortForwarded
= NetPort
then
1238 NetPongForwarded
:= False;
1239 NetPortForwarded
:= 0;
1241 DevList
:= upnpDiscover(1000, nil, nil, 0, 0, 2, Addr(Err
));
1242 if DevList
= nil then
1244 conwritefln('port forwarding failed: upnpDiscover() failed: %d', [Err
]);
1248 I
:= UPNP_GetValidIGD(DevList
, @Urls
, @Data
, Addr(LanAddr
[0]), 256);
1252 conwriteln('port forwarding failed: could not find an IGD device on this LAN');
1253 FreeUPNPDevList(DevList
);
1254 FreeUPNPUrls(@Urls
);
1258 StrPort
:= IntToStr(NetPort
);
1259 I
:= UPNP_AddPortMapping(
1260 Urls
.controlURL
, Addr(data
.first
.servicetype
[1]),
1261 PChar(StrPort
), PChar(StrPort
), Addr(LanAddr
[0]), PChar('D2DF'),
1262 PChar('UDP'), nil, PChar('0')
1267 conwritefln('forwarding port %d failed: error %d', [NetPort
, I
]);
1268 FreeUPNPDevList(DevList
);
1269 FreeUPNPUrls(@Urls
);
1273 if ForwardPongPort
then
1275 StrPort
:= IntToStr(NET_PING_PORT
);
1276 I
:= UPNP_AddPortMapping(
1277 Urls
.controlURL
, Addr(data
.first
.servicetype
[1]),
1278 PChar(StrPort
), PChar(StrPort
), Addr(LanAddr
[0]), PChar('D2DF'),
1279 PChar('UDP'), nil, PChar('0')
1284 conwritefln('forwarding port %d failed: error %d', [NetPort
+ 1, I
]);
1285 NetPongForwarded
:= False;
1289 conwritefln('forwarded port %d successfully', [NetPort
+ 1]);
1290 NetPongForwarded
:= True;
1294 conwritefln('forwarded port %d successfully', [NetPort
]);
1295 NetIGDControl
:= AnsiString(Urls
.controlURL
);
1296 NetIGDService
:= data
.first
.servicetype
;
1297 NetPortForwarded
:= NetPort
;
1299 FreeUPNPDevList(DevList
);
1300 FreeUPNPUrls(@Urls
);
1309 procedure g_Net_UnforwardPorts();
1310 {$IFDEF USE_MINIUPNPC}
1313 StrPort
: AnsiString;
1315 if NetPortForwarded
= 0 then Exit
;
1317 conwriteln('unforwarding ports...');
1319 StrPort
:= IntToStr(NetPortForwarded
);
1320 I
:= UPNP_DeletePortMapping(
1321 PChar(NetIGDControl
), Addr(NetIGDService
[1]),
1322 PChar(StrPort
), PChar('UDP'), nil
1324 conwritefln(' port %d: %d', [NetPortForwarded
, I
]);
1326 if NetPongForwarded
then
1328 NetPongForwarded
:= False;
1329 StrPort
:= IntToStr(NetPortForwarded
+ 1);
1330 I
:= UPNP_DeletePortMapping(
1331 PChar(NetIGDControl
), Addr(NetIGDService
[1]),
1332 PChar(StrPort
), PChar('UDP'), nil
1334 conwritefln(' port %d: %d', [NetPortForwarded
+ 1, I
]);
1337 NetPortForwarded
:= 0;
1345 conRegVar('cl_downloadtimeout', @g_Net_DownloadTimeout
, 0.0, 1000000.0, '', 'timeout in seconds, 0 to disable it');
1346 g_Net_DownloadTimeout
:= 60;
1347 NetIn
.Alloc(NET_BUFSIZE
);
1348 NetOut
.Alloc(NET_BUFSIZE
);
1349 NetBuf
[NET_UNRELIABLE
].Alloc(NET_BUFSIZE
*2);
1350 NetBuf
[NET_RELIABLE
].Alloc(NET_BUFSIZE
*2);
1354 NetBuf
[NET_UNRELIABLE
].Free();
1355 NetBuf
[NET_RELIABLE
].Free();