3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
29 #include "util/string.h"
30 #include "util/numeric.h"
31 #include "constants.h"
37 // Without this some of the network functions are not found on mingw
39 #define _WIN32_WINNT 0x0501
44 #define LAST_SOCKET_ERR() WSAGetLastError()
45 typedef SOCKET socket_t;
46 typedef int socklen_t;
48 #include <sys/types.h>
49 #include <sys/socket.h>
50 #include <netinet/in.h>
54 #include <arpa/inet.h>
55 #define LAST_SOCKET_ERR() (errno)
59 // Set to true to enable verbose debug output
60 bool socket_enable_debug_output = false; // yuck
62 static bool g_sockets_initialized = false;
68 // Windows needs sockets to be initialized before use
70 if(WSAStartup( MAKEWORD(2,2), &WsaData ) != NO_ERROR)
71 throw SocketException("WSAStartup failed");
73 g_sockets_initialized = true;
76 void sockets_cleanup()
79 // On Windows, cleanup sockets after use
90 memset(&m_address, 0, sizeof(m_address));
93 Address::Address(u32 address, u16 port)
95 memset(&m_address, 0, sizeof(m_address));
100 Address::Address(u8 a, u8 b, u8 c, u8 d, u16 port)
102 memset(&m_address, 0, sizeof(m_address));
103 setAddress(a, b, c, d);
107 Address::Address(const IPv6AddressBytes *ipv6_bytes, u16 port)
109 memset(&m_address, 0, sizeof(m_address));
110 setAddress(ipv6_bytes);
114 // Equality (address family, address and port must be equal)
115 bool Address::operator==(const Address &address)
117 if (address.m_addr_family != m_addr_family || address.m_port != m_port)
120 if (m_addr_family == AF_INET) {
121 return m_address.ipv4.sin_addr.s_addr ==
122 address.m_address.ipv4.sin_addr.s_addr;
125 if (m_addr_family == AF_INET6) {
126 return memcmp(m_address.ipv6.sin6_addr.s6_addr,
127 address.m_address.ipv6.sin6_addr.s6_addr, 16) == 0;
133 bool Address::operator!=(const Address &address)
135 return !(*this == address);
138 void Address::Resolve(const char *name)
140 if (!name || name[0] == 0) {
141 if (m_addr_family == AF_INET) {
143 } else if (m_addr_family == AF_INET6) {
144 setAddress((IPv6AddressBytes*) 0);
149 struct addrinfo *resolved, hints;
150 memset(&hints, 0, sizeof(hints));
153 hints.ai_socktype = 0;
154 hints.ai_protocol = 0;
156 if(g_settings->getBool("enable_ipv6"))
158 // AF_UNSPEC allows both IPv6 and IPv4 addresses to be returned
159 hints.ai_family = AF_UNSPEC;
163 hints.ai_family = AF_INET;
167 int e = getaddrinfo(name, NULL, &hints, &resolved);
169 throw ResolveError(gai_strerror(e));
172 if(resolved->ai_family == AF_INET)
174 struct sockaddr_in *t = (struct sockaddr_in *) resolved->ai_addr;
175 m_addr_family = AF_INET;
178 else if(resolved->ai_family == AF_INET6)
180 struct sockaddr_in6 *t = (struct sockaddr_in6 *) resolved->ai_addr;
181 m_addr_family = AF_INET6;
186 freeaddrinfo(resolved);
187 throw ResolveError("");
189 freeaddrinfo(resolved);
192 // IP address -> textual representation
193 std::string Address::serializeString() const
195 // windows XP doesnt have inet_ntop, maybe use better func
197 if(m_addr_family == AF_INET)
201 addr = ntohl(m_address.ipv4.sin_addr.s_addr);
202 a = (addr & 0xFF000000) >> 24;
203 b = (addr & 0x00FF0000) >> 16;
204 c = (addr & 0x0000FF00) >> 8;
205 d = (addr & 0x000000FF);
206 return itos(a) + "." + itos(b) + "." + itos(c) + "." + itos(d);
208 else if(m_addr_family == AF_INET6)
210 std::ostringstream os;
211 for(int i = 0; i < 16; i += 2)
214 (m_address.ipv6.sin6_addr.s6_addr[i] << 8) |
215 (m_address.ipv6.sin6_addr.s6_addr[i + 1]);
216 os << std::hex << section;
223 return std::string("");
225 char str[INET6_ADDRSTRLEN];
226 if (inet_ntop(m_addr_family, (m_addr_family == AF_INET) ? (void*)&(m_address.ipv4.sin_addr) : (void*)&(m_address.ipv6.sin6_addr), str, INET6_ADDRSTRLEN) == NULL) {
227 return std::string("");
229 return std::string(str);
233 struct sockaddr_in Address::getAddress() const
235 return m_address.ipv4; // NOTE: NO PORT INCLUDED, use getPort()
238 struct sockaddr_in6 Address::getAddress6() const
240 return m_address.ipv6; // NOTE: NO PORT INCLUDED, use getPort()
243 u16 Address::getPort() const
248 int Address::getFamily() const
250 return m_addr_family;
253 bool Address::isIPv6() const
255 return m_addr_family == AF_INET6;
258 bool Address::isZero() const
260 if (m_addr_family == AF_INET) {
261 return m_address.ipv4.sin_addr.s_addr == 0;
264 if (m_addr_family == AF_INET6) {
265 static const char zero[16] = {0};
266 return memcmp(m_address.ipv6.sin6_addr.s6_addr,
272 void Address::setAddress(u32 address)
274 m_addr_family = AF_INET;
275 m_address.ipv4.sin_family = AF_INET;
276 m_address.ipv4.sin_addr.s_addr = htonl(address);
279 void Address::setAddress(u8 a, u8 b, u8 c, u8 d)
281 m_addr_family = AF_INET;
282 m_address.ipv4.sin_family = AF_INET;
283 u32 addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
284 m_address.ipv4.sin_addr.s_addr = addr;
287 void Address::setAddress(const IPv6AddressBytes *ipv6_bytes)
289 m_addr_family = AF_INET6;
290 m_address.ipv6.sin6_family = AF_INET6;
292 memcpy(m_address.ipv6.sin6_addr.s6_addr, ipv6_bytes->bytes, 16);
294 memset(m_address.ipv6.sin6_addr.s6_addr, 0, 16);
297 void Address::setPort(u16 port)
302 void Address::print(std::ostream *s) const
304 if(m_addr_family == AF_INET6)
305 *s << "[" << serializeString() << "]:" << m_port;
307 *s << serializeString() << ":" << m_port;
314 UDPSocket::UDPSocket(bool ipv6)
319 bool UDPSocket::init(bool ipv6, bool noExceptions)
321 if (!g_sockets_initialized) {
322 dstream << "Sockets not initialized" << std::endl;
326 // Use IPv6 if specified
327 m_addr_family = ipv6 ? AF_INET6 : AF_INET;
328 m_handle = socket(m_addr_family, SOCK_DGRAM, IPPROTO_UDP);
330 if (socket_enable_debug_output) {
331 dstream << "UDPSocket(" << (int) m_handle
332 << ")::UDPSocket(): ipv6 = "
333 << (ipv6 ? "true" : "false")
342 throw SocketException(std::string("Failed to create socket: error ")
343 + itos(LAST_SOCKET_ERR()));
352 UDPSocket::~UDPSocket()
354 if (socket_enable_debug_output) {
355 dstream << "UDPSocket( " << (int) m_handle << ")::~UDPSocket()"
360 closesocket(m_handle);
366 void UDPSocket::Bind(Address addr)
368 if(socket_enable_debug_output) {
369 dstream << "UDPSocket(" << (int) m_handle << ")::Bind(): "
370 << addr.serializeString() << ":"
371 << addr.getPort() << std::endl;
374 if (addr.getFamily() != m_addr_family) {
375 static const char *errmsg = "Socket and bind address families do not match";
376 errorstream << "Bind failed: " << errmsg << std::endl;
377 throw SocketException(errmsg);
380 if(m_addr_family == AF_INET6) {
381 struct sockaddr_in6 address;
382 memset(&address, 0, sizeof(address));
384 address = addr.getAddress6();
385 address.sin6_family = AF_INET6;
386 address.sin6_port = htons(addr.getPort());
388 if(bind(m_handle, (const struct sockaddr *) &address,
389 sizeof(struct sockaddr_in6)) < 0) {
390 dstream << (int) m_handle << ": Bind failed: "
391 << strerror(errno) << std::endl;
392 throw SocketException("Failed to bind socket");
395 struct sockaddr_in address;
396 memset(&address, 0, sizeof(address));
398 address = addr.getAddress();
399 address.sin_family = AF_INET;
400 address.sin_port = htons(addr.getPort());
402 if (bind(m_handle, (const struct sockaddr *) &address,
403 sizeof(struct sockaddr_in)) < 0) {
404 dstream << (int)m_handle << ": Bind failed: "
405 << strerror(errno) << std::endl;
406 throw SocketException("Failed to bind socket");
411 void UDPSocket::Send(const Address & destination, const void * data, int size)
413 bool dumping_packet = false; // for INTERNET_SIMULATOR
415 if(INTERNET_SIMULATOR)
416 dumping_packet = myrand() % INTERNET_SIMULATOR_PACKET_LOSS == 0;
418 if(socket_enable_debug_output) {
419 // Print packet destination and size
420 dstream << (int)m_handle << " -> ";
421 destination.print(&dstream);
422 dstream << ", size=" << size;
424 // Print packet contents
425 dstream << ", data=";
426 for(int i = 0; i < size && i < 20; i++) {
429 unsigned int a = ((const unsigned char *)data)[i];
430 dstream << std::hex << std::setw(2) << std::setfill('0') << a;
437 dstream << " (DUMPED BY INTERNET_SIMULATOR)";
439 dstream << std::endl;
443 // Lol let's forget it
444 dstream << "UDPSocket::Send(): INTERNET_SIMULATOR: dumping packet."
449 if(destination.getFamily() != m_addr_family)
450 throw SendFailedException("Address family mismatch");
453 if(m_addr_family == AF_INET6) {
454 struct sockaddr_in6 address = destination.getAddress6();
455 address.sin6_port = htons(destination.getPort());
456 sent = sendto(m_handle, (const char *)data, size,
457 0, (struct sockaddr *)&address, sizeof(struct sockaddr_in6));
459 struct sockaddr_in address = destination.getAddress();
460 address.sin_port = htons(destination.getPort());
461 sent = sendto(m_handle, (const char *)data, size,
462 0, (struct sockaddr *)&address, sizeof(struct sockaddr_in));
466 throw SendFailedException("Failed to send packet");
469 int UDPSocket::Receive(Address & sender, void *data, int size)
472 if (!WaitData(m_timeout_ms))
476 if (m_addr_family == AF_INET6) {
477 struct sockaddr_in6 address;
478 memset(&address, 0, sizeof(address));
479 socklen_t address_len = sizeof(address);
481 received = recvfrom(m_handle, (char *) data,
482 size, 0, (struct sockaddr *) &address, &address_len);
487 u16 address_port = ntohs(address.sin6_port);
488 IPv6AddressBytes bytes;
489 memcpy(bytes.bytes, address.sin6_addr.s6_addr, 16);
490 sender = Address(&bytes, address_port);
492 struct sockaddr_in address;
493 memset(&address, 0, sizeof(address));
495 socklen_t address_len = sizeof(address);
497 received = recvfrom(m_handle, (char *)data,
498 size, 0, (struct sockaddr *)&address, &address_len);
503 u32 address_ip = ntohl(address.sin_addr.s_addr);
504 u16 address_port = ntohs(address.sin_port);
506 sender = Address(address_ip, address_port);
509 if (socket_enable_debug_output) {
510 // Print packet sender and size
511 dstream << (int) m_handle << " <- ";
512 sender.print(&dstream);
513 dstream << ", size=" << received;
515 // Print packet contents
516 dstream << ", data=";
517 for(int i = 0; i < received && i < 20; i++) {
520 unsigned int a = ((const unsigned char *) data)[i];
521 dstream << std::hex << std::setw(2) << std::setfill('0') << a;
526 dstream << std::endl;
532 int UDPSocket::GetHandle()
537 void UDPSocket::setTimeoutMs(int timeout_ms)
539 m_timeout_ms = timeout_ms;
542 bool UDPSocket::WaitData(int timeout_ms)
547 // Initialize the set
549 FD_SET(m_handle, &readset);
551 // Initialize time out struct
554 tv.tv_usec = timeout_ms * 1000;
557 result = select(m_handle+1, &readset, NULL, NULL, &tv);
562 if (result < 0 && (errno == EINTR || errno == EBADF)) {
563 // N.B. select() fails when sockets are destroyed on Connection's dtor
564 // with EBADF. Instead of doing tricky synchronization, allow this
565 // thread to exit but don't throw an exception.
570 dstream << m_handle << ": Select failed: " << strerror(errno) << std::endl;
573 int e = WSAGetLastError();
574 dstream << (int) m_handle << ": WSAGetLastError()="
576 if (e == 10004 /* WSAEINTR */ || e == 10009 /* WSAEBADF */) {
577 infostream << "Ignoring WSAEINTR/WSAEBADF." << std::endl;
582 throw SocketException("Select failed");
583 } else if (!FD_ISSET(m_handle, &readset)) {