OpenTTD: src/network/core/address.cpp Source File

OpenTTD

- Main Page
- Related Pages
- Modules
- Namespaces
- Data Structures
- Files

- File List
- Globals

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
26 const char *NetworkAddress::GetHostname()
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
39 uint16 NetworkAddress::GetPort() const
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
325 SOCKET NetworkAddress::Connect()
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 */