OpenTTD Source  1.11.2
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 
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 
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  static bool _resolve_timeout_error_message_shown = false;
243  auto start = std::chrono::steady_clock::now();
244  int e = getaddrinfo(StrEmpty(this->hostname) ? nullptr : this->hostname, port_name, &hints, &ai);
245  auto end = std::chrono::steady_clock::now();
246  std::chrono::seconds duration = std::chrono::duration_cast<std::chrono::seconds>(end - start);
247  if (!_resolve_timeout_error_message_shown && duration >= std::chrono::seconds(5)) {
248  DEBUG(net, 0, "getaddrinfo for hostname \"%s\", port %s, address family %s and socket type %s took %i seconds",
249  this->hostname, port_name, AddressFamilyAsString(family), SocketTypeAsString(socktype), (int)duration.count());
250  DEBUG(net, 0, " this is likely an issue in the DNS name resolver's configuration causing it to time out");
251  _resolve_timeout_error_message_shown = true;
252  }
253 
254 
255  if (reset_hostname) strecpy(this->hostname, "", lastof(this->hostname));
256 
257  if (e != 0) {
258  if (func != ResolveLoopProc) {
259  DEBUG(net, 0, "getaddrinfo for hostname \"%s\", port %s, address family %s and socket type %s failed: %s",
260  this->hostname, port_name, AddressFamilyAsString(family), SocketTypeAsString(socktype), FS2OTTD(gai_strerror(e)));
261  }
262  return INVALID_SOCKET;
263  }
264 
265  SOCKET sock = INVALID_SOCKET;
266  for (struct addrinfo *runp = ai; runp != nullptr; runp = runp->ai_next) {
267  /* When we are binding to multiple sockets, make sure we do not
268  * connect to one with exactly the same address twice. That's
269  * of course totally unneeded ;) */
270  if (sockets != nullptr) {
271  NetworkAddress address(runp->ai_addr, (int)runp->ai_addrlen);
272  if (sockets->Contains(address)) continue;
273  }
274  sock = func(runp);
275  if (sock == INVALID_SOCKET) continue;
276 
277  if (sockets == nullptr) {
278  this->address_length = (int)runp->ai_addrlen;
279  assert(sizeof(this->address) >= runp->ai_addrlen);
280  memcpy(&this->address, runp->ai_addr, runp->ai_addrlen);
281 #ifdef __EMSCRIPTEN__
282  /* Emscripten doesn't zero sin_zero, but as we compare addresses
283  * to see if they are the same address, we need them to be zero'd.
284  * Emscripten is, as far as we know, the only OS not doing this.
285  *
286  * https://github.com/emscripten-core/emscripten/issues/12998
287  */
288  if (this->address.ss_family == AF_INET) {
289  sockaddr_in *address_ipv4 = (sockaddr_in *)&this->address;
290  memset(address_ipv4->sin_zero, 0, sizeof(address_ipv4->sin_zero));
291  }
292 #endif
293  break;
294  }
295 
296  NetworkAddress addr(runp->ai_addr, (int)runp->ai_addrlen);
297  (*sockets)[addr] = sock;
298  sock = INVALID_SOCKET;
299  }
300  freeaddrinfo (ai);
301 
302  return sock;
303 }
304 
310 static SOCKET ConnectLoopProc(addrinfo *runp)
311 {
312  const char *type = NetworkAddress::SocketTypeAsString(runp->ai_socktype);
313  const char *family = NetworkAddress::AddressFamilyAsString(runp->ai_family);
314  char address[NETWORK_HOSTNAME_LENGTH + 6 + 7];
315  NetworkAddress(runp->ai_addr, (int)runp->ai_addrlen).GetAddressAsString(address, lastof(address));
316 
317  SOCKET sock = socket(runp->ai_family, runp->ai_socktype, runp->ai_protocol);
318  if (sock == INVALID_SOCKET) {
319  DEBUG(net, 1, "[%s] could not create %s socket: %s", type, family, NetworkError::GetLast().AsString());
320  return INVALID_SOCKET;
321  }
322 
323  if (!SetNoDelay(sock)) DEBUG(net, 1, "[%s] setting TCP_NODELAY failed", type);
324 
325  int err = connect(sock, runp->ai_addr, (int)runp->ai_addrlen);
326 #ifdef __EMSCRIPTEN__
327  /* Emscripten is asynchronous, and as such a connect() is still in
328  * progress by the time the call returns. */
329  if (err != 0 && !NetworkError::GetLast().IsConnectInProgress())
330 #else
331  if (err != 0)
332 #endif
333  {
334  DEBUG(net, 1, "[%s] could not connect %s socket: %s", type, family, NetworkError::GetLast().AsString());
335  closesocket(sock);
336  return INVALID_SOCKET;
337  }
338 
339  /* Connection succeeded */
340  if (!SetNonBlocking(sock)) DEBUG(net, 0, "[%s] setting non-blocking mode failed", type);
341 
342  DEBUG(net, 1, "[%s] connected to %s", type, address);
343 
344  return sock;
345 }
346 
352 {
353  DEBUG(net, 1, "Connecting to %s", this->GetAddressAsString().c_str());
354 
355  return this->Resolve(AF_UNSPEC, SOCK_STREAM, AI_ADDRCONFIG, nullptr, ConnectLoopProc);
356 }
357 
363 static SOCKET ListenLoopProc(addrinfo *runp)
364 {
365  const char *type = NetworkAddress::SocketTypeAsString(runp->ai_socktype);
366  const char *family = NetworkAddress::AddressFamilyAsString(runp->ai_family);
367  char address[NETWORK_HOSTNAME_LENGTH + 6 + 7];
368  NetworkAddress(runp->ai_addr, (int)runp->ai_addrlen).GetAddressAsString(address, lastof(address));
369 
370  SOCKET sock = socket(runp->ai_family, runp->ai_socktype, runp->ai_protocol);
371  if (sock == INVALID_SOCKET) {
372  DEBUG(net, 0, "[%s] could not create %s socket on port %s: %s", type, family, address, NetworkError::GetLast().AsString());
373  return INVALID_SOCKET;
374  }
375 
376  if (runp->ai_socktype == SOCK_STREAM && !SetNoDelay(sock)) {
377  DEBUG(net, 3, "[%s] setting TCP_NODELAY failed for port %s", type, address);
378  }
379 
380  int on = 1;
381  /* The (const char*) cast is needed for windows!! */
382  if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on)) == -1) {
383  DEBUG(net, 3, "[%s] could not set reusable %s sockets for port %s: %s", type, family, address, NetworkError::GetLast().AsString());
384  }
385 
386 #ifndef __OS2__
387  if (runp->ai_family == AF_INET6 &&
388  setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&on, sizeof(on)) == -1) {
389  DEBUG(net, 3, "[%s] could not disable IPv4 over IPv6 on port %s: %s", type, address, NetworkError::GetLast().AsString());
390  }
391 #endif
392 
393  if (bind(sock, runp->ai_addr, (int)runp->ai_addrlen) != 0) {
394  DEBUG(net, 1, "[%s] could not bind on %s port %s: %s", type, family, address, NetworkError::GetLast().AsString());
395  closesocket(sock);
396  return INVALID_SOCKET;
397  }
398 
399  if (runp->ai_socktype != SOCK_DGRAM && listen(sock, 1) != 0) {
400  DEBUG(net, 1, "[%s] could not listen at %s port %s: %s", type, family, address, NetworkError::GetLast().AsString());
401  closesocket(sock);
402  return INVALID_SOCKET;
403  }
404 
405  /* Connection succeeded */
406  if (!SetNonBlocking(sock)) DEBUG(net, 0, "[%s] setting non-blocking mode failed for %s port %s", type, family, address);
407 
408  DEBUG(net, 1, "[%s] listening on %s port %s", type, family, address);
409  return sock;
410 }
411 
417 void NetworkAddress::Listen(int socktype, SocketList *sockets)
418 {
419  assert(sockets != nullptr);
420 
421  /* Setting both hostname to nullptr and port to 0 is not allowed.
422  * As port 0 means bind to any port, the other must mean that
423  * we want to bind to 'all' IPs. */
424  if (this->address_length == 0 && this->address.ss_family == AF_UNSPEC &&
425  StrEmpty(this->hostname) && this->GetPort() == 0) {
426  this->Resolve(AF_INET, socktype, AI_ADDRCONFIG | AI_PASSIVE, sockets, ListenLoopProc);
427  this->Resolve(AF_INET6, socktype, AI_ADDRCONFIG | AI_PASSIVE, sockets, ListenLoopProc);
428  } else {
429  this->Resolve(AF_UNSPEC, socktype, AI_ADDRCONFIG | AI_PASSIVE, sockets, ListenLoopProc);
430  }
431 }
432 
439 /* static */ const char *NetworkAddress::SocketTypeAsString(int socktype)
440 {
441  switch (socktype) {
442  case SOCK_STREAM: return "tcp";
443  case SOCK_DGRAM: return "udp";
444  default: return "unsupported";
445  }
446 }
447 
454 /* static */ const char *NetworkAddress::AddressFamilyAsString(int family)
455 {
456  switch (family) {
457  case AF_UNSPEC: return "either IPv4 or IPv6";
458  case AF_INET: return "IPv4";
459  case AF_INET6: return "IPv6";
460  default: return "unsupported";
461  }
462 }
NetworkAddress::Connect
SOCKET Connect()
Connect to the given address.
Definition: address.cpp:351
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
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 >
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
NetworkError::GetLast
static NetworkError GetLast()
Get the last network error.
Definition: os_abstraction.cpp:116
ListenLoopProc
static SOCKET ListenLoopProc(addrinfo *runp)
Helper function to resolve a listening.
Definition: address.cpp:363
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:460
NetworkAddress::SocketTypeAsString
static const char * SocketTypeAsString(int socktype)
Convert the socket type into a string.
Definition: address.cpp:439
SetNonBlocking
bool SetNonBlocking(SOCKET d)
Try to set the socket into non-blocking mode.
Definition: os_abstraction.cpp:133
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:454
lastof
#define lastof(x)
Get the last element of an fixed size array.
Definition: stdafx.h:385
SetNoDelay
bool SetNoDelay(SOCKET d)
Try to set the socket to not delay sending.
Definition: os_abstraction.cpp:151
NetworkAddress::Listen
void Listen(int socktype, SocketList *sockets)
Make the given socket listen.
Definition: address.cpp:417
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:310
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