Fix: Data races on cursor state in OpenGL backends
[openttd-github.git] / src / network / core / address.cpp
bloba45bd49142c239a8489fd4b6c53604ac39de9ba4
1 /*
2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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/>.
6 */
8 /** @file core/address.cpp Implementation of the address. */
10 #include "../../stdafx.h"
12 #include "address.h"
13 #include "../../debug.h"
15 #include "../../safeguards.h"
17 /**
18 * Get the hostname; in case it wasn't given the
19 * IPv4 dotted representation is given.
20 * @return the hostname
22 const char *NetworkAddress::GetHostname()
24 if (StrEmpty(this->hostname) && this->address.ss_family != AF_UNSPEC) {
25 assert(this->address_length != 0);
26 getnameinfo((struct sockaddr *)&this->address, this->address_length, this->hostname, sizeof(this->hostname), nullptr, 0, NI_NUMERICHOST);
28 return this->hostname;
31 /**
32 * Get the port.
33 * @return the port.
35 uint16 NetworkAddress::GetPort() const
37 switch (this->address.ss_family) {
38 case AF_UNSPEC:
39 case AF_INET:
40 return ntohs(((const struct sockaddr_in *)&this->address)->sin_port);
42 case AF_INET6:
43 return ntohs(((const struct sockaddr_in6 *)&this->address)->sin6_port);
45 default:
46 NOT_REACHED();
50 /**
51 * Set the port.
52 * @param port set the port number.
54 void NetworkAddress::SetPort(uint16 port)
56 switch (this->address.ss_family) {
57 case AF_UNSPEC:
58 case AF_INET:
59 ((struct sockaddr_in*)&this->address)->sin_port = htons(port);
60 break;
62 case AF_INET6:
63 ((struct sockaddr_in6*)&this->address)->sin6_port = htons(port);
64 break;
66 default:
67 NOT_REACHED();
71 /**
72 * Get the address as a string, e.g. 127.0.0.1:12345.
73 * @param buffer the buffer to write to
74 * @param last the last element in the buffer
75 * @param with_family whether to add the family (e.g. IPvX).
77 void NetworkAddress::GetAddressAsString(char *buffer, const char *last, bool with_family)
79 if (this->GetAddress()->ss_family == AF_INET6) buffer = strecpy(buffer, "[", last);
80 buffer = strecpy(buffer, this->GetHostname(), last);
81 if (this->GetAddress()->ss_family == AF_INET6) buffer = strecpy(buffer, "]", last);
82 buffer += seprintf(buffer, last, ":%d", this->GetPort());
84 if (with_family) {
85 char family;
86 switch (this->address.ss_family) {
87 case AF_INET: family = '4'; break;
88 case AF_INET6: family = '6'; break;
89 default: family = '?'; break;
91 seprintf(buffer, last, " (IPv%c)", family);
95 /**
96 * Get the address as a string, e.g. 127.0.0.1:12345.
97 * @param with_family whether to add the family (e.g. IPvX).
98 * @return the address
100 std::string NetworkAddress::GetAddressAsString(bool with_family)
102 /* 6 = for the : and 5 for the decimal port number */
103 char buf[NETWORK_HOSTNAME_LENGTH + 6 + 7];
104 this->GetAddressAsString(buf, lastof(buf), with_family);
105 return buf;
109 * Helper function to resolve without opening a socket.
110 * @param runp information about the socket to try not
111 * @return the opened socket or INVALID_SOCKET
113 static SOCKET ResolveLoopProc(addrinfo *runp)
115 /* We just want the first 'entry', so return a valid socket. */
116 return !INVALID_SOCKET;
120 * Get the address in its internal representation.
121 * @return the address
123 const sockaddr_storage *NetworkAddress::GetAddress()
125 if (!this->IsResolved()) {
126 /* Here we try to resolve a network address. We use SOCK_STREAM as
127 * socket type because some stupid OSes, like Solaris, cannot be
128 * bothered to implement the specifications and allow '0' as value
129 * that means "don't care whether it is SOCK_STREAM or SOCK_DGRAM".
131 this->Resolve(this->address.ss_family, SOCK_STREAM, AI_ADDRCONFIG, nullptr, ResolveLoopProc);
132 this->resolved = true;
134 return &this->address;
138 * Checks of this address is of the given family.
139 * @param family the family to check against
140 * @return true if it is of the given family
142 bool NetworkAddress::IsFamily(int family)
144 if (!this->IsResolved()) {
145 this->Resolve(family, SOCK_STREAM, AI_ADDRCONFIG, nullptr, ResolveLoopProc);
147 return this->address.ss_family == family;
151 * Checks whether this IP address is contained by the given netmask.
152 * @param netmask the netmask in CIDR notation to test against.
153 * @note netmask without /n assumes all bits need to match.
154 * @return true if this IP is within the netmask.
156 bool NetworkAddress::IsInNetmask(const char *netmask)
158 /* Resolve it if we didn't do it already */
159 if (!this->IsResolved()) this->GetAddress();
161 int cidr = this->address.ss_family == AF_INET ? 32 : 128;
163 NetworkAddress mask_address;
165 /* Check for CIDR separator */
166 const char *chr_cidr = strchr(netmask, '/');
167 if (chr_cidr != nullptr) {
168 int tmp_cidr = atoi(chr_cidr + 1);
170 /* Invalid CIDR, treat as single host */
171 if (tmp_cidr > 0 || tmp_cidr < cidr) cidr = tmp_cidr;
173 /* Remove the / so that NetworkAddress works on the IP portion */
174 std::string ip_str(netmask, chr_cidr - netmask);
175 mask_address = NetworkAddress(ip_str.c_str(), 0, this->address.ss_family);
176 } else {
177 mask_address = NetworkAddress(netmask, 0, this->address.ss_family);
180 if (mask_address.GetAddressLength() == 0) return false;
182 uint32 *ip;
183 uint32 *mask;
184 switch (this->address.ss_family) {
185 case AF_INET:
186 ip = (uint32*)&((struct sockaddr_in*)&this->address)->sin_addr.s_addr;
187 mask = (uint32*)&((struct sockaddr_in*)&mask_address.address)->sin_addr.s_addr;
188 break;
190 case AF_INET6:
191 ip = (uint32*)&((struct sockaddr_in6*)&this->address)->sin6_addr;
192 mask = (uint32*)&((struct sockaddr_in6*)&mask_address.address)->sin6_addr;
193 break;
195 default:
196 NOT_REACHED();
199 while (cidr > 0) {
200 uint32 msk = cidr >= 32 ? (uint32)-1 : htonl(-(1 << (32 - cidr)));
201 if ((*mask++ & msk) != (*ip++ & msk)) return false;
203 cidr -= 32;
206 return true;
210 * Resolve this address into a socket
211 * @param family the type of 'protocol' (IPv4, IPv6)
212 * @param socktype the type of socket (TCP, UDP, etc)
213 * @param flags the flags to send to getaddrinfo
214 * @param sockets the list of sockets to add the sockets to
215 * @param func the inner working while looping over the address info
216 * @return the resolved socket or INVALID_SOCKET.
218 SOCKET NetworkAddress::Resolve(int family, int socktype, int flags, SocketList *sockets, LoopProc func)
220 struct addrinfo *ai;
221 struct addrinfo hints;
222 memset(&hints, 0, sizeof (hints));
223 hints.ai_family = family;
224 hints.ai_flags = flags;
225 hints.ai_socktype = socktype;
227 /* The port needs to be a string. Six is enough to contain all characters + '\0'. */
228 char port_name[6];
229 seprintf(port_name, lastof(port_name), "%u", this->GetPort());
231 bool reset_hostname = false;
232 /* Setting both hostname to nullptr and port to 0 is not allowed.
233 * As port 0 means bind to any port, the other must mean that
234 * we want to bind to 'all' IPs. */
235 if (StrEmpty(this->hostname) && this->address_length == 0 && this->GetPort() == 0) {
236 reset_hostname = true;
237 int fam = this->address.ss_family;
238 if (fam == AF_UNSPEC) fam = family;
239 strecpy(this->hostname, fam == AF_INET ? "0.0.0.0" : "::", lastof(this->hostname));
242 int e = getaddrinfo(StrEmpty(this->hostname) ? nullptr : this->hostname, port_name, &hints, &ai);
244 if (reset_hostname) strecpy(this->hostname, "", lastof(this->hostname));
246 if (e != 0) {
247 if (func != ResolveLoopProc) {
248 DEBUG(net, 0, "getaddrinfo for hostname \"%s\", port %s, address family %s and socket type %s failed: %s",
249 this->hostname, port_name, AddressFamilyAsString(family), SocketTypeAsString(socktype), FS2OTTD(gai_strerror(e)).c_str());
251 return INVALID_SOCKET;
254 SOCKET sock = INVALID_SOCKET;
255 for (struct addrinfo *runp = ai; runp != nullptr; runp = runp->ai_next) {
256 /* When we are binding to multiple sockets, make sure we do not
257 * connect to one with exactly the same address twice. That's
258 * of course totally unneeded ;) */
259 if (sockets != nullptr) {
260 NetworkAddress address(runp->ai_addr, (int)runp->ai_addrlen);
261 if (sockets->Contains(address)) continue;
263 sock = func(runp);
264 if (sock == INVALID_SOCKET) continue;
266 if (sockets == nullptr) {
267 this->address_length = (int)runp->ai_addrlen;
268 assert(sizeof(this->address) >= runp->ai_addrlen);
269 memcpy(&this->address, runp->ai_addr, runp->ai_addrlen);
270 #ifdef __EMSCRIPTEN__
271 /* Emscripten doesn't zero sin_zero, but as we compare addresses
272 * to see if they are the same address, we need them to be zero'd.
273 * Emscripten is, as far as we know, the only OS not doing this.
275 * https://github.com/emscripten-core/emscripten/issues/12998
277 if (this->address.ss_family == AF_INET) {
278 sockaddr_in *address_ipv4 = (sockaddr_in *)&this->address;
279 memset(address_ipv4->sin_zero, 0, sizeof(address_ipv4->sin_zero));
281 #endif
282 break;
285 NetworkAddress addr(runp->ai_addr, (int)runp->ai_addrlen);
286 (*sockets)[addr] = sock;
287 sock = INVALID_SOCKET;
289 freeaddrinfo (ai);
291 return sock;
295 * Helper function to resolve a connected socket.
296 * @param runp information about the socket to try not
297 * @return the opened socket or INVALID_SOCKET
299 static SOCKET ConnectLoopProc(addrinfo *runp)
301 const char *type = NetworkAddress::SocketTypeAsString(runp->ai_socktype);
302 const char *family = NetworkAddress::AddressFamilyAsString(runp->ai_family);
303 char address[NETWORK_HOSTNAME_LENGTH + 6 + 7];
304 NetworkAddress(runp->ai_addr, (int)runp->ai_addrlen).GetAddressAsString(address, lastof(address));
306 SOCKET sock = socket(runp->ai_family, runp->ai_socktype, runp->ai_protocol);
307 if (sock == INVALID_SOCKET) {
308 DEBUG(net, 1, "[%s] could not create %s socket: %s", type, family, strerror(errno));
309 return INVALID_SOCKET;
312 if (!SetNoDelay(sock)) DEBUG(net, 1, "[%s] setting TCP_NODELAY failed", type);
314 int err = connect(sock, runp->ai_addr, (int)runp->ai_addrlen);
315 #ifdef __EMSCRIPTEN__
316 /* Emscripten is asynchronous, and as such a connect() is still in
317 * progress by the time the call returns. */
318 if (err != 0 && errno != EINPROGRESS)
319 #else
320 if (err != 0)
321 #endif
323 DEBUG(net, 1, "[%s] could not connect %s socket: %s", type, family, strerror(errno));
324 closesocket(sock);
325 return INVALID_SOCKET;
328 /* Connection succeeded */
329 if (!SetNonBlocking(sock)) DEBUG(net, 0, "[%s] setting non-blocking mode failed", type);
331 DEBUG(net, 1, "[%s] connected to %s", type, address);
333 return sock;
337 * Connect to the given address.
338 * @return the connected socket or INVALID_SOCKET.
340 SOCKET NetworkAddress::Connect()
342 DEBUG(net, 1, "Connecting to %s", this->GetAddressAsString().c_str());
344 return this->Resolve(AF_UNSPEC, SOCK_STREAM, AI_ADDRCONFIG, nullptr, ConnectLoopProc);
348 * Helper function to resolve a listening.
349 * @param runp information about the socket to try not
350 * @return the opened socket or INVALID_SOCKET
352 static SOCKET ListenLoopProc(addrinfo *runp)
354 const char *type = NetworkAddress::SocketTypeAsString(runp->ai_socktype);
355 const char *family = NetworkAddress::AddressFamilyAsString(runp->ai_family);
356 char address[NETWORK_HOSTNAME_LENGTH + 6 + 7];
357 NetworkAddress(runp->ai_addr, (int)runp->ai_addrlen).GetAddressAsString(address, lastof(address));
359 SOCKET sock = socket(runp->ai_family, runp->ai_socktype, runp->ai_protocol);
360 if (sock == INVALID_SOCKET) {
361 DEBUG(net, 0, "[%s] could not create %s socket on port %s: %s", type, family, address, strerror(errno));
362 return INVALID_SOCKET;
365 if (runp->ai_socktype == SOCK_STREAM && !SetNoDelay(sock)) {
366 DEBUG(net, 3, "[%s] setting TCP_NODELAY failed for port %s", type, address);
369 int on = 1;
370 /* The (const char*) cast is needed for windows!! */
371 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on)) == -1) {
372 DEBUG(net, 3, "[%s] could not set reusable %s sockets for port %s: %s", type, family, address, strerror(errno));
375 #ifndef __OS2__
376 if (runp->ai_family == AF_INET6 &&
377 setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&on, sizeof(on)) == -1) {
378 DEBUG(net, 3, "[%s] could not disable IPv4 over IPv6 on port %s: %s", type, address, strerror(errno));
380 #endif
382 if (bind(sock, runp->ai_addr, (int)runp->ai_addrlen) != 0) {
383 DEBUG(net, 1, "[%s] could not bind on %s port %s: %s", type, family, address, strerror(errno));
384 closesocket(sock);
385 return INVALID_SOCKET;
388 if (runp->ai_socktype != SOCK_DGRAM && listen(sock, 1) != 0) {
389 DEBUG(net, 1, "[%s] could not listen at %s port %s: %s", type, family, address, strerror(errno));
390 closesocket(sock);
391 return INVALID_SOCKET;
394 /* Connection succeeded */
395 if (!SetNonBlocking(sock)) DEBUG(net, 0, "[%s] setting non-blocking mode failed for %s port %s", type, family, address);
397 DEBUG(net, 1, "[%s] listening on %s port %s", type, family, address);
398 return sock;
402 * Make the given socket listen.
403 * @param socktype the type of socket (TCP, UDP, etc)
404 * @param sockets the list of sockets to add the sockets to
406 void NetworkAddress::Listen(int socktype, SocketList *sockets)
408 assert(sockets != nullptr);
410 /* Setting both hostname to nullptr and port to 0 is not allowed.
411 * As port 0 means bind to any port, the other must mean that
412 * we want to bind to 'all' IPs. */
413 if (this->address_length == 0 && this->address.ss_family == AF_UNSPEC &&
414 StrEmpty(this->hostname) && this->GetPort() == 0) {
415 this->Resolve(AF_INET, socktype, AI_ADDRCONFIG | AI_PASSIVE, sockets, ListenLoopProc);
416 this->Resolve(AF_INET6, socktype, AI_ADDRCONFIG | AI_PASSIVE, sockets, ListenLoopProc);
417 } else {
418 this->Resolve(AF_UNSPEC, socktype, AI_ADDRCONFIG | AI_PASSIVE, sockets, ListenLoopProc);
423 * Convert the socket type into a string
424 * @param socktype the socket type to convert
425 * @return the string representation
426 * @note only works for SOCK_STREAM and SOCK_DGRAM
428 /* static */ const char *NetworkAddress::SocketTypeAsString(int socktype)
430 switch (socktype) {
431 case SOCK_STREAM: return "tcp";
432 case SOCK_DGRAM: return "udp";
433 default: return "unsupported";
438 * Convert the address family into a string
439 * @param family the family to convert
440 * @return the string representation
441 * @note only works for AF_INET, AF_INET6 and AF_UNSPEC
443 /* static */ const char *NetworkAddress::AddressFamilyAsString(int family)
445 switch (family) {
446 case AF_UNSPEC: return "either IPv4 or IPv6";
447 case AF_INET: return "IPv4";
448 case AF_INET6: return "IPv6";
449 default: return "unsupported";