OpenTTD Source 20261112-master-gbcbec5e63f
udp.cpp
Go to the documentation of this file.
1/*
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 <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "../../stdafx.h"
11#include "../../debug.h"
12#include "udp.h"
13
14#include "../../safeguards.h"
15
21{
22 if (bind != nullptr) {
23 for (NetworkAddress &addr : *bind) {
24 this->bind.push_back(addr);
25 }
26 } else {
27 /* As an empty hostname and port 0 don't go well when
28 * resolving it we need to add an address for each of
29 * the address families we support. */
30 this->bind.emplace_back("", 0, AF_INET);
31 this->bind.emplace_back("", 0, AF_INET6);
32 }
33}
34
35
41{
42 /* Make sure socket is closed */
43 this->CloseSocket();
44
45 for (NetworkAddress &addr : this->bind) {
46 addr.Listen(SOCK_DGRAM, &this->sockets);
47 }
48
49 return !this->sockets.empty();
50}
51
56{
57 for (auto &s : this->sockets) {
58 closesocket(s.first);
59 }
60 this->sockets.clear();
61}
62
70void NetworkUDPSocketHandler::SendPacket(Packet &p, NetworkAddress &recv, bool all, bool broadcast)
71{
72 if (this->sockets.empty()) this->Listen();
73
74 for (auto &s : this->sockets) {
75 /* Make a local copy because if we resolve it we cannot
76 * easily unresolve it so we can resolve it later again. */
77 NetworkAddress send(recv);
78
79 /* Not the same type */
80 if (!send.IsFamily(s.second.GetAddress()->ss_family)) continue;
81
82 p.PrepareToSend();
83
84 if (broadcast) {
85 /* Enable broadcast */
86 unsigned long val = 1;
87 if (setsockopt(s.first, SOL_SOCKET, SO_BROADCAST, (char *) &val, sizeof(val)) < 0) {
88 Debug(Facility::Net, Severity::Error, "Setting broadcast mode failed: {}", NetworkError::GetLast().AsString());
89 }
90 }
91
92 /* Send the buffer */
93 std::ptrdiff_t res = p.TransferOut([&](std::span<const uint8_t> buffer) {
94 return sendto(s.first, reinterpret_cast<const char *>(buffer.data()), static_cast<int>(buffer.size()), 0, reinterpret_cast<const struct sockaddr *>(send.GetAddress()), send.GetAddressLength());
95 });
97
98 /* Check for any errors, but ignore it otherwise */
99 if (res == -1) Debug(Facility::Net, Severity::Error, "sendto({}) failed: {}", send.GetAddressAsString(), NetworkError::GetLast().AsString());
100
101 if (!all) break;
102 }
103}
104
109{
110 for (auto &s : this->sockets) {
111 for (int i = 0; i < 1000; i++) { // Do not infinitely loop when DoSing with UDP
112 struct sockaddr_storage client_addr{};
113
114 /* The limit is UDP_MTU, but also allocate that much as we need to read the whole packet in one go. */
115 Packet p(this, UDP_MTU, UDP_MTU);
116 socklen_t client_len = sizeof(client_addr);
117
118 /* Try to receive anything */
119 SetNonBlocking(s.first); // Some OSes seem to lose the non-blocking status of the socket
120 std::ptrdiff_t nbytes = p.TransferIn([&](std::span<uint8_t> buffer) {
121 return recvfrom(s.first, reinterpret_cast<char *>(buffer.data()), static_cast<int>(buffer.size()), 0, reinterpret_cast<struct sockaddr *>(&client_addr), &client_len);
122 });
123
124 /* Did we get the bytes for the base header of the packet? */
125 if (nbytes <= 0) break; // No data, i.e. no packet
126 if (nbytes <= 2) continue; // Invalid data; try next packet
127#ifdef __EMSCRIPTEN__
128 client_len = FixAddrLenForEmscripten(client_addr);
129#endif
130
131 NetworkAddress address(client_addr, client_len);
132
133 /* If the size does not match the packet must be corrupted.
134 * Otherwise it will be marked as corrupted later on. */
135 if (!p.ParsePacketSize() || static_cast<size_t>(nbytes) != p.Size()) {
136 Debug(Facility::Net, Severity::Error, "Received a packet with mismatching size from {}", address.GetAddressAsString());
137 continue;
138 }
139 if (!p.PrepareToRead()) {
140 Debug(Facility::Net, Severity::Error, "Invalid packet received (too small / decryption error)");
141 continue;
142 }
143
144 /* Handle the packet */
145 this->HandleUDPPacket(p, address);
146 }
147 }
148}
149
156{
157 /* New packet == new client, which has not quit yet */
158 this->Reopen();
159
160 PacketUDPType type = static_cast<PacketUDPType>(p.Recv_uint8());
161
162 switch (type) {
163 case PacketUDPType::ClientFindServer: this->ReceiveClientFindServer(p, client_addr); break;
164 case PacketUDPType::ServerResponse: this->ReceiveServerResponse(p, client_addr); break;
165
166 default:
167 Debug(Facility::Net, Severity::Critical, "[udp] Received invalid packet type {} from {}", type, client_addr.GetAddressAsString());
168 break;
169 }
170}
171
178{
179 Debug(Facility::Net, Severity::Critical, "[udp] Received packet type {} on wrong port from {}", type, client_addr.GetAddressAsString());
180}
181
std::vector< NetworkAddress > NetworkAddressList
Type for a list of addresses.
Definition address.h:18
Wrapper for (un)resolved network addresses; there's no reason to transform a numeric IP to a string a...
Definition address.h:26
int GetAddressLength()
Get the (valid) length of the address.
Definition address.h:93
bool IsFamily(int family)
Checks of this address is of the given family.
Definition address.cpp:134
const sockaddr_storage * GetAddress()
Get the address in its internal representation.
Definition address.cpp:115
std::string GetAddressAsString(bool with_family=true)
Get the address as a string, e.g.
Definition address.cpp:96
static NetworkError GetLast()
Get the last network error.
void Reopen()
Reopen the socket so we can send/receive stuff again.
Definition core.h:75
void CloseSocket()
Close the actual UDP socket.
Definition udp.cpp:55
bool Listen()
Start listening on the given host and port.
Definition udp.cpp:40
SocketList sockets
The opened sockets.
Definition udp.h:35
void SendPacket(Packet &p, NetworkAddress &recv, bool all=false, bool broadcast=false)
Send a packet over UDP.
Definition udp.cpp:70
virtual void ReceiveServerResponse(Packet &p, NetworkAddress &client_addr)
Response to a query letting the client know we are here.
Definition udp.cpp:183
void ReceivePackets()
Receive a packet at UDP level.
Definition udp.cpp:108
NetworkUDPSocketHandler(NetworkAddressList *bind=nullptr)
Create an UDP socket but don't listen yet.
Definition udp.cpp:20
void ReceiveInvalidPacket(PacketUDPType, NetworkAddress &client_addr)
Helper for logging receiving invalid packets.
Definition udp.cpp:177
NetworkAddressList bind
The address to bind to.
Definition udp.h:33
virtual void ReceiveClientFindServer(Packet &p, NetworkAddress &client_addr)
Queries to the server for information about the game.
Definition udp.cpp:182
void HandleUDPPacket(Packet &p, NetworkAddress &client_addr)
Handle an incoming packets by sending it to the correct function.
Definition udp.cpp:155
static const size_t UDP_MTU
Number of bytes we can pack in a single UDP packet.
Definition config.h:26
Functions related to debugging.
#define Debug(facility, severity, format_string,...)
Output a line of debugging information.
Definition debug.h:36
@ Net
Net message facility.
Definition debug_type.h:33
@ Critical
Critical, user should know about this.
Definition debug_type.h:15
@ Error
Error, but we are recovering.
Definition debug_type.h:16
@ Trace1
Trace information #1.
Definition debug_type.h:22
bool SetNonBlocking(SOCKET d)
Try to set the socket into non-blocking mode.
A number of safeguards to prevent using unsafe methods.
Definition of base types and functions in a cross-platform compatible way.
size_t Size() const
Get the number of bytes in the packet.
Definition packet.cpp:248
std::ptrdiff_t TransferIn(F transfer_function)
Transfer data from the given function into the packet.
Definition packet.h:182
bool PrepareToRead()
Prepares the packet so it can be read.
Definition packet.cpp:276
uint8_t Recv_uint8()
Read a 8 bits integer from the packet.
Definition packet.cpp:316
bool ParsePacketSize()
Reads the packet size from the raw packet and stores it in the packet->size.
Definition packet.cpp:257
void PrepareToSend()
Writes the packet size from the raw packet from packet->size.
Definition packet.cpp:64
std::ptrdiff_t TransferOut(F transfer_function)
Transfer data from the packet to the given function.
Definition packet.h:153
Basic functions to receive and send UDP packets.
PacketUDPType
Enum with all types of UDP packets.
Definition udp.h:20
@ ClientFindServer
Queries a game server for game information.
Definition udp.h:21
@ ServerResponse
Reply of the game server with game information.
Definition udp.h:22