OpenTTD Source 20261112-master-gbcbec5e63f
address.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
12#include "address.h"
13#include "../network_func.h"
14#include "../network_internal.h"
15#include "../../debug.h"
17
18#include "../../safeguards.h"
19
25const std::string &NetworkAddress::GetHostname()
26{
27 if (this->hostname.empty() && this->address.ss_family != AF_UNSPEC) {
28 assert(this->address_length != 0);
29 char buffer[NETWORK_HOSTNAME_LENGTH];
30 getnameinfo((struct sockaddr *)&this->address, this->address_length, buffer, sizeof(buffer), nullptr, 0, NI_NUMERICHOST);
31 this->hostname = buffer;
32 }
33 return this->hostname;
34}
35
41{
42 switch (this->address.ss_family) {
43 case AF_UNSPEC:
44 case AF_INET:
45 return ntohs(((const struct sockaddr_in *)&this->address)->sin_port);
46
47 case AF_INET6:
48 return ntohs(((const struct sockaddr_in6 *)&this->address)->sin6_port);
49
50 default:
51 NOT_REACHED();
52 }
53}
54
59void NetworkAddress::SetPort(uint16_t port)
60{
61 switch (this->address.ss_family) {
62 case AF_UNSPEC:
63 case AF_INET:
64 ((struct sockaddr_in*)&this->address)->sin_port = htons(port);
65 break;
66
67 case AF_INET6:
68 ((struct sockaddr_in6*)&this->address)->sin6_port = htons(port);
69 break;
70
71 default:
72 NOT_REACHED();
73 }
74}
75
82static std::string_view GetAddressFormatString(uint16_t family, bool with_family)
83{
84 switch (family) {
85 case AF_INET: return with_family ? "{}:{} (IPv4)" : "{}:{}";
86 case AF_INET6: return with_family ? "[{}]:{} (IPv6)" : "[{}]:{}";
87 default: return with_family ? "{}:{} (IPv?)" : "{}:{}";
88 }
89}
90
96std::string NetworkAddress::GetAddressAsString(bool with_family)
97{
98 return fmt::format(fmt::runtime(GetAddressFormatString(this->GetAddress()->ss_family, with_family)), this->GetHostname(), this->GetPort());
99}
100
105static SOCKET ResolveLoopProc(addrinfo *)
106{
107 /* We just want the first 'entry', so return a valid socket. */
108 return !INVALID_SOCKET;
109}
110
115const sockaddr_storage *NetworkAddress::GetAddress()
116{
117 if (!this->IsResolved()) {
118 /* Here we try to resolve a network address. We use SOCK_STREAM as
119 * socket type because some stupid OSes, like Solaris, cannot be
120 * bothered to implement the specifications and allow '0' as value
121 * that means "don't care whether it is SOCK_STREAM or SOCK_DGRAM".
122 */
123 this->Resolve(this->address.ss_family, SOCK_STREAM, AI_ADDRCONFIG, nullptr, ResolveLoopProc);
124 this->resolved = true;
125 }
126 return &this->address;
127}
128
135{
136 if (!this->IsResolved()) {
137 this->Resolve(family, SOCK_STREAM, AI_ADDRCONFIG, nullptr, ResolveLoopProc);
138 }
139 return this->address.ss_family == family;
140}
141
148bool NetworkAddress::IsInNetmask(std::string_view netmask)
149{
150 /* Resolve it if we didn't do it already */
151 if (!this->IsResolved()) this->GetAddress();
152
153 int cidr = this->address.ss_family == AF_INET ? 32 : 128;
154
155 StringConsumer consumer{netmask};
156 /* Check for CIDR separator */
157 NetworkAddress mask_address(consumer.ReadUntilChar('/', StringConsumer::SKIP_ONE_SEPARATOR), 0, this->address.ss_family);
158 if (mask_address.GetAddressLength() == 0) return false;
159
160 if (consumer.AnyBytesLeft()) {
161 int tmp_cidr = consumer.ReadIntegerBase(10, cidr);
162
163 /* Invalid CIDR, treat as single host */
164 if (tmp_cidr > 0 && tmp_cidr < cidr) cidr = tmp_cidr;
165 }
166
167 uint32_t *ip;
168 uint32_t *mask;
169 switch (this->address.ss_family) {
170 case AF_INET:
171 ip = (uint32_t*)&((struct sockaddr_in*)&this->address)->sin_addr.s_addr;
172 mask = (uint32_t*)&((struct sockaddr_in*)&mask_address.address)->sin_addr.s_addr;
173 break;
174
175 case AF_INET6:
176 ip = (uint32_t*)&((struct sockaddr_in6*)&this->address)->sin6_addr;
177 mask = (uint32_t*)&((struct sockaddr_in6*)&mask_address.address)->sin6_addr;
178 break;
179
180 default:
181 NOT_REACHED();
182 }
183
184 while (cidr > 0) {
185 uint32_t msk = cidr >= 32 ? (uint32_t)-1 : htonl(-(1 << (32 - cidr)));
186 if ((*mask++ & msk) != (*ip++ & msk)) return false;
187
188 cidr -= 32;
189 }
190
191 return true;
192}
193
203SOCKET NetworkAddress::Resolve(int family, int socktype, int flags, SocketList *sockets, LoopProc func)
204{
205 struct addrinfo *ai;
206 struct addrinfo hints{};
207 hints.ai_family = family;
208 hints.ai_flags = flags;
209 hints.ai_socktype = socktype;
210
211 /* The port needs to be a string. Six is enough to contain all characters + '\0'. */
212 std::string port_name = fmt::format("{}", this->GetPort());
213
214 bool reset_hostname = false;
215 /* Setting both hostname to nullptr and port to 0 is not allowed.
216 * As port 0 means bind to any port, the other must mean that
217 * we want to bind to 'all' IPs. */
218 if (this->hostname.empty() && this->address_length == 0 && this->GetPort() == 0) {
219 reset_hostname = true;
220 int fam = this->address.ss_family;
221 if (fam == AF_UNSPEC) fam = family;
222 this->hostname = fam == AF_INET ? "0.0.0.0" : "::";
223 }
224
225 static bool _resolve_timeout_error_message_shown = false;
226 auto start = std::chrono::steady_clock::now();
227 int e = getaddrinfo(this->hostname.empty() ? nullptr : this->hostname.c_str(), port_name.c_str(), &hints, &ai);
228 auto end = std::chrono::steady_clock::now();
229 std::chrono::seconds duration = std::chrono::duration_cast<std::chrono::seconds>(end - start);
230 if (!_resolve_timeout_error_message_shown && duration >= std::chrono::seconds(5)) {
231 Debug(Facility::Net, Severity::Critical, "getaddrinfo for hostname \"{}\", port {}, address family {} and socket type {} took {} seconds",
232 this->hostname, port_name, AddressFamilyAsString(family), SocketTypeAsString(socktype), duration.count());
233 Debug(Facility::Net, Severity::Critical, " this is likely an issue in the DNS name resolver's configuration causing it to time out");
234 _resolve_timeout_error_message_shown = true;
235 }
236
237
238 if (reset_hostname) this->hostname.clear();
239
240 if (e != 0) {
241 if (func != ResolveLoopProc) {
242 Debug(Facility::Net, Severity::Critical, "getaddrinfo for hostname \"{}\", port {}, address family {} and socket type {} failed: {}",
243 this->hostname, port_name, AddressFamilyAsString(family), SocketTypeAsString(socktype), FS2OTTD(gai_strerror(e)));
244 }
245 return INVALID_SOCKET;
246 }
247
248 SOCKET sock = INVALID_SOCKET;
249 for (struct addrinfo *runp = ai; runp != nullptr; runp = runp->ai_next) {
250 /* When we are binding to multiple sockets, make sure we do not
251 * connect to one with exactly the same address twice. That's
252 * of course totally unneeded ;) */
253 if (sockets != nullptr) {
254 NetworkAddress address(runp->ai_addr, (int)runp->ai_addrlen);
255 if (std::any_of(sockets->begin(), sockets->end(), [&address](const auto &p) { return p.second == address; })) continue;
256 }
257 sock = func(runp);
258 if (sock == INVALID_SOCKET) continue;
259
260 if (sockets == nullptr) {
261 this->address_length = (int)runp->ai_addrlen;
262 assert(sizeof(this->address) >= runp->ai_addrlen);
263 std::copy_n(reinterpret_cast<const std::byte *>(runp->ai_addr), runp->ai_addrlen, reinterpret_cast<std::byte *>(&this->address));
264#ifdef __EMSCRIPTEN__
265 /* Emscripten doesn't zero sin_zero, but as we compare addresses
266 * to see if they are the same address, we need them to be zeroed.
267 * Emscripten is, as far as we know, the only OS not doing this.
268 *
269 * https://github.com/emscripten-core/emscripten/issues/12998
270 */
271 if (this->address.ss_family == AF_INET) {
272 sockaddr_in *address_ipv4 = (sockaddr_in *)&this->address;
273 std::ranges::fill(address_ipv4->sin_zero, 0);
274 }
275#endif
276 break;
277 }
278
279 NetworkAddress addr(runp->ai_addr, (int)runp->ai_addrlen);
280 (*sockets)[sock] = std::move(addr);
281 sock = INVALID_SOCKET;
282 }
283 freeaddrinfo (ai);
284
285 return sock;
286}
287
293static SOCKET ListenLoopProc(addrinfo *runp)
294{
295 std::string address = NetworkAddress(runp->ai_addr, (int)runp->ai_addrlen).GetAddressAsString();
296
297 SOCKET sock = socket(runp->ai_family, runp->ai_socktype, runp->ai_protocol);
298 if (sock == INVALID_SOCKET) {
299 std::string_view type = NetworkAddress::SocketTypeAsString(runp->ai_socktype);
300 std::string_view family = NetworkAddress::AddressFamilyAsString(runp->ai_family);
301 Debug(Facility::Net, Severity::Critical, "Could not create {} {} socket: {}", type, family, NetworkError::GetLast().AsString());
302 return INVALID_SOCKET;
303 }
304
305 if (runp->ai_socktype == SOCK_STREAM && !SetNoDelay(sock)) {
306 Debug(Facility::Net, Severity::Error, "Setting no-delay mode failed: {}", NetworkError::GetLast().AsString());
307 }
308
309 if (!SetReusePort(sock)) {
310 Debug(Facility::Net, Severity::Critical, "Setting reuse-address mode failed: {}", NetworkError::GetLast().AsString());
311 }
312
313 int on = 1;
314 if (runp->ai_family == AF_INET6 &&
315 setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast<const char *>(&on), sizeof(on)) == -1) {
316 Debug(Facility::Net, Severity::Notice, "Could not disable IPv4 over IPv6: {}", NetworkError::GetLast().AsString());
317 }
318
319 if (bind(sock, runp->ai_addr, (int)runp->ai_addrlen) != 0) {
320 Debug(Facility::Net, Severity::Critical, "Could not bind socket on {}: {}", address, NetworkError::GetLast().AsString());
321 closesocket(sock);
322 return INVALID_SOCKET;
323 }
324
325 if (runp->ai_socktype != SOCK_DGRAM && listen(sock, 1) != 0) {
326 Debug(Facility::Net, Severity::Critical, "Could not listen on socket: {}", NetworkError::GetLast().AsString());
327 closesocket(sock);
328 return INVALID_SOCKET;
329 }
330
331 /* Connection succeeded */
332
333 if (!SetNonBlocking(sock)) {
334 Debug(Facility::Net, Severity::Critical, "Setting non-blocking mode failed: {}", NetworkError::GetLast().AsString());
335 }
336
337 Debug(Facility::Net, Severity::Notice, "Listening on {}", address);
338 return sock;
339}
340
347{
348 assert(sockets != nullptr);
349
350 /* Setting both hostname to "" and port to 0 is not allowed.
351 * As port 0 means bind to any port, the other must mean that
352 * we want to bind to 'all' IPs. */
353 if (this->address_length == 0 && this->address.ss_family == AF_UNSPEC &&
354 this->hostname.empty() && this->GetPort() == 0) {
355 this->Resolve(AF_INET, socktype, AI_ADDRCONFIG | AI_PASSIVE, sockets, ListenLoopProc);
356 this->Resolve(AF_INET6, socktype, AI_ADDRCONFIG | AI_PASSIVE, sockets, ListenLoopProc);
357 } else {
358 this->Resolve(AF_UNSPEC, socktype, AI_ADDRCONFIG | AI_PASSIVE, sockets, ListenLoopProc);
359 }
360}
361
368/* static */ std::string_view NetworkAddress::SocketTypeAsString(int socktype)
369{
370 switch (socktype) {
371 case SOCK_STREAM: return "tcp";
372 case SOCK_DGRAM: return "udp";
373 default: return "unsupported";
374 }
375}
376
383/* static */ std::string_view NetworkAddress::AddressFamilyAsString(int family)
384{
385 switch (family) {
386 case AF_UNSPEC: return "either IPv4 or IPv6";
387 case AF_INET: return "IPv4";
388 case AF_INET6: return "IPv6";
389 default: return "unsupported";
390 }
391}
392
399{
400 sockaddr_storage addr = {};
401 socklen_t addr_len = sizeof(addr);
402 if (getpeername(sock, (sockaddr *)&addr, &addr_len) != 0) {
403 Debug(Facility::Net, Severity::Critical, "Failed to get address of the peer: {}", NetworkError::GetLast().AsString());
404 return NetworkAddress();
405 }
406 return NetworkAddress(addr, addr_len);
407}
408
415{
416 sockaddr_storage addr = {};
417 socklen_t addr_len = sizeof(addr);
418 if (getsockname(sock, (sockaddr *)&addr, &addr_len) != 0) {
419 Debug(Facility::Net, Severity::Critical, "Failed to get address of the socket: {}", NetworkError::GetLast().AsString());
420 return NetworkAddress();
421 }
422 return NetworkAddress(addr, addr_len);
423}
424
430/* static */ const std::string NetworkAddress::GetPeerName(SOCKET sock)
431{
433}
434
445/* static */ ServerAddress ServerAddress::Parse(std::string_view connection_string, uint16_t default_port, CompanyID *company_id)
446{
447 if (connection_string.starts_with("+")) {
448 std::string_view invite_code = ParseCompanyFromConnectionString(connection_string, company_id);
449 return ServerAddress(ServerAddressType::InviteCode, std::string(invite_code));
450 }
451
452 uint16_t port = default_port;
453 std::string_view ip = ParseFullConnectionString(connection_string, port, company_id);
454 return ServerAddress(ServerAddressType::Direct, fmt::format("{}:{}", ip, port));
455}
static SOCKET ListenLoopProc(addrinfo *runp)
Helper function to resolve a listening.
Definition address.cpp:293
static SOCKET ResolveLoopProc(addrinfo *)
Helper function to resolve without opening a socket.
Definition address.cpp:105
static std::string_view GetAddressFormatString(uint16_t family, bool with_family)
Helper to get the formatting string of an address for a given family.
Definition address.cpp:82
Wrapper for network addresses.
@ InviteCode
Server-address is based on an invite code.
Definition address.h:175
@ Direct
Server-address is based on an hostname:port.
Definition address.h:174
std::map< SOCKET, NetworkAddress > SocketList
Type for a mapping between address and socket.
Definition address.h:19
Wrapper for (un)resolved network addresses; there's no reason to transform a numeric IP to a string a...
Definition address.h:26
static NetworkAddress GetPeerAddress(SOCKET sock)
Get the peer address of a socket as NetworkAddress.
Definition address.cpp:398
bool resolved
Whether the address has been (tried to be) resolved.
Definition address.h:31
int GetAddressLength()
Get the (valid) length of the address.
Definition address.h:93
sockaddr_storage address
The resolved address.
Definition address.h:30
static std::string_view AddressFamilyAsString(int family)
Convert the address family into a string.
Definition address.cpp:383
bool IsFamily(int family)
Checks of this address is of the given family.
Definition address.cpp:134
bool IsResolved() const
Check whether the IP address has been resolved already.
Definition address.h:107
static const std::string GetPeerName(SOCKET sock)
Get the peer name of a socket in string format.
Definition address.cpp:430
SOCKET(* LoopProc)(addrinfo *runp)
Helper function to resolve something to a socket.
Definition address.h:38
static std::string_view SocketTypeAsString(int socktype)
Convert the socket type into a string.
Definition address.cpp:368
static NetworkAddress GetSockAddress(SOCKET sock)
Get the local address of a socket as NetworkAddress.
Definition address.cpp:414
std::string hostname
The hostname.
Definition address.h:28
uint16_t GetPort() const
Get the port.
Definition address.cpp:40
void Listen(int socktype, SocketList *sockets)
Make the given socket listen.
Definition address.cpp:346
SOCKET Resolve(int family, int socktype, int flags, SocketList *sockets, LoopProc func)
Resolve this address into a socket.
Definition address.cpp:203
void SetPort(uint16_t port)
Set the port.
Definition address.cpp:59
NetworkAddress(struct sockaddr_storage &address, int address_length)
Create a network address based on a resolved IP and port.
Definition address.h:47
const sockaddr_storage * GetAddress()
Get the address in its internal representation.
Definition address.cpp:115
const std::string & GetHostname()
Get the hostname; in case it wasn't given the IPv4 dotted representation is given.
Definition address.cpp:25
int address_length
The length of the resolved address.
Definition address.h:29
std::string GetAddressAsString(bool with_family=true)
Get the address as a string, e.g.
Definition address.cpp:96
bool IsInNetmask(std::string_view netmask)
Checks whether this IP address is contained by the given netmask.
Definition address.cpp:148
static NetworkError GetLast()
Get the last network error.
std::string connection_string
The connection string for this ServerAddress.
Definition address.h:197
static ServerAddress Parse(std::string_view connection_string, uint16_t default_port, CompanyID *company_id=nullptr)
Convert a string containing either "hostname", "hostname:port" or invite code to a ServerAddress,...
Definition address.cpp:445
ServerAddress(ServerAddressType type, std::string &&connection_string)
Create a new ServerAddress object.
Definition address.h:193
Parse data from a string / buffer.
std::string_view ReadUntilChar(char c, SeparatorUsage sep)
Read data until the first occurrence of 8-bit char 'c', and advance reader.
@ SKIP_ONE_SEPARATOR
Read and discard one separator, do not include it in the result.
bool AnyBytesLeft() const noexcept
Check whether any bytes left to read.
T ReadIntegerBase(int base, T def=0, bool clamp=false)
Read and parse an integer in number 'base', and advance the reader.
static const uint NETWORK_HOSTNAME_LENGTH
The maximum length of the host name, in bytes including '\0'.
Definition config.h:52
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
@ Notice
Notice.
Definition debug_type.h:18
@ Critical
Critical, user should know about this.
Definition debug_type.h:15
@ Error
Error, but we are recovering.
Definition debug_type.h:16
std::string_view ParseCompanyFromConnectionString(std::string_view connection_string, CompanyID *company_id)
Parse the company part ("#company" postfix) of a connecting string.
Definition network.cpp:483
std::string_view ParseFullConnectionString(std::string_view connection_string, uint16_t &port, CompanyID *company_id)
Converts a string to ip/port/company Format: IP:port::company.
Definition network.cpp:527
Network functions used by other parts of OpenTTD.
Variables and function used internally.
bool SetReusePort(SOCKET d)
Try to set the socket to reuse ports.
bool SetNoDelay(SOCKET d)
Try to set the socket to not delay sending.
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.
Parse strings.
SocketList TCPListenHandler< Tsocket, EnumPacketType, Tfull_packet, Tban_packet >::sockets
Instantiate the sockets.
Definition tcp_listen.h:180
std::string FS2OTTD(std::wstring_view name)
Convert to OpenTTD's encoding from a wide string.
Definition win32.cpp:373