address.cpp

Go to the documentation of this file.
00001 /* $Id$ */
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 
00024 const char *NetworkAddress::GetHostname()
00025 {
00026   if (StrEmpty(this->hostname) && this->address.ss_family != AF_UNSPEC) {
00027     assert(this->address_length != 0);
00028     getnameinfo((struct sockaddr *)&this->address, this->address_length, this->hostname, sizeof(this->hostname), NULL, 0, NI_NUMERICHOST);
00029   }
00030   return this->hostname;
00031 }
00032 
00037 uint16 NetworkAddress::GetPort() const
00038 {
00039   switch (this->address.ss_family) {
00040     case AF_UNSPEC:
00041     case AF_INET:
00042       return ntohs(((struct sockaddr_in *)&this->address)->sin_port);
00043 
00044     case AF_INET6:
00045       return ntohs(((struct sockaddr_in6 *)&this->address)->sin6_port);
00046 
00047     default:
00048       NOT_REACHED();
00049   }
00050 }
00051 
00056 void NetworkAddress::SetPort(uint16 port)
00057 {
00058   switch (this->address.ss_family) {
00059     case AF_UNSPEC:
00060     case AF_INET:
00061       ((struct sockaddr_in*)&this->address)->sin_port = htons(port);
00062       break;
00063 
00064     case AF_INET6:
00065       ((struct sockaddr_in6*)&this->address)->sin6_port = htons(port);
00066       break;
00067 
00068     default:
00069       NOT_REACHED();
00070   }
00071 }
00072 
00079 void NetworkAddress::GetAddressAsString(char *buffer, const char *last, bool with_family)
00080 {
00081   if (this->GetAddress()->ss_family == AF_INET6) buffer = strecpy(buffer, "[", last);
00082   buffer = strecpy(buffer, this->GetHostname(), last);
00083   if (this->GetAddress()->ss_family == AF_INET6) buffer = strecpy(buffer, "]", last);
00084   buffer += seprintf(buffer, last, ":%d", this->GetPort());
00085 
00086   if (with_family) {
00087     char family;
00088     switch (this->address.ss_family) {
00089       case AF_INET:  family = '4'; break;
00090       case AF_INET6: family = '6'; break;
00091       default:       family = '?'; break;
00092     }
00093     seprintf(buffer, last, " (IPv%c)", family);
00094   }
00095 }
00096 
00103 const char *NetworkAddress::GetAddressAsString(bool with_family)
00104 {
00105   /* 6 = for the : and 5 for the decimal port number */
00106   static char buf[NETWORK_HOSTNAME_LENGTH + 6 + 7];
00107   this->GetAddressAsString(buf, lastof(buf), with_family);
00108   return buf;
00109 }
00110 
00116 static SOCKET ResolveLoopProc(addrinfo *runp)
00117 {
00118   /* We just want the first 'entry', so return a valid socket. */
00119   return !INVALID_SOCKET;
00120 }
00121 
00126 const sockaddr_storage *NetworkAddress::GetAddress()
00127 {
00128   if (!this->IsResolved()) {
00129     /* Here we try to resolve a network address. We use SOCK_STREAM as
00130      * socket type because some stupid OSes, like Solaris, cannot be
00131      * bothered to implement the specifications and allow '0' as value
00132      * that means "don't care whether it is SOCK_STREAM or SOCK_DGRAM".
00133      */
00134     this->Resolve(this->address.ss_family, SOCK_STREAM, AI_ADDRCONFIG, NULL, ResolveLoopProc);
00135   }
00136   return &this->address;
00137 }
00138 
00144 bool NetworkAddress::IsFamily(int family)
00145 {
00146   if (!this->IsResolved()) {
00147     this->Resolve(family, SOCK_STREAM, AI_ADDRCONFIG, NULL, ResolveLoopProc);
00148   }
00149   return this->address.ss_family == family;
00150 }
00151 
00158 bool NetworkAddress::IsInNetmask(char *netmask)
00159 {
00160   /* Resolve it if we didn't do it already */
00161   if (!this->IsResolved()) this->GetAddress();
00162 
00163   int cidr = this->address.ss_family == AF_INET ? 32 : 128;
00164 
00165   NetworkAddress mask_address;
00166 
00167   /* Check for CIDR separator */
00168   char *chr_cidr = strchr(netmask, '/');
00169   if (chr_cidr != NULL) {
00170     int tmp_cidr = atoi(chr_cidr + 1);
00171 
00172     /* Invalid CIDR, treat as single host */
00173     if (tmp_cidr > 0 || tmp_cidr < cidr) cidr = tmp_cidr;
00174 
00175     /* Remove and then replace the / so that NetworkAddress works on the IP portion */
00176     *chr_cidr = '\0';
00177     mask_address = NetworkAddress(netmask, 0, this->address.ss_family);
00178     *chr_cidr = '/';
00179   } else {
00180     mask_address = NetworkAddress(netmask, 0, this->address.ss_family);
00181   }
00182 
00183   if (mask_address.GetAddressLength() == 0) return false;
00184 
00185   uint32 *ip;
00186   uint32 *mask;
00187   switch (this->address.ss_family) {
00188     case AF_INET:
00189       ip = (uint32*)&((struct sockaddr_in*)&this->address)->sin_addr.s_addr;
00190       mask = (uint32*)&((struct sockaddr_in*)&mask_address.address)->sin_addr.s_addr;
00191       break;
00192 
00193     case AF_INET6:
00194       ip = (uint32*)&((struct sockaddr_in6*)&this->address)->sin6_addr;
00195       mask = (uint32*)&((struct sockaddr_in6*)&mask_address.address)->sin6_addr;
00196       break;
00197 
00198     default:
00199       NOT_REACHED();
00200   }
00201 
00202   while (cidr > 0) {
00203     uint32 msk = cidr >= 32 ? (uint32)-1 : htonl(-(1 << (32 - cidr)));
00204     if ((*mask++ & msk) != (*ip++ & msk)) return false;
00205 
00206     cidr -= 32;
00207   }
00208 
00209   return true;
00210 }
00211 
00221 SOCKET NetworkAddress::Resolve(int family, int socktype, int flags, SocketList *sockets, LoopProc func)
00222 {
00223   struct addrinfo *ai;
00224   struct addrinfo hints;
00225   memset(&hints, 0, sizeof (hints));
00226   hints.ai_family   = family;
00227   hints.ai_flags    = flags;
00228   hints.ai_socktype = socktype;
00229 
00230   /* The port needs to be a string. Six is enough to contain all characters + '\0'. */
00231   char port_name[6];
00232   seprintf(port_name, lastof(port_name), "%u", this->GetPort());
00233 
00234   bool reset_hostname = false;
00235   /* Setting both hostname to NULL and port to 0 is not allowed.
00236    * As port 0 means bind to any port, the other must mean that
00237    * we want to bind to 'all' IPs. */
00238   if (StrEmpty(this->hostname) && this->address_length == 0 && this->GetPort() == 0) {
00239     reset_hostname = true;
00240     int fam = this->address.ss_family;
00241     if (fam == AF_UNSPEC) fam = family;
00242     strecpy(this->hostname, fam == AF_INET ? "0.0.0.0" : "::", lastof(this->hostname));
00243   }
00244 
00245   int e = getaddrinfo(StrEmpty(this->hostname) ? NULL : this->hostname, port_name, &hints, &ai);
00246 
00247   if (reset_hostname) strecpy(this->hostname, "", lastof(this->hostname));
00248 
00249   if (e != 0) {
00250     if (func != ResolveLoopProc) {
00251       DEBUG(net, 0, "getaddrinfo for hostname \"%s\", port %s, address family %s and socket type %s failed: %s",
00252         this->hostname, port_name, AddressFamilyAsString(family), SocketTypeAsString(socktype), FS2OTTD(gai_strerror(e)));
00253     }
00254     return INVALID_SOCKET;
00255   }
00256 
00257   SOCKET sock = INVALID_SOCKET;
00258   for (struct addrinfo *runp = ai; runp != NULL; runp = runp->ai_next) {
00259     /* When we are binding to multiple sockets, make sure we do not
00260      * connect to one with exactly the same address twice. That's
00261      * ofcourse totally unneeded ;) */
00262     if (sockets != NULL) {
00263       NetworkAddress address(runp->ai_addr, (int)runp->ai_addrlen);
00264       if (sockets->Contains(address)) continue;
00265     }
00266     sock = func(runp);
00267     if (sock == INVALID_SOCKET) continue;
00268 
00269     if (sockets == NULL) {
00270       this->address_length = (int)runp->ai_addrlen;
00271       assert(sizeof(this->address) >= runp->ai_addrlen);
00272       memcpy(&this->address, runp->ai_addr, runp->ai_addrlen);
00273       break;
00274     }
00275 
00276     NetworkAddress addr(runp->ai_addr, (int)runp->ai_addrlen);
00277     (*sockets)[addr] = sock;
00278     sock = INVALID_SOCKET;
00279   }
00280   freeaddrinfo (ai);
00281 
00282   return sock;
00283 }
00284 
00290 static SOCKET ConnectLoopProc(addrinfo *runp)
00291 {
00292   const char *type = NetworkAddress::SocketTypeAsString(runp->ai_socktype);
00293   const char *family = NetworkAddress::AddressFamilyAsString(runp->ai_family);
00294   const char *address = NetworkAddress(runp->ai_addr, (int)runp->ai_addrlen).GetAddressAsString();
00295 
00296   SOCKET sock = socket(runp->ai_family, runp->ai_socktype, runp->ai_protocol);
00297   if (sock == INVALID_SOCKET) {
00298     DEBUG(net, 1, "[%s] could not create %s socket: %s", type, family, strerror(errno));
00299     return INVALID_SOCKET;
00300   }
00301 
00302   if (!SetNoDelay(sock)) DEBUG(net, 1, "[%s] setting TCP_NODELAY failed", type);
00303 
00304   if (connect(sock, runp->ai_addr, (int)runp->ai_addrlen) != 0) {
00305     DEBUG(net, 1, "[%s] could not connect %s socket: %s", type, family, strerror(errno));
00306     closesocket(sock);
00307     return INVALID_SOCKET;
00308   }
00309 
00310   /* Connection succeeded */
00311   if (!SetNonBlocking(sock)) DEBUG(net, 0, "[%s] setting non-blocking mode failed", type);
00312 
00313   DEBUG(net, 1, "[%s] connected to %s", type, address);
00314 
00315   return sock;
00316 }
00317 
00322 SOCKET NetworkAddress::Connect()
00323 {
00324   DEBUG(net, 1, "Connecting to %s", this->GetAddressAsString());
00325 
00326   return this->Resolve(AF_UNSPEC, SOCK_STREAM, AI_ADDRCONFIG, NULL, ConnectLoopProc);
00327 }
00328 
00334 static SOCKET ListenLoopProc(addrinfo *runp)
00335 {
00336   const char *type = NetworkAddress::SocketTypeAsString(runp->ai_socktype);
00337   const char *family = NetworkAddress::AddressFamilyAsString(runp->ai_family);
00338   const char *address = NetworkAddress(runp->ai_addr, (int)runp->ai_addrlen).GetAddressAsString();
00339 
00340   SOCKET sock = socket(runp->ai_family, runp->ai_socktype, runp->ai_protocol);
00341   if (sock == INVALID_SOCKET) {
00342     DEBUG(net, 0, "[%s] could not create %s socket on port %s: %s", type, family, address, strerror(errno));
00343     return INVALID_SOCKET;
00344   }
00345 
00346   if (runp->ai_socktype == SOCK_STREAM && !SetNoDelay(sock)) {
00347     DEBUG(net, 3, "[%s] setting TCP_NODELAY failed for port %s", type, address);
00348   }
00349 
00350   int on = 1;
00351   /* The (const char*) cast is needed for windows!! */
00352   if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on)) == -1) {
00353     DEBUG(net, 3, "[%s] could not set reusable %s sockets for port %s: %s", type, family, address, strerror(errno));
00354   }
00355 
00356   if (runp->ai_family == AF_INET6 &&
00357       setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&on, sizeof(on)) == -1) {
00358     DEBUG(net, 3, "[%s] could not disable IPv4 over IPv6 on port %s: %s", type, address, strerror(errno));
00359   }
00360 
00361   if (bind(sock, runp->ai_addr, (int)runp->ai_addrlen) != 0) {
00362     DEBUG(net, 1, "[%s] could not bind on %s port %s: %s", type, family, address, strerror(errno));
00363     closesocket(sock);
00364     return INVALID_SOCKET;
00365   }
00366 
00367   if (runp->ai_socktype != SOCK_DGRAM && listen(sock, 1) != 0) {
00368     DEBUG(net, 1, "[%s] could not listen at %s port %s: %s", type, family, address, strerror(errno));
00369     closesocket(sock);
00370     return INVALID_SOCKET;
00371   }
00372 
00373   /* Connection succeeded */
00374   if (!SetNonBlocking(sock)) DEBUG(net, 0, "[%s] setting non-blocking mode failed for %s port %s", type, family, address);
00375 
00376   DEBUG(net, 1, "[%s] listening on %s port %s", type, family, address);
00377   return sock;
00378 }
00379 
00385 void NetworkAddress::Listen(int socktype, SocketList *sockets)
00386 {
00387   assert(sockets != NULL);
00388 
00389   /* Setting both hostname to NULL and port to 0 is not allowed.
00390    * As port 0 means bind to any port, the other must mean that
00391    * we want to bind to 'all' IPs. */
00392   if (this->address_length == 0 && this->address.ss_family == AF_UNSPEC &&
00393       StrEmpty(this->hostname) && this->GetPort() == 0) {
00394     this->Resolve(AF_INET,  socktype, AI_ADDRCONFIG | AI_PASSIVE, sockets, ListenLoopProc);
00395     this->Resolve(AF_INET6, socktype, AI_ADDRCONFIG | AI_PASSIVE, sockets, ListenLoopProc);
00396   } else {
00397     this->Resolve(AF_UNSPEC, socktype, AI_ADDRCONFIG | AI_PASSIVE, sockets, ListenLoopProc);
00398   }
00399 }
00400 
00407 /* static */ const char *NetworkAddress::SocketTypeAsString(int socktype)
00408 {
00409   switch (socktype) {
00410     case SOCK_STREAM: return "tcp";
00411     case SOCK_DGRAM:  return "udp";
00412     default:          return "unsupported";
00413   }
00414 }
00415 
00422 /* static */ const char *NetworkAddress::AddressFamilyAsString(int family)
00423 {
00424   switch (family) {
00425     case AF_UNSPEC: return "either IPv4 or IPv6";
00426     case AF_INET:   return "IPv4";
00427     case AF_INET6:  return "IPv6";
00428     default:        return "unsupported";
00429   }
00430 }
00431 
00432 #endif /* ENABLE_NETWORK */

Generated on Wed Apr 13 00:47:49 2011 for OpenTTD by  doxygen 1.6.1