# address.cpp

Go to the documentation of this file.

    00001 /* $Id: address.cpp 17693 2009-10-04 17:16:41Z rubidium $ */
    00002
    00003 /*
    00004  * This file is part of OpenTTD.
    00005  * 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.
    00006  * 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.
    00007  * 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/>.
    00008  */
    00009
    00012 #include "../../stdafx.h"
    00013
    00014 #ifdef ENABLE_NETWORK
    00015
    00016 #include "address.h"
    00017 #include "../../debug.h"
    00018
    00019 const char *NetworkAddress::GetHostname()
    00020 {
    00021   if (StrEmpty(this->hostname) && this->address.ss_family != AF_UNSPEC) {
    00022     assert(this->address_length != 0);
    00023     getnameinfo((struct sockaddr *)&this->address, this->address_length, this->hostname, sizeof(this->hostname), NULL, 0, NI_NUMERICHOST);
    00024   }
    00025   return this->hostname;
    00026 }
    00027
    00028 uint16 NetworkAddress::GetPort() const
    00029 {
    00030   switch (this->address.ss_family) {
    00031     case AF_UNSPEC:
    00032     case AF_INET:
    00033       return ntohs(((struct sockaddr_in *)&this->address)->sin_port);
    00034
    00035     case AF_INET6:
    00036       return ntohs(((struct sockaddr_in6 *)&this->address)->sin6_port);
    00037
    00038     default:
    00039       NOT_REACHED();
    00040   }
    00041 }
    00042
    00043 void NetworkAddress::SetPort(uint16 port)
    00044 {
    00045   switch (this->address.ss_family) {
    00046     case AF_UNSPEC:
    00047     case AF_INET:
    00048       ((struct sockaddr_in*)&this->address)->sin_port = htons(port);
    00049       break;
    00050
    00051     case AF_INET6:
    00052       ((struct sockaddr_in6*)&this->address)->sin6_port = htons(port);
    00053       break;
    00054
    00055     default:
    00056       NOT_REACHED();
    00057   }
    00058 }
    00059
    00060 void NetworkAddress::GetAddressAsString(char *buffer, const char *last, bool with_family)
    00061 {
    00062   if (this->GetAddress()->ss_family == AF_INET6) buffer = strecpy(buffer, "[", last);
    00063   buffer = strecpy(buffer, this->GetHostname(), last);
    00064   if (this->GetAddress()->ss_family == AF_INET6) buffer = strecpy(buffer, "]", last);
    00065   buffer += seprintf(buffer, last, ":%d", this->GetPort());
    00066
    00067   if (with_family) {
    00068     char family;
    00069     switch (this->address.ss_family) {
    00070       case AF_INET:  family = '4'; break;
    00071       case AF_INET6: family = '6'; break;
    00072       default:       family = '?'; break;
    00073     }
    00074     seprintf(buffer, last, " (IPv%c)", family);
    00075   }
    00076 }
    00077
    00078 const char *NetworkAddress::GetAddressAsString(bool with_family)
    00079 {
    00080   /* 6 = for the : and 5 for the decimal port number */
    00081   static char buf[NETWORK_HOSTNAME_LENGTH + 6 + 7];
    00082   this->GetAddressAsString(buf, lastof(buf), with_family);
    00083   return buf;
    00084 }
    00085
    00091 static SOCKET ResolveLoopProc(addrinfo *runp)
    00092 {
    00093   /* We just want the first 'entry', so return a valid socket. */
    00094   return !INVALID_SOCKET;
    00095 }
    00096
    00097 const sockaddr_storage *NetworkAddress::GetAddress()
    00098 {
    00099   if (!this->IsResolved()) {
    00100     /* Here we try to resolve a network address. We use SOCK_STREAM as
    00101      * socket type because some stupid OSes, like Solaris, cannot be
    00102      * bothered to implement the specifications and allow '0' as value
    00103      * that means "don't care whether it is SOCK_STREAM or SOCK_DGRAM".
    00104      */
    00105     this->Resolve(this->address.ss_family, SOCK_STREAM, AI_ADDRCONFIG, NULL, ResolveLoopProc);
    00106   }
    00107   return &this->address;
    00108 }
    00109
    00110 bool NetworkAddress::IsFamily(int family)
    00111 {
    00112   if (!this->IsResolved()) {
    00113     this->Resolve(family, SOCK_STREAM, AI_ADDRCONFIG, NULL, ResolveLoopProc);
    00114   }
    00115   return this->address.ss_family == family;
    00116 }
    00117
    00118 bool NetworkAddress::IsInNetmask(char *netmask)
    00119 {
    00120   /* Resolve it if we didn't do it already */
    00121   if (!this->IsResolved()) this->GetAddress();
    00122
    00123   int cidr = this->address.ss_family == AF_INET ? 32 : 128;
    00124
    00125   NetworkAddress mask_address;
    00126
    00127   /* Check for CIDR separator */
    00128   char *chr_cidr = strchr(netmask, '/');
    00129   if (chr_cidr != NULL) {
    00130     int tmp_cidr = atoi(chr_cidr + 1);
    00131
    00132     /* Invalid CIDR, treat as single host */
    00133     if (tmp_cidr > 0 || tmp_cidr < cidr) cidr = tmp_cidr;
    00134
    00135     /* Remove and then replace the / so that NetworkAddress works on the IP portion */
    00136     *chr_cidr = '\0';
    00137     mask_address = NetworkAddress(netmask, 0, this->address.ss_family);
    00138     *chr_cidr = '/';
    00139   } else {
    00140     mask_address = NetworkAddress(netmask, 0, this->address.ss_family);
    00141   }
    00142
    00143   if (mask_address.GetAddressLength() == 0) return false;
    00144
    00145   uint32 *ip;
    00146   uint32 *mask;
    00147   switch (this->address.ss_family) {
    00148     case AF_INET:
    00149       ip = (uint32*)&((struct sockaddr_in*)&this->address)->sin_addr.s_addr;
    00150       mask = (uint32*)&((struct sockaddr_in*)&mask_address.address)->sin_addr.s_addr;
    00151       break;
    00152
    00153     case AF_INET6:
    00154       ip = (uint32*)&((struct sockaddr_in6*)&this->address)->sin6_addr;
    00155       mask = (uint32*)&((struct sockaddr_in6*)&mask_address.address)->sin6_addr;
    00156       break;
    00157
    00158     default:
    00159       NOT_REACHED();
    00160   }
    00161
    00162   while (cidr > 0) {
    00163     uint32 msk = cidr >= 32 ? (uint32)-1 : htonl(-(1 << (32 - cidr)));
    00164     if ((*mask & msk) != (*ip & msk)) return false;
    00165
    00166     cidr -= 32;
    00167   }
    00168
    00169   return true;
    00170 }
    00171
    00172 SOCKET NetworkAddress::Resolve(int family, int socktype, int flags, SocketList *sockets, LoopProc func)
    00173 {
    00174   struct addrinfo *ai;
    00175   struct addrinfo hints;
    00176   memset(&hints, 0, sizeof (hints));
    00177   hints.ai_family   = family;
    00178   hints.ai_flags    = flags;
    00179   hints.ai_socktype = socktype;
    00180
    00181   /* The port needs to be a string. Six is enough to contain all characters + '\0'. */
    00182   char port_name[6];
    00183   seprintf(port_name, lastof(port_name), "%u", this->GetPort());
    00184
    00185   bool reset_hostname = false;
    00186   /* Setting both hostname to NULL and port to 0 is not allowed.
    00187    * As port 0 means bind to any port, the other must mean that
    00188    * we want to bind to 'all' IPs. */
    00189   if (StrEmpty(this->hostname) && this->address_length == 0 && this->GetPort() == 0) {
    00190     reset_hostname = true;
    00191     int fam = this->address.ss_family;
    00192     if (fam == AF_UNSPEC) fam = family;
    00193     strecpy(this->hostname, fam == AF_INET ? "0.0.0.0" : "::", lastof(this->hostname));
    00194   }
    00195
    00196   int e = getaddrinfo(StrEmpty(this->hostname) ? NULL : this->hostname, port_name, &hints, &ai);
    00197
    00198   if (reset_hostname) strecpy(this->hostname, "", lastof(this->hostname));
    00199
    00200   if (e != 0) {
    00201     if (func != ResolveLoopProc) {
    00202       DEBUG(net, 0, "getaddrinfo for hostname \"%s\", port %s, address family %s and socket type %s failed: %s",
    00203         this->hostname, port_name, AddressFamilyAsString(family), SocketTypeAsString(socktype), FS2OTTD(gai_strerror(e)));
    00204     }
    00205     return INVALID_SOCKET;
    00206   }
    00207
    00208   SOCKET sock = INVALID_SOCKET;
    00209   for (struct addrinfo *runp = ai; runp != NULL; runp = runp->ai_next) {
    00210     /* When we are binding to multiple sockets, make sure we do not
    00211      * connect to one with exactly the same address twice. That's
    00212      * ofcourse totally unneeded ;) */
    00213     if (sockets != NULL) {
    00214       NetworkAddress address(runp->ai_addr, (int)runp->ai_addrlen);
    00215       if (sockets->Find(address) != sockets->End()) continue;
    00216     }
    00217     sock = func(runp);
    00218     if (sock == INVALID_SOCKET) continue;
    00219
    00220     if (sockets == NULL) {
    00221       this->address_length = (int)runp->ai_addrlen;
    00222       assert(sizeof(this->address) >= runp->ai_addrlen);
    00223       memcpy(&this->address, runp->ai_addr, runp->ai_addrlen);
    00224       break;
    00225     }
    00226
    00227     NetworkAddress addr(runp->ai_addr, (int)runp->ai_addrlen);
    00228     (*sockets)[addr] = sock;
    00229     sock = INVALID_SOCKET;
    00230   }
    00231   freeaddrinfo (ai);
    00232
    00233   return sock;
    00234 }
    00235
    00241 static SOCKET ConnectLoopProc(addrinfo *runp)
    00242 {
    00243   const char *type = NetworkAddress::SocketTypeAsString(runp->ai_socktype);
    00244   const char *family = NetworkAddress::AddressFamilyAsString(runp->ai_family);
    00245   const char *address = NetworkAddress(runp->ai_addr, (int)runp->ai_addrlen).GetAddressAsString();
    00246
    00247   SOCKET sock = socket(runp->ai_family, runp->ai_socktype, runp->ai_protocol);
    00248   if (sock == INVALID_SOCKET) {
    00249     DEBUG(net, 1, "[%s] could not create %s socket: %s", type, family, strerror(errno));
    00250     return INVALID_SOCKET;
    00251   }
    00252
    00253   if (!SetNoDelay(sock)) DEBUG(net, 1, "[%s] setting TCP_NODELAY failed", type);
    00254
    00255   if (connect(sock, runp->ai_addr, (int)runp->ai_addrlen) != 0) {
    00256     DEBUG(net, 1, "[%s] could not connect %s socket: %s", type, family, strerror(errno));
    00257     closesocket(sock);
    00258     return INVALID_SOCKET;
    00259   }
    00260
    00261   /* Connection succeeded */
    00262   if (!SetNonBlocking(sock)) DEBUG(net, 0, "[%s] setting non-blocking mode failed", type);
    00263
    00264   DEBUG(net, 1, "[%s] connected to %s", type, address);
    00265
    00266   return sock;
    00267 }
    00268
    00269 SOCKET NetworkAddress::Connect()
    00270 {
    00271   DEBUG(net, 1, "Connecting to %s", this->GetAddressAsString());
    00272
    00273   return this->Resolve(AF_UNSPEC, SOCK_STREAM, AI_ADDRCONFIG, NULL, ConnectLoopProc);
    00274 }
    00275
    00281 static SOCKET ListenLoopProc(addrinfo *runp)
    00282 {
    00283   const char *type = NetworkAddress::SocketTypeAsString(runp->ai_socktype);
    00284   const char *family = NetworkAddress::AddressFamilyAsString(runp->ai_family);
    00285   const char *address = NetworkAddress(runp->ai_addr, (int)runp->ai_addrlen).GetAddressAsString();
    00286
    00287   SOCKET sock = socket(runp->ai_family, runp->ai_socktype, runp->ai_protocol);
    00288   if (sock == INVALID_SOCKET) {
    00289     DEBUG(net, 0, "[%s] could not create %s socket on port %s: %s", type, family, address, strerror(errno));
    00290     return INVALID_SOCKET;
    00291   }
    00292
    00293   if (runp->ai_socktype == SOCK_STREAM && !SetNoDelay(sock)) {
    00294     DEBUG(net, 3, "[%s] setting TCP_NODELAY failed for port %s", type, address);
    00295   }
    00296
    00297   int on = 1;
    00298   /* The (const char*) cast is needed for windows!! */
    00299   if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on)) == -1) {
    00300     DEBUG(net, 3, "[%s] could not set reusable %s sockets for port %s: %s", type, family, address, strerror(errno));
    00301   }
    00302
    00303   if (runp->ai_family == AF_INET6 &&
    00304       setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&on, sizeof(on)) == -1) {
    00305     DEBUG(net, 3, "[%s] could not disable IPv4 over IPv6 on port %s: %s", type, address, strerror(errno));
    00306   }
    00307
    00308   if (bind(sock, runp->ai_addr, (int)runp->ai_addrlen) != 0) {
    00309     DEBUG(net, 1, "[%s] could not bind on %s port %s: %s", type, family, address, strerror(errno));
    00310     closesocket(sock);
    00311     return INVALID_SOCKET;
    00312   }
    00313
    00314   if (runp->ai_socktype != SOCK_DGRAM && listen(sock, 1) != 0) {
    00315     DEBUG(net, 1, "[%s] could not listen at %s port %s: %s", type, family, address, strerror(errno));
    00316     closesocket(sock);
    00317     return INVALID_SOCKET;
    00318   }
    00319
    00320   /* Connection succeeded */
    00321   if (!SetNonBlocking(sock)) DEBUG(net, 0, "[%s] setting non-blocking mode failed for %s port %s", type, family, address);
    00322
    00323   DEBUG(net, 1, "[%s] listening on %s port %s", type, family, address);
    00324   return sock;
    00325 }
    00326
    00327 void NetworkAddress::Listen(int socktype, SocketList *sockets)
    00328 {
    00329   assert(sockets != NULL);
    00330
    00331   /* Setting both hostname to NULL and port to 0 is not allowed.
    00332    * As port 0 means bind to any port, the other must mean that
    00333    * we want to bind to 'all' IPs. */
    00334   if (this->address_length == 0 && this->address.ss_family == AF_UNSPEC &&
    00335       StrEmpty(this->hostname) && this->GetPort() == 0) {
    00336     this->Resolve(AF_INET,  socktype, AI_ADDRCONFIG | AI_PASSIVE, sockets, ListenLoopProc);
    00337     this->Resolve(AF_INET6, socktype, AI_ADDRCONFIG | AI_PASSIVE, sockets, ListenLoopProc);
    00338   } else {
    00339     this->Resolve(AF_UNSPEC, socktype, AI_ADDRCONFIG | AI_PASSIVE, sockets, ListenLoopProc);
    00340   }
    00341 }
    00342
    00343 /* static */ const char *NetworkAddress::SocketTypeAsString(int socktype)
    00344 {
    00345   switch (socktype) {
    00346     case SOCK_STREAM: return "tcp";
    00347     case SOCK_DGRAM:  return "udp";
    00348     default:          return "unsupported";
    00349   }
    00350 }
    00351
    00352 /* static */ const char *NetworkAddress::AddressFamilyAsString(int family)
    00353 {
    00354   switch (family) {
    00355     case AF_UNSPEC: return "either IPv4 or IPv6";
    00356     case AF_INET:   return "IPv4";
    00357     case AF_INET6:  return "IPv6";
    00358     default:        return "unsupported";
    00359   }
    00360 }
    00361
    00362 #endif /* ENABLE_NETWORK */