2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
9 * @file core/udp.cpp Basic functions to receive and send UDP packets.
12 #include "../../stdafx.h"
13 #include "../../date_func.h"
14 #include "../../debug.h"
17 #include "../../safeguards.h"
20 * Create an UDP socket but don't listen yet.
21 * @param bind the addresses to bind to.
23 NetworkUDPSocketHandler::NetworkUDPSocketHandler(NetworkAddressList
*bind
)
25 if (bind
!= nullptr) {
26 for (NetworkAddress
&addr
: *bind
) {
27 this->bind
.push_back(addr
);
30 /* As hostname nullptr and port 0/nullptr don't go well when
31 * resolving it we need to add an address for each of
32 * the address families we support. */
33 this->bind
.emplace_back(nullptr, 0, AF_INET
);
34 this->bind
.emplace_back(nullptr, 0, AF_INET6
);
40 * Start listening on the given host and port.
41 * @return true if at least one port is listening
43 bool NetworkUDPSocketHandler::Listen()
45 /* Make sure socket is closed */
48 for (NetworkAddress
&addr
: this->bind
) {
49 addr
.Listen(SOCK_DGRAM
, &this->sockets
);
52 return this->sockets
.size() != 0;
56 * Close the given UDP socket
58 void NetworkUDPSocketHandler::Close()
60 for (auto &s
: this->sockets
) {
61 closesocket(s
.second
);
63 this->sockets
.clear();
66 NetworkRecvStatus
NetworkUDPSocketHandler::CloseConnection(bool error
)
68 NetworkSocketHandler::CloseConnection(error
);
69 return NETWORK_RECV_STATUS_OKAY
;
73 * Send a packet over UDP
74 * @param p the packet to send
75 * @param recv the receiver (target) of the packet
76 * @param all send the packet using all sockets that can send it
77 * @param broadcast whether to send a broadcast message
79 void NetworkUDPSocketHandler::SendPacket(Packet
*p
, NetworkAddress
*recv
, bool all
, bool broadcast
)
81 if (this->sockets
.size() == 0) this->Listen();
83 for (auto &s
: this->sockets
) {
84 /* Make a local copy because if we resolve it we cannot
85 * easily unresolve it so we can resolve it later again. */
86 NetworkAddress
send(*recv
);
88 /* Not the same type */
89 if (!send
.IsFamily(s
.first
.GetAddress()->ss_family
)) continue;
94 /* Enable broadcast */
95 unsigned long val
= 1;
96 if (setsockopt(s
.second
, SOL_SOCKET
, SO_BROADCAST
, (char *) &val
, sizeof(val
)) < 0) {
97 DEBUG(net
, 1, "[udp] setting broadcast failed with: %i", GET_LAST_ERROR());
101 /* Send the buffer */
102 int res
= sendto(s
.second
, (const char*)p
->buffer
, p
->size
, 0, (const struct sockaddr
*)send
.GetAddress(), send
.GetAddressLength());
103 DEBUG(net
, 7, "[udp] sendto(%s)", send
.GetAddressAsString().c_str());
105 /* Check for any errors, but ignore it otherwise */
106 if (res
== -1) DEBUG(net
, 1, "[udp] sendto(%s) failed with: %i", send
.GetAddressAsString().c_str(), GET_LAST_ERROR());
113 * Receive a packet at UDP level
115 void NetworkUDPSocketHandler::ReceivePackets()
117 for (auto &s
: this->sockets
) {
118 for (int i
= 0; i
< 1000; i
++) { // Do not infinitely loop when DoSing with UDP
119 struct sockaddr_storage client_addr
;
120 memset(&client_addr
, 0, sizeof(client_addr
));
123 socklen_t client_len
= sizeof(client_addr
);
125 /* Try to receive anything */
126 SetNonBlocking(s
.second
); // Some OSes seem to lose the non-blocking status of the socket
127 int nbytes
= recvfrom(s
.second
, (char*)p
.buffer
, SEND_MTU
, 0, (struct sockaddr
*)&client_addr
, &client_len
);
129 /* Did we get the bytes for the base header of the packet? */
130 if (nbytes
<= 0) break; // No data, i.e. no packet
131 if (nbytes
<= 2) continue; // Invalid data; try next packet
132 #ifdef __EMSCRIPTEN__
133 client_len
= FixAddrLenForEmscripten(client_addr
);
136 NetworkAddress
address(client_addr
, client_len
);
139 /* If the size does not match the packet must be corrupted.
140 * Otherwise it will be marked as corrupted later on. */
141 if (nbytes
!= p
.size
) {
142 DEBUG(net
, 1, "received a packet with mismatching size from %s", address
.GetAddressAsString().c_str());
146 /* Handle the packet */
147 this->HandleUDPPacket(&p
, &address
);
154 * Serializes the NetworkGameInfo struct to the packet
155 * @param p the packet to write the data to
156 * @param info the NetworkGameInfo struct to serialize
158 void NetworkUDPSocketHandler::SendNetworkGameInfo(Packet
*p
, const NetworkGameInfo
*info
)
160 p
->Send_uint8 (NETWORK_GAME_INFO_VERSION
);
163 * Please observe the order.
164 * The parts must be read in the same order as they are sent!
167 /* Update the documentation in udp.h on changes
168 * to the NetworkGameInfo wire-protocol! */
170 /* NETWORK_GAME_INFO_VERSION = 4 */
172 /* Only send the GRF Identification (GRF_ID and MD5 checksum) of
173 * the GRFs that are needed, i.e. the ones that the server has
174 * selected in the NewGRF GUI and not the ones that are used due
175 * to the fact that they are in [newgrf-static] in openttd.cfg */
179 /* Count number of GRFs to send information about */
180 for (c
= info
->grfconfig
; c
!= nullptr; c
= c
->next
) {
181 if (!HasBit(c
->flags
, GCF_STATIC
)) count
++;
183 p
->Send_uint8 (count
); // Send number of GRFs
185 /* Send actual GRF Identifications */
186 for (c
= info
->grfconfig
; c
!= nullptr; c
= c
->next
) {
187 if (!HasBit(c
->flags
, GCF_STATIC
)) this->SendGRFIdentifier(p
, &c
->ident
);
191 /* NETWORK_GAME_INFO_VERSION = 3 */
192 p
->Send_uint32(info
->game_date
);
193 p
->Send_uint32(info
->start_date
);
195 /* NETWORK_GAME_INFO_VERSION = 2 */
196 p
->Send_uint8 (info
->companies_max
);
197 p
->Send_uint8 (info
->companies_on
);
198 p
->Send_uint8 (info
->spectators_max
);
200 /* NETWORK_GAME_INFO_VERSION = 1 */
201 p
->Send_string(info
->server_name
);
202 p
->Send_string(info
->server_revision
);
203 p
->Send_uint8 (info
->server_lang
);
204 p
->Send_bool (info
->use_password
);
205 p
->Send_uint8 (info
->clients_max
);
206 p
->Send_uint8 (info
->clients_on
);
207 p
->Send_uint8 (info
->spectators_on
);
208 p
->Send_string(info
->map_name
);
209 p
->Send_uint16(info
->map_width
);
210 p
->Send_uint16(info
->map_height
);
211 p
->Send_uint8 (info
->map_set
);
212 p
->Send_bool (info
->dedicated
);
216 * Deserializes the NetworkGameInfo struct from the packet
217 * @param p the packet to read the data from
218 * @param info the NetworkGameInfo to deserialize into
220 void NetworkUDPSocketHandler::ReceiveNetworkGameInfo(Packet
*p
, NetworkGameInfo
*info
)
222 static const Date MAX_DATE
= ConvertYMDToDate(MAX_YEAR
, 11, 31); // December is month 11
224 info
->game_info_version
= p
->Recv_uint8();
227 * Please observe the order.
228 * The parts must be read in the same order as they are sent!
231 /* Update the documentation in udp.h on changes
232 * to the NetworkGameInfo wire-protocol! */
234 switch (info
->game_info_version
) {
236 GRFConfig
**dst
= &info
->grfconfig
;
238 uint num_grfs
= p
->Recv_uint8();
240 /* Broken/bad data. It cannot have that many NewGRFs. */
241 if (num_grfs
> NETWORK_MAX_GRF_COUNT
) return;
243 for (i
= 0; i
< num_grfs
; i
++) {
244 GRFConfig
*c
= new GRFConfig();
245 this->ReceiveGRFIdentifier(p
, &c
->ident
);
246 this->HandleIncomingNetworkGameInfoGRFConfig(c
);
248 /* Append GRFConfig to the list */
256 info
->game_date
= Clamp(p
->Recv_uint32(), 0, MAX_DATE
);
257 info
->start_date
= Clamp(p
->Recv_uint32(), 0, MAX_DATE
);
261 info
->companies_max
= p
->Recv_uint8 ();
262 info
->companies_on
= p
->Recv_uint8 ();
263 info
->spectators_max
= p
->Recv_uint8 ();
267 p
->Recv_string(info
->server_name
, sizeof(info
->server_name
));
268 p
->Recv_string(info
->server_revision
, sizeof(info
->server_revision
));
269 info
->server_lang
= p
->Recv_uint8 ();
270 info
->use_password
= p
->Recv_bool ();
271 info
->clients_max
= p
->Recv_uint8 ();
272 info
->clients_on
= p
->Recv_uint8 ();
273 info
->spectators_on
= p
->Recv_uint8 ();
274 if (info
->game_info_version
< 3) { // 16 bits dates got scrapped and are read earlier
275 info
->game_date
= p
->Recv_uint16() + DAYS_TILL_ORIGINAL_BASE_YEAR
;
276 info
->start_date
= p
->Recv_uint16() + DAYS_TILL_ORIGINAL_BASE_YEAR
;
278 p
->Recv_string(info
->map_name
, sizeof(info
->map_name
));
279 info
->map_width
= p
->Recv_uint16();
280 info
->map_height
= p
->Recv_uint16();
281 info
->map_set
= p
->Recv_uint8 ();
282 info
->dedicated
= p
->Recv_bool ();
284 if (info
->server_lang
>= NETWORK_NUM_LANGUAGES
) info
->server_lang
= 0;
285 if (info
->map_set
>= NETWORK_NUM_LANDSCAPES
) info
->map_set
= 0;
290 * Handle an incoming packets by sending it to the correct function.
291 * @param p the received packet
292 * @param client_addr the sender of the packet
294 void NetworkUDPSocketHandler::HandleUDPPacket(Packet
*p
, NetworkAddress
*client_addr
)
298 /* New packet == new client, which has not quit yet */
301 type
= (PacketUDPType
)p
->Recv_uint8();
303 switch (this->HasClientQuit() ? PACKET_UDP_END
: type
) {
304 case PACKET_UDP_CLIENT_FIND_SERVER
: this->Receive_CLIENT_FIND_SERVER(p
, client_addr
); break;
305 case PACKET_UDP_SERVER_RESPONSE
: this->Receive_SERVER_RESPONSE(p
, client_addr
); break;
306 case PACKET_UDP_CLIENT_DETAIL_INFO
: this->Receive_CLIENT_DETAIL_INFO(p
, client_addr
); break;
307 case PACKET_UDP_SERVER_DETAIL_INFO
: this->Receive_SERVER_DETAIL_INFO(p
, client_addr
); break;
308 case PACKET_UDP_SERVER_REGISTER
: this->Receive_SERVER_REGISTER(p
, client_addr
); break;
309 case PACKET_UDP_MASTER_ACK_REGISTER
: this->Receive_MASTER_ACK_REGISTER(p
, client_addr
); break;
310 case PACKET_UDP_CLIENT_GET_LIST
: this->Receive_CLIENT_GET_LIST(p
, client_addr
); break;
311 case PACKET_UDP_MASTER_RESPONSE_LIST
: this->Receive_MASTER_RESPONSE_LIST(p
, client_addr
); break;
312 case PACKET_UDP_SERVER_UNREGISTER
: this->Receive_SERVER_UNREGISTER(p
, client_addr
); break;
313 case PACKET_UDP_CLIENT_GET_NEWGRFS
: this->Receive_CLIENT_GET_NEWGRFS(p
, client_addr
); break;
314 case PACKET_UDP_SERVER_NEWGRFS
: this->Receive_SERVER_NEWGRFS(p
, client_addr
); break;
315 case PACKET_UDP_MASTER_SESSION_KEY
: this->Receive_MASTER_SESSION_KEY(p
, client_addr
); break;
318 if (this->HasClientQuit()) {
319 DEBUG(net
, 0, "[udp] received invalid packet type %d from %s", type
, client_addr
->GetAddressAsString().c_str());
321 DEBUG(net
, 0, "[udp] received illegal packet from %s", client_addr
->GetAddressAsString().c_str());
328 * Helper for logging receiving invalid packets.
329 * @param type The received packet type.
330 * @param client_addr The address we received the packet from.
332 void NetworkUDPSocketHandler::ReceiveInvalidPacket(PacketUDPType type
, NetworkAddress
*client_addr
)
334 DEBUG(net
, 0, "[udp] received packet type %d on wrong port from %s", type
, client_addr
->GetAddressAsString().c_str());
337 void NetworkUDPSocketHandler::Receive_CLIENT_FIND_SERVER(Packet
*p
, NetworkAddress
*client_addr
) { this->ReceiveInvalidPacket(PACKET_UDP_CLIENT_FIND_SERVER
, client_addr
); }
338 void NetworkUDPSocketHandler::Receive_SERVER_RESPONSE(Packet
*p
, NetworkAddress
*client_addr
) { this->ReceiveInvalidPacket(PACKET_UDP_SERVER_RESPONSE
, client_addr
); }
339 void NetworkUDPSocketHandler::Receive_CLIENT_DETAIL_INFO(Packet
*p
, NetworkAddress
*client_addr
) { this->ReceiveInvalidPacket(PACKET_UDP_CLIENT_DETAIL_INFO
, client_addr
); }
340 void NetworkUDPSocketHandler::Receive_SERVER_DETAIL_INFO(Packet
*p
, NetworkAddress
*client_addr
) { this->ReceiveInvalidPacket(PACKET_UDP_SERVER_DETAIL_INFO
, client_addr
); }
341 void NetworkUDPSocketHandler::Receive_SERVER_REGISTER(Packet
*p
, NetworkAddress
*client_addr
) { this->ReceiveInvalidPacket(PACKET_UDP_SERVER_REGISTER
, client_addr
); }
342 void NetworkUDPSocketHandler::Receive_MASTER_ACK_REGISTER(Packet
*p
, NetworkAddress
*client_addr
) { this->ReceiveInvalidPacket(PACKET_UDP_MASTER_ACK_REGISTER
, client_addr
); }
343 void NetworkUDPSocketHandler::Receive_CLIENT_GET_LIST(Packet
*p
, NetworkAddress
*client_addr
) { this->ReceiveInvalidPacket(PACKET_UDP_CLIENT_GET_LIST
, client_addr
); }
344 void NetworkUDPSocketHandler::Receive_MASTER_RESPONSE_LIST(Packet
*p
, NetworkAddress
*client_addr
) { this->ReceiveInvalidPacket(PACKET_UDP_MASTER_RESPONSE_LIST
, client_addr
); }
345 void NetworkUDPSocketHandler::Receive_SERVER_UNREGISTER(Packet
*p
, NetworkAddress
*client_addr
) { this->ReceiveInvalidPacket(PACKET_UDP_SERVER_UNREGISTER
, client_addr
); }
346 void NetworkUDPSocketHandler::Receive_CLIENT_GET_NEWGRFS(Packet
*p
, NetworkAddress
*client_addr
) { this->ReceiveInvalidPacket(PACKET_UDP_CLIENT_GET_NEWGRFS
, client_addr
); }
347 void NetworkUDPSocketHandler::Receive_SERVER_NEWGRFS(Packet
*p
, NetworkAddress
*client_addr
) { this->ReceiveInvalidPacket(PACKET_UDP_SERVER_NEWGRFS
, client_addr
); }
348 void NetworkUDPSocketHandler::Receive_MASTER_SESSION_KEY(Packet
*p
, NetworkAddress
*client_addr
) { this->ReceiveInvalidPacket(PACKET_UDP_MASTER_SESSION_KEY
, client_addr
); }