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