OpenTTD Source: src/network/core/address.cpp Source File

OpenTTD Source 1.11.0-RC1

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 <http://www.gnu.org/licenses/>.
6 */
7
10 #include "../../stdafx.h"
11
12 #include "address.h"
13 #include "../../debug.h"
14
15 #include "../../safeguards.h"
16
22 const char *NetworkAddress::GetHostname()
23 {
24 if (StrEmpty(this->hostname) && this->address.ss_family != AF_UNSPEC) {
25 assert(this->address_length != 0);
26 getnameinfo((struct sockaddr *)&this->address, this->address_length, this->hostname, sizeof(this->hostname), nullptr, 0, NI_NUMERICHOST);
27 }
28 return this->hostname;
29 }
30
35 uint16 NetworkAddress::GetPort() const
36 {
37 switch (this->address.ss_family) {
38 case AF_UNSPEC:
39 case AF_INET:
40 return ntohs(((const struct sockaddr_in *)&this->address)->sin_port);
41
42 case AF_INET6:
43 return ntohs(((const struct sockaddr_in6 *)&this->address)->sin6_port);
44
45 default:
46 NOT_REACHED();
47 }
48 }
49
54 void NetworkAddress::SetPort(uint16 port)
55 {
56 switch (this->address.ss_family) {
57 case AF_UNSPEC:
58 case AF_INET:
59 ((struct sockaddr_in*)&this->address)->sin_port = htons(port);
60 break;
61
62 case AF_INET6:
63 ((struct sockaddr_in6*)&this->address)->sin6_port = htons(port);
64 break;
65
66 default:
67 NOT_REACHED();
68 }
69 }
70
77 void NetworkAddress::GetAddressAsString(char *buffer, const char *last, bool with_family)
78 {
79 if (this->GetAddress()->ss_family == AF_INET6) buffer = strecpy(buffer, "[", last);
80 buffer = strecpy(buffer, this->GetHostname(), last);
81 if (this->GetAddress()->ss_family == AF_INET6) buffer = strecpy(buffer, "]", last);
82 buffer += seprintf(buffer, last, ":%d", this->GetPort());
83
84 if (with_family) {
85 char family;
86 switch (this->address.ss_family) {
87 case AF_INET: family = '4'; break;
88 case AF_INET6: family = '6'; break;
89 default: family = '?'; break;
90 }
91 seprintf(buffer, last, " (IPv%c)", family);
92 }
93 }
94
100 std::string NetworkAddress::GetAddressAsString(bool with_family)
101 {
102 /* 6 = for the : and 5 for the decimal port number */
103 char buf[NETWORK_HOSTNAME_LENGTH + 6 + 7];
104 this->GetAddressAsString(buf, lastof(buf), with_family);
105 return buf;
106 }
107
113 static SOCKET ResolveLoopProc(addrinfo *runp)
114 {
115 /* We just want the first 'entry', so return a valid socket. */
116 return !INVALID_SOCKET;
117 }
118
123 const sockaddr_storage *NetworkAddress::GetAddress()
124 {
125 if (!this->IsResolved()) {
126 /* Here we try to resolve a network address. We use SOCK_STREAM as
127 * socket type because some stupid OSes, like Solaris, cannot be
128 * bothered to implement the specifications and allow '0' as value
129 * that means "don't care whether it is SOCK_STREAM or SOCK_DGRAM".
130 */
131 this->Resolve(this->address.ss_family, SOCK_STREAM, AI_ADDRCONFIG, nullptr, ResolveLoopProc);
132 this->resolved = true;
133 }
134 return &this->address;
135 }
136
142 bool NetworkAddress::IsFamily(int family)
143 {
144 if (!this->IsResolved()) {
145 this->Resolve(family, SOCK_STREAM, AI_ADDRCONFIG, nullptr, ResolveLoopProc);
146 }
147 return this->address.ss_family == family;
148 }
149
156 bool NetworkAddress::IsInNetmask(const char *netmask)
157 {
158 /* Resolve it if we didn't do it already */
159 if (!this->IsResolved()) this->GetAddress();
160
161 int cidr = this->address.ss_family == AF_INET ? 32 : 128;
162
163 NetworkAddress mask_address;
164
165 /* Check for CIDR separator */
166 const char *chr_cidr = strchr(netmask, '/');
167 if (chr_cidr != nullptr) {
168 int tmp_cidr = atoi(chr_cidr + 1);
169
170 /* Invalid CIDR, treat as single host */
171 if (tmp_cidr > 0 || tmp_cidr < cidr) cidr = tmp_cidr;
172
173 /* Remove the / so that NetworkAddress works on the IP portion */
174 std::string ip_str(netmask, chr_cidr - netmask);
175 mask_address = NetworkAddress(ip_str.c_str(), 0, this->address.ss_family);
176 } else {
177 mask_address = NetworkAddress(netmask, 0, this->address.ss_family);
178 }
179
180 if (mask_address.GetAddressLength() == 0) return false;
181
182 uint32 *ip;
183 uint32 *mask;
184 switch (this->address.ss_family) {
185 case AF_INET:
186 ip = (uint32*)&((struct sockaddr_in*)&this->address)->sin_addr.s_addr;
187 mask = (uint32*)&((struct sockaddr_in*)&mask_address.address)->sin_addr.s_addr;
188 break;
189
190 case AF_INET6:
191 ip = (uint32*)&((struct sockaddr_in6*)&this->address)->sin6_addr;
192 mask = (uint32*)&((struct sockaddr_in6*)&mask_address.address)->sin6_addr;
193 break;
194
195 default:
196 NOT_REACHED();
197 }
198
199 while (cidr > 0) {
200 uint32 msk = cidr >= 32 ? (uint32)-1 : htonl(-(1 << (32 - cidr)));
201 if ((*mask++ & msk) != (*ip++ & msk)) return false;
202
203 cidr -= 32;
204 }
205
206 return true;
207 }
208
218 SOCKET NetworkAddress::Resolve(int family, int socktype, int flags, SocketList *sockets, LoopProc func)
219 {
220 struct addrinfo *ai;
221 struct addrinfo hints;
222 memset(&hints, 0, sizeof (hints));
223 hints.ai_family = family;
224 hints.ai_flags = flags;
225 hints.ai_socktype = socktype;
226
227 /* The port needs to be a string. Six is enough to contain all characters + '\0'. */
228 char port_name[6];
229 seprintf(port_name, lastof(port_name), "%u", this->GetPort());
230
231 bool reset_hostname = false;
232 /* Setting both hostname to nullptr and port to 0 is not allowed.
233 * As port 0 means bind to any port, the other must mean that
234 * we want to bind to 'all' IPs. */
235 if (StrEmpty(this->hostname) && this->address_length == 0 && this->GetPort() == 0) {
236 reset_hostname = true;
237 int fam = this->address.ss_family;
238 if (fam == AF_UNSPEC) fam = family;
239 strecpy(this->hostname, fam == AF_INET ? "0.0.0.0" : "::", lastof(this->hostname));
240 }
241
242 int e = getaddrinfo(StrEmpty(this->hostname) ? nullptr : this->hostname, port_name, &hints, &ai);
243
244 if (reset_hostname) strecpy(this->hostname, "", lastof(this->hostname));
245
246 if (e != 0) {
247 if (func != ResolveLoopProc) {
248 DEBUG(net, 0, "getaddrinfo for hostname \"%s\", port %s, address family %s and socket type %s failed: %s",
249 this->hostname, port_name, AddressFamilyAsString(family), SocketTypeAsString(socktype), FS2OTTD(gai_strerror(e)));
250 }
251 return INVALID_SOCKET;
252 }
253
254 SOCKET sock = INVALID_SOCKET;
255 for (struct addrinfo *runp = ai; runp != nullptr; runp = runp->ai_next) {
256 /* When we are binding to multiple sockets, make sure we do not
257 * connect to one with exactly the same address twice. That's
258 * of course totally unneeded ;) */
259 if (sockets != nullptr) {
260 NetworkAddress address(runp->ai_addr, (int)runp->ai_addrlen);
261 if (sockets->Contains(address)) continue;
262 }
263 sock = func(runp);
264 if (sock == INVALID_SOCKET) continue;
265
266 if (sockets == nullptr) {
267 this->address_length = (int)runp->ai_addrlen;
268 assert(sizeof(this->address) >= runp->ai_addrlen);
269 memcpy(&this->address, runp->ai_addr, runp->ai_addrlen);
270 #ifdef __EMSCRIPTEN__
271 /* Emscripten doesn't zero sin_zero, but as we compare addresses
272 * to see if they are the same address, we need them to be zero'd.
273 * Emscripten is, as far as we know, the only OS not doing this.
274 *
275 * https://github.com/emscripten-core/emscripten/issues/12998
276 */
277 if (this->address.ss_family == AF_INET) {
278 sockaddr_in *address_ipv4 = (sockaddr_in *)&this->address;
279 memset(address_ipv4->sin_zero, 0, sizeof(address_ipv4->sin_zero));
280 }
281 #endif
282 break;
283 }
284
285 NetworkAddress addr(runp->ai_addr, (int)runp->ai_addrlen);
286 (*sockets)[addr] = sock;
287 sock = INVALID_SOCKET;
288 }
289 freeaddrinfo (ai);
290
291 return sock;
292 }
293
299 static SOCKET ConnectLoopProc(addrinfo *runp)
300 {
301 const char *type = NetworkAddress::SocketTypeAsString(runp->ai_socktype);
302 const char *family = NetworkAddress::AddressFamilyAsString(runp->ai_family);
303 char address[NETWORK_HOSTNAME_LENGTH + 6 + 7];
304 NetworkAddress(runp->ai_addr, (int)runp->ai_addrlen).GetAddressAsString(address, lastof(address));
305
306 SOCKET sock = socket(runp->ai_family, runp->ai_socktype, runp->ai_protocol);
307 if (sock == INVALID_SOCKET) {
308 DEBUG(net, 1, "[%s] could not create %s socket: %s", type, family, strerror(errno));
309 return INVALID_SOCKET;
310 }
311
312 if (!SetNoDelay(sock)) DEBUG(net, 1, "[%s] setting TCP_NODELAY failed", type);
313
314 int err = connect(sock, runp->ai_addr, (int)runp->ai_addrlen);
315 #ifdef __EMSCRIPTEN__
316 /* Emscripten is asynchronous, and as such a connect() is still in
317 * progress by the time the call returns. */
318 if (err != 0 && errno != EINPROGRESS)
319 #else
320 if (err != 0)
321 #endif
322 {
323 DEBUG(net, 1, "[%s] could not connect %s socket: %s", type, family, strerror(errno));
324 closesocket(sock);
325 return INVALID_SOCKET;
326 }
327
328 /* Connection succeeded */
329 if (!SetNonBlocking(sock)) DEBUG(net, 0, "[%s] setting non-blocking mode failed", type);
330
331 DEBUG(net, 1, "[%s] connected to %s", type, address);
332
333 return sock;
334 }
335
340 SOCKET NetworkAddress::Connect()
341 {
342 DEBUG(net, 1, "Connecting to %s", this->GetAddressAsString().c_str());
343
344 return this->Resolve(AF_UNSPEC, SOCK_STREAM, AI_ADDRCONFIG, nullptr, ConnectLoopProc);
345 }
346
352 static SOCKET ListenLoopProc(addrinfo *runp)
353 {
354 const char *type = NetworkAddress::SocketTypeAsString(runp->ai_socktype);
355 const char *family = NetworkAddress::AddressFamilyAsString(runp->ai_family);
356 char address[NETWORK_HOSTNAME_LENGTH + 6 + 7];
357 NetworkAddress(runp->ai_addr, (int)runp->ai_addrlen).GetAddressAsString(address, lastof(address));
358
359 SOCKET sock = socket(runp->ai_family, runp->ai_socktype, runp->ai_protocol);
360 if (sock == INVALID_SOCKET) {
361 DEBUG(net, 0, "[%s] could not create %s socket on port %s: %s", type, family, address, strerror(errno));
362 return INVALID_SOCKET;
363 }
364
365 if (runp->ai_socktype == SOCK_STREAM && !SetNoDelay(sock)) {
366 DEBUG(net, 3, "[%s] setting TCP_NODELAY failed for port %s", type, address);
367 }
368
369 int on = 1;
370 /* The (const char*) cast is needed for windows!! */
371 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on)) == -1) {
372 DEBUG(net, 3, "[%s] could not set reusable %s sockets for port %s: %s", type, family, address, strerror(errno));
373 }
374
375 #ifndef __OS2__
376 if (runp->ai_family == AF_INET6 &&
377 setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&on, sizeof(on)) == -1) {
378 DEBUG(net, 3, "[%s] could not disable IPv4 over IPv6 on port %s: %s", type, address, strerror(errno));
379 }
380 #endif
381
382 if (bind(sock, runp->ai_addr, (int)runp->ai_addrlen) != 0) {
383 DEBUG(net, 1, "[%s] could not bind on %s port %s: %s", type, family, address, strerror(errno));
384 closesocket(sock);
385 return INVALID_SOCKET;
386 }
387
388 if (runp->ai_socktype != SOCK_DGRAM && listen(sock, 1) != 0) {
389 DEBUG(net, 1, "[%s] could not listen at %s port %s: %s", type, family, address, strerror(errno));
390 closesocket(sock);
391 return INVALID_SOCKET;
392 }
393
394 /* Connection succeeded */
395 if (!SetNonBlocking(sock)) DEBUG(net, 0, "[%s] setting non-blocking mode failed for %s port %s", type, family, address);
396
397 DEBUG(net, 1, "[%s] listening on %s port %s", type, family, address);
398 return sock;
399 }
400
406 void NetworkAddress::Listen(int socktype, SocketList *sockets)
407 {
408 assert(sockets != nullptr);
409
410 /* Setting both hostname to nullptr and port to 0 is not allowed.
411 * As port 0 means bind to any port, the other must mean that
412 * we want to bind to 'all' IPs. */
413 if (this->address_length == 0 && this->address.ss_family == AF_UNSPEC &&
414 StrEmpty(this->hostname) && this->GetPort() == 0) {
415 this->Resolve(AF_INET, socktype, AI_ADDRCONFIG | AI_PASSIVE, sockets, ListenLoopProc);
416 this->Resolve(AF_INET6, socktype, AI_ADDRCONFIG | AI_PASSIVE, sockets, ListenLoopProc);
417 } else {
418 this->Resolve(AF_UNSPEC, socktype, AI_ADDRCONFIG | AI_PASSIVE, sockets, ListenLoopProc);
419 }
420 }
421
428 /* static */ const char *NetworkAddress::SocketTypeAsString(int socktype)
429 {
430 switch (socktype) {
431 case SOCK_STREAM: return "tcp";
432 case SOCK_DGRAM: return "udp";
433 default: return "unsupported";
434 }
435 }
436
443 /* static */ const char *NetworkAddress::AddressFamilyAsString(int family)
444 {
445 switch (family) {
446 case AF_UNSPEC: return "either IPv4 or IPv6";
447 case AF_INET: return "IPv4";
448 case AF_INET6: return "IPv6";
449 default: return "unsupported";
450 }
451 }
NetworkAddress::Connect
SOCKET Connect()
Connect to the given address.
Definition: address.cpp:340
NetworkAddress::GetAddress
const sockaddr_storage * GetAddress()
Get the address in its internal representation.
Definition: address.cpp:123
FS2OTTD
const char * FS2OTTD(const wchar_t *name)
Convert to OpenTTD's encoding from wide characters.
Definition: win32.cpp:565
NetworkAddress::GetAddressLength
int GetAddressLength()
Get the (valid) length of the address.
Definition: address.h:103
NetworkAddress::SetPort
void SetPort(uint16 port)
Set the port.
Definition: address.cpp:54
NetworkAddress::Resolve
SOCKET Resolve(int family, int socktype, int flags, SocketList *sockets, LoopProc func)
Resolve this address into a socket.
Definition: address.cpp:218
NetworkAddress::resolved
bool resolved
Whether the address has been (tried to be) resolved.
Definition: address.h:34
ResolveLoopProc
static SOCKET ResolveLoopProc(addrinfo *runp)
Helper function to resolve without opening a socket.
Definition: address.cpp:113
SetNoDelay
static bool SetNoDelay(SOCKET d)
Try to set the socket to not delay sending.
Definition: os_abstraction.h:200
NetworkAddress::IsInNetmask
bool IsInNetmask(const char *netmask)
Checks whether this IP address is contained by the given netmask.
Definition: address.cpp:156
SmallMap< NetworkAddress, SOCKET >
SetNonBlocking
static bool SetNonBlocking(SOCKET d)
Try to set the socket into non-blocking mode.
Definition: os_abstraction.h:181
address.h
DEBUG
#define DEBUG(name, level,...)
Output a line of debugging information.
Definition: debug.h:35
NetworkAddress::GetHostname
const char * GetHostname()
Get the hostname; in case it wasn't given the IPv4 dotted representation is given.
Definition: address.cpp:22
ListenLoopProc
static SOCKET ListenLoopProc(addrinfo *runp)
Helper function to resolve a listening.
Definition: address.cpp:352
NetworkAddress::GetPort
uint16 GetPort() const
Get the port.
Definition: address.cpp:35
NetworkAddress::address_length
int address_length
The length of the resolved address.
Definition: address.h:32
StrEmpty
static bool StrEmpty(const char *s)
Check if a string buffer is empty.
Definition: string_func.h:60
NetworkAddress::NetworkAddress
NetworkAddress(struct sockaddr_storage &address, int address_length)
Create a network address based on a resolved IP and port.
Definition: address.h:50
NetworkAddress
Wrapper for (un)resolved network addresses; there's no reason to transform a numeric IP to a string a...
Definition: address.h:29
NetworkAddress::hostname
char hostname[NETWORK_HOSTNAME_LENGTH]
The hostname.
Definition: address.h:31
NetworkAddress::IsResolved
bool IsResolved() const
Check whether the IP address has been resolved already.
Definition: address.h:117
seprintf
int CDECL seprintf(char *str, const char *last, const char *format,...)
Safer implementation of snprintf; same as snprintf except:
Definition: string.cpp:442
NetworkAddress::SocketTypeAsString
static const char * SocketTypeAsString(int socktype)
Convert the socket type into a string.
Definition: address.cpp:428
NetworkAddress::IsFamily
bool IsFamily(int family)
Checks of this address is of the given family.
Definition: address.cpp:142
NETWORK_HOSTNAME_LENGTH
static const uint NETWORK_HOSTNAME_LENGTH
The maximum length of the host name, in bytes including '\0'.
Definition: config.h:42
strecpy
char * strecpy(char *dst, const char *src, const char *last)
Copies characters from one buffer to another.
Definition: string.cpp:112
NetworkAddress::AddressFamilyAsString
static const char * AddressFamilyAsString(int family)
Convert the address family into a string.
Definition: address.cpp:443
lastof
#define lastof(x)
Get the last element of an fixed size array.
Definition: stdafx.h:383
NetworkAddress::Listen
void Listen(int socktype, SocketList *sockets)
Make the given socket listen.
Definition: address.cpp:406
NetworkAddress::GetAddressAsString
void GetAddressAsString(char *buffer, const char *last, bool with_family=true)
Get the address as a string, e.g.
Definition: address.cpp:77
ConnectLoopProc
static SOCKET ConnectLoopProc(addrinfo *runp)
Helper function to resolve a connected socket.
Definition: address.cpp:299
NetworkAddress::address
sockaddr_storage address
The resolved address.
Definition: address.h:33
SmallMap::Contains
bool Contains(const T &key) const
Tests whether a key is assigned in this map.
Definition: smallmap_type.hpp:79