OpenTTD
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 
101 const char *NetworkAddress::GetAddressAsString(bool with_family)
102 {
103  /* 6 = for the : and 5 for the decimal port number */
104  static char buf[NETWORK_HOSTNAME_LENGTH + 6 + 7];
105  this->GetAddressAsString(buf, lastof(buf), with_family);
106  return buf;
107 }
108 
114 static SOCKET ResolveLoopProc(addrinfo *runp)
115 {
116  /* We just want the first 'entry', so return a valid socket. */
117  return !INVALID_SOCKET;
118 }
119 
124 const sockaddr_storage *NetworkAddress::GetAddress()
125 {
126  if (!this->IsResolved()) {
127  /* Here we try to resolve a network address. We use SOCK_STREAM as
128  * socket type because some stupid OSes, like Solaris, cannot be
129  * bothered to implement the specifications and allow '0' as value
130  * that means "don't care whether it is SOCK_STREAM or SOCK_DGRAM".
131  */
132  this->Resolve(this->address.ss_family, SOCK_STREAM, AI_ADDRCONFIG, nullptr, ResolveLoopProc);
133  this->resolved = true;
134  }
135  return &this->address;
136 }
137 
143 bool NetworkAddress::IsFamily(int family)
144 {
145  if (!this->IsResolved()) {
146  this->Resolve(family, SOCK_STREAM, AI_ADDRCONFIG, nullptr, ResolveLoopProc);
147  }
148  return this->address.ss_family == family;
149 }
150 
157 bool NetworkAddress::IsInNetmask(const char *netmask)
158 {
159  /* Resolve it if we didn't do it already */
160  if (!this->IsResolved()) this->GetAddress();
161 
162  int cidr = this->address.ss_family == AF_INET ? 32 : 128;
163 
164  NetworkAddress mask_address;
165 
166  /* Check for CIDR separator */
167  const char *chr_cidr = strchr(netmask, '/');
168  if (chr_cidr != nullptr) {
169  int tmp_cidr = atoi(chr_cidr + 1);
170 
171  /* Invalid CIDR, treat as single host */
172  if (tmp_cidr > 0 || tmp_cidr < cidr) cidr = tmp_cidr;
173 
174  /* Remove the / so that NetworkAddress works on the IP portion */
175  std::string ip_str(netmask, chr_cidr - netmask);
176  mask_address = NetworkAddress(ip_str.c_str(), 0, this->address.ss_family);
177  } else {
178  mask_address = NetworkAddress(netmask, 0, this->address.ss_family);
179  }
180 
181  if (mask_address.GetAddressLength() == 0) return false;
182 
183  uint32 *ip;
184  uint32 *mask;
185  switch (this->address.ss_family) {
186  case AF_INET:
187  ip = (uint32*)&((struct sockaddr_in*)&this->address)->sin_addr.s_addr;
188  mask = (uint32*)&((struct sockaddr_in*)&mask_address.address)->sin_addr.s_addr;
189  break;
190 
191  case AF_INET6:
192  ip = (uint32*)&((struct sockaddr_in6*)&this->address)->sin6_addr;
193  mask = (uint32*)&((struct sockaddr_in6*)&mask_address.address)->sin6_addr;
194  break;
195 
196  default:
197  NOT_REACHED();
198  }
199 
200  while (cidr > 0) {
201  uint32 msk = cidr >= 32 ? (uint32)-1 : htonl(-(1 << (32 - cidr)));
202  if ((*mask++ & msk) != (*ip++ & msk)) return false;
203 
204  cidr -= 32;
205  }
206 
207  return true;
208 }
209 
219 SOCKET NetworkAddress::Resolve(int family, int socktype, int flags, SocketList *sockets, LoopProc func)
220 {
221  struct addrinfo *ai;
222  struct addrinfo hints;
223  memset(&hints, 0, sizeof (hints));
224  hints.ai_family = family;
225  hints.ai_flags = flags;
226  hints.ai_socktype = socktype;
227 
228  /* The port needs to be a string. Six is enough to contain all characters + '\0'. */
229  char port_name[6];
230  seprintf(port_name, lastof(port_name), "%u", this->GetPort());
231 
232  bool reset_hostname = false;
233  /* Setting both hostname to nullptr and port to 0 is not allowed.
234  * As port 0 means bind to any port, the other must mean that
235  * we want to bind to 'all' IPs. */
236  if (StrEmpty(this->hostname) && this->address_length == 0 && this->GetPort() == 0) {
237  reset_hostname = true;
238  int fam = this->address.ss_family;
239  if (fam == AF_UNSPEC) fam = family;
240  strecpy(this->hostname, fam == AF_INET ? "0.0.0.0" : "::", lastof(this->hostname));
241  }
242 
243  int e = getaddrinfo(StrEmpty(this->hostname) ? nullptr : this->hostname, port_name, &hints, &ai);
244 
245  if (reset_hostname) strecpy(this->hostname, "", lastof(this->hostname));
246 
247  if (e != 0) {
248  if (func != ResolveLoopProc) {
249  DEBUG(net, 0, "getaddrinfo for hostname \"%s\", port %s, address family %s and socket type %s failed: %s",
250  this->hostname, port_name, AddressFamilyAsString(family), SocketTypeAsString(socktype), FS2OTTD(gai_strerror(e)));
251  }
252  return INVALID_SOCKET;
253  }
254 
255  SOCKET sock = INVALID_SOCKET;
256  for (struct addrinfo *runp = ai; runp != nullptr; runp = runp->ai_next) {
257  /* When we are binding to multiple sockets, make sure we do not
258  * connect to one with exactly the same address twice. That's
259  * of course totally unneeded ;) */
260  if (sockets != nullptr) {
261  NetworkAddress address(runp->ai_addr, (int)runp->ai_addrlen);
262  if (sockets->Contains(address)) continue;
263  }
264  sock = func(runp);
265  if (sock == INVALID_SOCKET) continue;
266 
267  if (sockets == nullptr) {
268  this->address_length = (int)runp->ai_addrlen;
269  assert(sizeof(this->address) >= runp->ai_addrlen);
270  memcpy(&this->address, runp->ai_addr, runp->ai_addrlen);
271  break;
272  }
273 
274  NetworkAddress addr(runp->ai_addr, (int)runp->ai_addrlen);
275  (*sockets)[addr] = sock;
276  sock = INVALID_SOCKET;
277  }
278  freeaddrinfo (ai);
279 
280  return sock;
281 }
282 
288 static SOCKET ConnectLoopProc(addrinfo *runp)
289 {
290  const char *type = NetworkAddress::SocketTypeAsString(runp->ai_socktype);
291  const char *family = NetworkAddress::AddressFamilyAsString(runp->ai_family);
292  const char *address = NetworkAddress(runp->ai_addr, (int)runp->ai_addrlen).GetAddressAsString();
293 
294  SOCKET sock = socket(runp->ai_family, runp->ai_socktype, runp->ai_protocol);
295  if (sock == INVALID_SOCKET) {
296  DEBUG(net, 1, "[%s] could not create %s socket: %s", type, family, strerror(errno));
297  return INVALID_SOCKET;
298  }
299 
300  if (!SetNoDelay(sock)) DEBUG(net, 1, "[%s] setting TCP_NODELAY failed", type);
301 
302  if (connect(sock, runp->ai_addr, (int)runp->ai_addrlen) != 0) {
303  DEBUG(net, 1, "[%s] could not connect %s socket: %s", type, family, strerror(errno));
304  closesocket(sock);
305  return INVALID_SOCKET;
306  }
307 
308  /* Connection succeeded */
309  if (!SetNonBlocking(sock)) DEBUG(net, 0, "[%s] setting non-blocking mode failed", type);
310 
311  DEBUG(net, 1, "[%s] connected to %s", type, address);
312 
313  return sock;
314 }
315 
321 {
322  DEBUG(net, 1, "Connecting to %s", this->GetAddressAsString());
323 
324  return this->Resolve(AF_UNSPEC, SOCK_STREAM, AI_ADDRCONFIG, nullptr, ConnectLoopProc);
325 }
326 
332 static SOCKET ListenLoopProc(addrinfo *runp)
333 {
334  const char *type = NetworkAddress::SocketTypeAsString(runp->ai_socktype);
335  const char *family = NetworkAddress::AddressFamilyAsString(runp->ai_family);
336  const char *address = NetworkAddress(runp->ai_addr, (int)runp->ai_addrlen).GetAddressAsString();
337 
338  SOCKET sock = socket(runp->ai_family, runp->ai_socktype, runp->ai_protocol);
339  if (sock == INVALID_SOCKET) {
340  DEBUG(net, 0, "[%s] could not create %s socket on port %s: %s", type, family, address, strerror(errno));
341  return INVALID_SOCKET;
342  }
343 
344  if (runp->ai_socktype == SOCK_STREAM && !SetNoDelay(sock)) {
345  DEBUG(net, 3, "[%s] setting TCP_NODELAY failed for port %s", type, address);
346  }
347 
348  int on = 1;
349  /* The (const char*) cast is needed for windows!! */
350  if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on)) == -1) {
351  DEBUG(net, 3, "[%s] could not set reusable %s sockets for port %s: %s", type, family, address, strerror(errno));
352  }
353 
354 #ifndef __OS2__
355  if (runp->ai_family == AF_INET6 &&
356  setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&on, sizeof(on)) == -1) {
357  DEBUG(net, 3, "[%s] could not disable IPv4 over IPv6 on port %s: %s", type, address, strerror(errno));
358  }
359 #endif
360 
361  if (bind(sock, runp->ai_addr, (int)runp->ai_addrlen) != 0) {
362  DEBUG(net, 1, "[%s] could not bind on %s port %s: %s", type, family, address, strerror(errno));
363  closesocket(sock);
364  return INVALID_SOCKET;
365  }
366 
367  if (runp->ai_socktype != SOCK_DGRAM && listen(sock, 1) != 0) {
368  DEBUG(net, 1, "[%s] could not listen at %s port %s: %s", type, family, address, strerror(errno));
369  closesocket(sock);
370  return INVALID_SOCKET;
371  }
372 
373  /* Connection succeeded */
374  if (!SetNonBlocking(sock)) DEBUG(net, 0, "[%s] setting non-blocking mode failed for %s port %s", type, family, address);
375 
376  DEBUG(net, 1, "[%s] listening on %s port %s", type, family, address);
377  return sock;
378 }
379 
385 void NetworkAddress::Listen(int socktype, SocketList *sockets)
386 {
387  assert(sockets != nullptr);
388 
389  /* Setting both hostname to nullptr and port to 0 is not allowed.
390  * As port 0 means bind to any port, the other must mean that
391  * we want to bind to 'all' IPs. */
392  if (this->address_length == 0 && this->address.ss_family == AF_UNSPEC &&
393  StrEmpty(this->hostname) && this->GetPort() == 0) {
394  this->Resolve(AF_INET, socktype, AI_ADDRCONFIG | AI_PASSIVE, sockets, ListenLoopProc);
395  this->Resolve(AF_INET6, socktype, AI_ADDRCONFIG | AI_PASSIVE, sockets, ListenLoopProc);
396  } else {
397  this->Resolve(AF_UNSPEC, socktype, AI_ADDRCONFIG | AI_PASSIVE, sockets, ListenLoopProc);
398  }
399 }
400 
407 /* static */ const char *NetworkAddress::SocketTypeAsString(int socktype)
408 {
409  switch (socktype) {
410  case SOCK_STREAM: return "tcp";
411  case SOCK_DGRAM: return "udp";
412  default: return "unsupported";
413  }
414 }
415 
422 /* static */ const char *NetworkAddress::AddressFamilyAsString(int family)
423 {
424  switch (family) {
425  case AF_UNSPEC: return "either IPv4 or IPv6";
426  case AF_INET: return "IPv4";
427  case AF_INET6: return "IPv6";
428  default: return "unsupported";
429  }
430 }
const char * FS2OTTD(const TCHAR *name)
Convert to OpenTTD&#39;s encoding from that of the local environment.
Definition: win32.cpp:558
sockaddr_storage address
The resolved address.
Definition: address.h:31
int CDECL seprintf(char *str, const char *last, const char *format,...)
Safer implementation of snprintf; same as snprintf except:
Definition: string.cpp:407
Wrapper for (un)resolved network addresses; there&#39;s no reason to transform a numeric IP to a string a...
Definition: address.h:27
NetworkAddress(struct sockaddr_storage &address, int address_length)
Create a network address based on a resolved IP and port.
Definition: address.h:48
#define lastof(x)
Get the last element of an fixed size array.
Definition: depend.cpp:48
bool IsFamily(int family)
Checks of this address is of the given family.
Definition: address.cpp:143
static SOCKET ListenLoopProc(addrinfo *runp)
Helper function to resolve a listening.
Definition: address.cpp:332
int GetAddressLength()
Get the (valid) length of the address.
Definition: address.h:101
bool Contains(const T &key) const
Tests whether a key is assigned in this map.
static SOCKET ConnectLoopProc(addrinfo *runp)
Helper function to resolve a connected socket.
Definition: address.cpp:288
Wrapper for network addresses.
const char * GetHostname()
Get the hostname; in case it wasn&#39;t given the IPv4 dotted representation is given.
Definition: address.cpp:22
static const char * SocketTypeAsString(int socktype)
Convert the socket type into a string.
Definition: address.cpp:407
static SOCKET ResolveLoopProc(addrinfo *runp)
Helper function to resolve without opening a socket.
Definition: address.cpp:114
static const uint NETWORK_HOSTNAME_LENGTH
The maximum length of the host name, in bytes including &#39;\0&#39;.
Definition: config.h:42
bool IsInNetmask(const char *netmask)
Checks whether this IP address is contained by the given netmask.
Definition: address.cpp:157
#define DEBUG(name, level,...)
Output a line of debugging information.
Definition: debug.h:35
void SetPort(uint16 port)
Set the port.
Definition: address.cpp:54
SOCKET Resolve(int family, int socktype, int flags, SocketList *sockets, LoopProc func)
Resolve this address into a socket.
Definition: address.cpp:219
SOCKET Connect()
Connect to the given address.
Definition: address.cpp:320
static bool StrEmpty(const char *s)
Check if a string buffer is empty.
Definition: string_func.h:57
static bool SetNonBlocking(SOCKET d)
Try to set the socket into non-blocking mode.
char * strecpy(char *dst, const char *src, const char *last)
Copies characters from one buffer to another.
Definition: depend.cpp:66
static const char * AddressFamilyAsString(int family)
Convert the address family into a string.
Definition: address.cpp:422
SOCKET(* LoopProc)(addrinfo *runp)
Helper function to resolve something to a socket.
Definition: address.h:39
uint16 GetPort() const
Get the port.
Definition: address.cpp:35
char hostname[NETWORK_HOSTNAME_LENGTH]
The hostname.
Definition: address.h:29
static bool SetNoDelay(SOCKET d)
Try to set the socket to not delay sending.
bool resolved
Whether the address has been (tried to be) resolved.
Definition: address.h:32
const sockaddr_storage * GetAddress()
Get the address in its internal representation.
Definition: address.cpp:124
void GetAddressAsString(char *buffer, const char *last, bool with_family=true)
Get the address as a string, e.g.
Definition: address.cpp:77
int address_length
The length of the resolved address.
Definition: address.h:30
bool IsResolved() const
Check whether the IP address has been resolved already.
Definition: address.h:115
void Listen(int socktype, SocketList *sockets)
Make the given socket listen.
Definition: address.cpp:385