Maintain a circular buffer of recent commands, add to crashlog.
[openttd-joker.git] / src / network / core / address.cpp
blob99ca7694cb39d2e927cd185d7fef435354243421
1 /* $Id: address.cpp 24900 2013-01-08 22:46:42Z planetmaker $ */
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 */
10 /** @file core/address.cpp Implementation of the address. */
12 #include "../../stdafx.h"
14 #ifdef ENABLE_NETWORK
16 #include "address.h"
17 #include "../../debug.h"
19 #include "../../safeguards.h"
21 /**
22 * Get the hostname; in case it wasn't given the
23 * IPv4 dotted representation is given.
24 * @return the hostname
26 const char *NetworkAddress::GetHostname()
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);
32 return this->hostname;
35 /**
36 * Get the port.
37 * @return the port.
39 uint16 NetworkAddress::GetPort() const
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);
46 case AF_INET6:
47 return ntohs(((const struct sockaddr_in6 *)&this->address)->sin6_port);
49 default:
50 NOT_REACHED();
54 /**
55 * Set the port.
56 * @param port set the port number.
58 void NetworkAddress::SetPort(uint16 port)
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;
66 case AF_INET6:
67 ((struct sockaddr_in6*)&this->address)->sin6_port = htons(port);
68 break;
70 default:
71 NOT_REACHED();
75 /**
76 * Get the address as a string, e.g. 127.0.0.1:12345.
77 * @param buffer the buffer to write to
78 * @param last the last element in the buffer
79 * @param with_family whether to add the family (e.g. IPvX).
81 void NetworkAddress::GetAddressAsString(char *buffer, const char *last, bool with_family)
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());
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;
95 seprintf(buffer, last, " (IPv%c)", family);
99 /**
100 * Get the address as a string, e.g. 127.0.0.1:12345.
101 * @param with_family whether to add the family (e.g. IPvX).
102 * @return the address
103 * @note NOT thread safe
105 const char *NetworkAddress::GetAddressAsString(bool with_family)
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;
114 * Helper function to resolve without opening a socket.
115 * @param runp information about the socket to try not
116 * @return the opened socket or INVALID_SOCKET
118 static SOCKET ResolveLoopProc(addrinfo *runp)
120 /* We just want the first 'entry', so return a valid socket. */
121 return !INVALID_SOCKET;
125 * Get the address in its internal representation.
126 * @return the address
128 const sockaddr_storage *NetworkAddress::GetAddress()
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".
136 this->Resolve(this->address.ss_family, SOCK_STREAM, AI_ADDRCONFIG, NULL, ResolveLoopProc);
137 this->resolved = true;
139 return &this->address;
143 * Checks of this address is of the given family.
144 * @param family the family to check against
145 * @return true if it is of the given family
147 bool NetworkAddress::IsFamily(int family)
149 if (!this->IsResolved()) {
150 this->Resolve(family, SOCK_STREAM, AI_ADDRCONFIG, NULL, ResolveLoopProc);
152 return this->address.ss_family == family;
156 * Checks whether this IP address is contained by the given netmask.
157 * @param netmask the netmask in CIDR notation to test against.
158 * @note netmask without /n assumes all bits need to match.
159 * @return true if this IP is within the netmask.
161 bool NetworkAddress::IsInNetmask(char *netmask)
163 /* Resolve it if we didn't do it already */
164 if (!this->IsResolved()) this->GetAddress();
166 int cidr = this->address.ss_family == AF_INET ? 32 : 128;
168 NetworkAddress mask_address;
170 /* Check for CIDR separator */
171 char *chr_cidr = strchr(netmask, '/');
172 if (chr_cidr != NULL) {
173 int tmp_cidr = atoi(chr_cidr + 1);
175 /* Invalid CIDR, treat as single host */
176 if (tmp_cidr > 0 || tmp_cidr < cidr) cidr = tmp_cidr;
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);
186 if (mask_address.GetAddressLength() == 0) return false;
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;
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;
201 default:
202 NOT_REACHED();
205 while (cidr > 0) {
206 uint32 msk = cidr >= 32 ? (uint32)-1 : htonl(-(1 << (32 - cidr)));
207 if ((*mask++ & msk) != (*ip++ & msk)) return false;
209 cidr -= 32;
212 return true;
216 * Resolve this address into a socket
217 * @param family the type of 'protocol' (IPv4, IPv6)
218 * @param socktype the type of socket (TCP, UDP, etc)
219 * @param flags the flags to send to getaddrinfo
220 * @param sockets the list of sockets to add the sockets to
221 * @param func the inner working while looping over the address info
222 * @return the resolved socket or INVALID_SOCKET.
224 SOCKET NetworkAddress::Resolve(int family, int socktype, int flags, SocketList *sockets, LoopProc func)
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;
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());
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));
248 int e = getaddrinfo(StrEmpty(this->hostname) ? NULL : this->hostname, port_name, &hints, &ai);
250 if (reset_hostname) strecpy(this->hostname, "", lastof(this->hostname));
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)));
257 return INVALID_SOCKET;
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;
269 sock = func(runp);
270 if (sock == INVALID_SOCKET) continue;
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;
279 NetworkAddress addr(runp->ai_addr, (int)runp->ai_addrlen);
280 (*sockets)[addr] = sock;
281 sock = INVALID_SOCKET;
283 freeaddrinfo (ai);
285 return sock;
289 * Helper function to resolve a connected socket.
290 * @param runp information about the socket to try not
291 * @return the opened socket or INVALID_SOCKET
293 static SOCKET ConnectLoopProc(addrinfo *runp)
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();
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;
305 if (!SetNoDelay(sock)) DEBUG(net, 1, "[%s] setting TCP_NODELAY failed", type);
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;
313 /* Connection succeeded */
314 if (!SetNonBlocking(sock)) DEBUG(net, 0, "[%s] setting non-blocking mode failed", type);
316 DEBUG(net, 1, "[%s] connected to %s", type, address);
318 return sock;
322 * Connect to the given address.
323 * @return the connected socket or INVALID_SOCKET.
325 SOCKET NetworkAddress::Connect()
327 DEBUG(net, 1, "Connecting to %s", this->GetAddressAsString());
329 return this->Resolve(AF_UNSPEC, SOCK_STREAM, AI_ADDRCONFIG, NULL, ConnectLoopProc);
333 * Helper function to resolve a listening.
334 * @param runp information about the socket to try not
335 * @return the opened socket or INVALID_SOCKET
337 static SOCKET ListenLoopProc(addrinfo *runp)
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();
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;
349 if (runp->ai_socktype == SOCK_STREAM && !SetNoDelay(sock)) {
350 DEBUG(net, 3, "[%s] setting TCP_NODELAY failed for port %s", type, address);
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));
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));
364 #endif
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;
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;
378 /* Connection succeeded */
379 if (!SetNonBlocking(sock)) DEBUG(net, 0, "[%s] setting non-blocking mode failed for %s port %s", type, family, address);
381 DEBUG(net, 1, "[%s] listening on %s port %s", type, family, address);
382 return sock;
386 * Make the given socket listen.
387 * @param socktype the type of socket (TCP, UDP, etc)
388 * @param sockets the list of sockets to add the sockets to
390 void NetworkAddress::Listen(int socktype, SocketList *sockets)
392 assert(sockets != NULL);
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);
407 * Convert the socket type into a string
408 * @param socktype the socket type to convert
409 * @return the string representation
410 * @note only works for SOCK_STREAM and SOCK_DGRAM
412 /* static */ const char *NetworkAddress::SocketTypeAsString(int socktype)
414 switch (socktype) {
415 case SOCK_STREAM: return "tcp";
416 case SOCK_DGRAM: return "udp";
417 default: return "unsupported";
422 * Convert the address family into a string
423 * @param family the family to convert
424 * @return the string representation
425 * @note only works for AF_INET, AF_INET6 and AF_UNSPEC
427 /* static */ const char *NetworkAddress::AddressFamilyAsString(int family)
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";
437 #endif /* ENABLE_NETWORK */