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