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 #ifndef WIN32_LEAN_AND_MEAN
38 #define WIN32_LEAN_AND_MEAN
40 // Without this some of the network functions are not found on mingw
42 #define _WIN32_WINNT 0x0501
47 #define LAST_SOCKET_ERR() WSAGetLastError()
48 typedef SOCKET socket_t;
49 typedef int socklen_t;
51 #include <sys/types.h>
52 #include <sys/socket.h>
53 #include <netinet/in.h>
57 #include <arpa/inet.h>
58 #define LAST_SOCKET_ERR() (errno)
62 // Set to true to enable verbose debug output
63 bool socket_enable_debug_output = false; // yuck
65 static bool g_sockets_initialized = false;
71 // Windows needs sockets to be initialized before use
73 if(WSAStartup( MAKEWORD(2,2), &WsaData ) != NO_ERROR)
74 throw SocketException("WSAStartup failed");
76 g_sockets_initialized = true;
79 void sockets_cleanup()
82 // On Windows, cleanup sockets after use
93 memset(&m_address, 0, sizeof(m_address));
96 Address::Address(u32 address, u16 port)
98 memset(&m_address, 0, sizeof(m_address));
103 Address::Address(u8 a, u8 b, u8 c, u8 d, u16 port)
105 memset(&m_address, 0, sizeof(m_address));
106 setAddress(a, b, c, d);
110 Address::Address(const IPv6AddressBytes *ipv6_bytes, u16 port)
112 memset(&m_address, 0, sizeof(m_address));
113 setAddress(ipv6_bytes);
117 // Equality (address family, address and port must be equal)
118 bool Address::operator==(const Address &address)
120 if(address.m_addr_family != m_addr_family || address.m_port != m_port)
122 else if(m_addr_family == AF_INET)
124 return m_address.ipv4.sin_addr.s_addr ==
125 address.m_address.ipv4.sin_addr.s_addr;
127 else if(m_addr_family == AF_INET6)
129 return memcmp(m_address.ipv6.sin6_addr.s6_addr,
130 address.m_address.ipv6.sin6_addr.s6_addr, 16) == 0;
136 bool Address::operator!=(const Address &address)
138 return !(*this == address);
141 void Address::Resolve(const char *name)
143 if (!name || name[0] == 0) {
144 if (m_addr_family == AF_INET) {
146 } else if (m_addr_family == AF_INET6) {
147 setAddress((IPv6AddressBytes*) 0);
152 struct addrinfo *resolved, hints;
153 memset(&hints, 0, sizeof(hints));
156 hints.ai_socktype = 0;
157 hints.ai_protocol = 0;
159 if(g_settings->getBool("enable_ipv6"))
161 // AF_UNSPEC allows both IPv6 and IPv4 addresses to be returned
162 hints.ai_family = AF_UNSPEC;
166 hints.ai_family = AF_INET;
170 int e = getaddrinfo(name, NULL, &hints, &resolved);
172 throw ResolveError(gai_strerror(e));
175 if(resolved->ai_family == AF_INET)
177 struct sockaddr_in *t = (struct sockaddr_in *) resolved->ai_addr;
178 m_addr_family = AF_INET;
181 else if(resolved->ai_family == AF_INET6)
183 struct sockaddr_in6 *t = (struct sockaddr_in6 *) resolved->ai_addr;
184 m_addr_family = AF_INET6;
189 freeaddrinfo(resolved);
190 throw ResolveError("");
192 freeaddrinfo(resolved);
195 // IP address -> textual representation
196 std::string Address::serializeString() const
198 // windows XP doesnt have inet_ntop, maybe use better func
200 if(m_addr_family == AF_INET)
204 addr = ntohl(m_address.ipv4.sin_addr.s_addr);
205 a = (addr & 0xFF000000) >> 24;
206 b = (addr & 0x00FF0000) >> 16;
207 c = (addr & 0x0000FF00) >> 8;
208 d = (addr & 0x000000FF);
209 return itos(a) + "." + itos(b) + "." + itos(c) + "." + itos(d);
211 else if(m_addr_family == AF_INET6)
213 std::ostringstream os;
214 for(int i = 0; i < 16; i += 2)
217 (m_address.ipv6.sin6_addr.s6_addr[i] << 8) |
218 (m_address.ipv6.sin6_addr.s6_addr[i + 1]);
219 os << std::hex << section;
226 return std::string("");
228 char str[INET6_ADDRSTRLEN];
229 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) {
230 return std::string("");
232 return std::string(str);
236 struct sockaddr_in Address::getAddress() const
238 return m_address.ipv4; // NOTE: NO PORT INCLUDED, use getPort()
241 struct sockaddr_in6 Address::getAddress6() const
243 return m_address.ipv6; // NOTE: NO PORT INCLUDED, use getPort()
246 u16 Address::getPort() const
251 int Address::getFamily() const
253 return m_addr_family;
256 bool Address::isIPv6() const
258 return m_addr_family == AF_INET6;
261 bool Address::isZero() const
263 if (m_addr_family == AF_INET) {
264 return m_address.ipv4.sin_addr.s_addr == 0;
265 } else if (m_addr_family == AF_INET6) {
266 static const char zero[16] = {0};
267 return memcmp(m_address.ipv6.sin6_addr.s6_addr,
273 void Address::setAddress(u32 address)
275 m_addr_family = AF_INET;
276 m_address.ipv4.sin_family = AF_INET;
277 m_address.ipv4.sin_addr.s_addr = htonl(address);
280 void Address::setAddress(u8 a, u8 b, u8 c, u8 d)
282 m_addr_family = AF_INET;
283 m_address.ipv4.sin_family = AF_INET;
284 u32 addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
285 m_address.ipv4.sin_addr.s_addr = addr;
288 void Address::setAddress(const IPv6AddressBytes *ipv6_bytes)
290 m_addr_family = AF_INET6;
291 m_address.ipv6.sin6_family = AF_INET6;
293 memcpy(m_address.ipv6.sin6_addr.s6_addr, ipv6_bytes->bytes, 16);
295 memset(m_address.ipv6.sin6_addr.s6_addr, 0, 16);
298 void Address::setPort(u16 port)
303 void Address::print(std::ostream *s) const
305 if(m_addr_family == AF_INET6)
306 *s << "[" << serializeString() << "]:" << m_port;
308 *s << serializeString() << ":" << m_port;
315 UDPSocket::UDPSocket(bool ipv6)
320 bool UDPSocket::init(bool ipv6, bool noExceptions)
322 if (g_sockets_initialized == false) {
323 dstream << "Sockets not initialized" << std::endl;
327 // Use IPv6 if specified
328 m_addr_family = ipv6 ? AF_INET6 : AF_INET;
329 m_handle = socket(m_addr_family, SOCK_DGRAM, IPPROTO_UDP);
331 if (socket_enable_debug_output) {
332 dstream << "UDPSocket(" << (int) m_handle
333 << ")::UDPSocket(): ipv6 = "
334 << (ipv6 ? "true" : "false")
342 throw SocketException(std::string("Failed to create socket: error ")
343 + itos(LAST_SOCKET_ERR()));
353 UDPSocket::~UDPSocket()
355 if (socket_enable_debug_output) {
356 dstream << "UDPSocket( " << (int) m_handle << ")::~UDPSocket()"
361 closesocket(m_handle);
367 void UDPSocket::Bind(Address addr)
369 if(socket_enable_debug_output) {
370 dstream << "UDPSocket(" << (int) m_handle << ")::Bind(): "
371 << addr.serializeString() << ":"
372 << addr.getPort() << std::endl;
375 if (addr.getFamily() != m_addr_family) {
376 static const char *errmsg = "Socket and bind address families do not match";
377 errorstream << "Bind failed: " << errmsg << std::endl;
378 throw SocketException(errmsg);
381 if(m_addr_family == AF_INET6) {
382 struct sockaddr_in6 address;
383 memset(&address, 0, sizeof(address));
385 address = addr.getAddress6();
386 address.sin6_family = AF_INET6;
387 address.sin6_port = htons(addr.getPort());
389 if(bind(m_handle, (const struct sockaddr *) &address,
390 sizeof(struct sockaddr_in6)) < 0) {
391 dstream << (int) m_handle << ": Bind failed: "
392 << strerror(errno) << std::endl;
393 throw SocketException("Failed to bind socket");
396 struct sockaddr_in address;
397 memset(&address, 0, sizeof(address));
399 address = addr.getAddress();
400 address.sin_family = AF_INET;
401 address.sin_port = htons(addr.getPort());
403 if (bind(m_handle, (const struct sockaddr *) &address,
404 sizeof(struct sockaddr_in)) < 0) {
405 dstream << (int)m_handle << ": Bind failed: "
406 << strerror(errno) << std::endl;
407 throw SocketException("Failed to bind socket");
412 void UDPSocket::Send(const Address & destination, const void * data, int size)
414 bool dumping_packet = false; // for INTERNET_SIMULATOR
416 if(INTERNET_SIMULATOR)
417 dumping_packet = myrand() % INTERNET_SIMULATOR_PACKET_LOSS == 0;
419 if(socket_enable_debug_output) {
420 // Print packet destination and size
421 dstream << (int)m_handle << " -> ";
422 destination.print(&dstream);
423 dstream << ", size=" << size;
425 // Print packet contents
426 dstream << ", data=";
427 for(int i = 0; i < size && i < 20; i++) {
430 unsigned int a = ((const unsigned char *)data)[i];
431 dstream << std::hex << std::setw(2) << std::setfill('0') << a;
438 dstream << " (DUMPED BY INTERNET_SIMULATOR)";
440 dstream << std::endl;
444 // Lol let's forget it
445 dstream << "UDPSocket::Send(): INTERNET_SIMULATOR: dumping packet."
450 if(destination.getFamily() != m_addr_family)
451 throw SendFailedException("Address family mismatch");
454 if(m_addr_family == AF_INET6) {
455 struct sockaddr_in6 address = destination.getAddress6();
456 address.sin6_port = htons(destination.getPort());
457 sent = sendto(m_handle, (const char *)data, size,
458 0, (struct sockaddr *)&address, sizeof(struct sockaddr_in6));
460 struct sockaddr_in address = destination.getAddress();
461 address.sin_port = htons(destination.getPort());
462 sent = sendto(m_handle, (const char *)data, size,
463 0, (struct sockaddr *)&address, sizeof(struct sockaddr_in));
467 throw SendFailedException("Failed to send packet");
470 int UDPSocket::Receive(Address & sender, void *data, int size)
473 if(WaitData(m_timeout_ms) == false)
477 if (m_addr_family == AF_INET6) {
478 struct sockaddr_in6 address;
479 memset(&address, 0, sizeof(address));
480 socklen_t address_len = sizeof(address);
482 received = recvfrom(m_handle, (char *) data,
483 size, 0, (struct sockaddr *) &address, &address_len);
488 u16 address_port = ntohs(address.sin6_port);
489 IPv6AddressBytes bytes;
490 memcpy(bytes.bytes, address.sin6_addr.s6_addr, 16);
491 sender = Address(&bytes, address_port);
493 struct sockaddr_in address;
494 memset(&address, 0, sizeof(address));
496 socklen_t address_len = sizeof(address);
498 received = recvfrom(m_handle, (char *)data,
499 size, 0, (struct sockaddr *)&address, &address_len);
504 u32 address_ip = ntohl(address.sin_addr.s_addr);
505 u16 address_port = ntohs(address.sin_port);
507 sender = Address(address_ip, address_port);
510 if (socket_enable_debug_output) {
511 // Print packet sender and size
512 dstream << (int) m_handle << " <- ";
513 sender.print(&dstream);
514 dstream << ", size=" << received;
516 // Print packet contents
517 dstream << ", data=";
518 for(int i = 0; i < received && i < 20; i++) {
521 unsigned int a = ((const unsigned char *) data)[i];
522 dstream << std::hex << std::setw(2) << std::setfill('0') << a;
527 dstream << std::endl;
533 int UDPSocket::GetHandle()
538 void UDPSocket::setTimeoutMs(int timeout_ms)
540 m_timeout_ms = timeout_ms;
543 bool UDPSocket::WaitData(int timeout_ms)
548 // Initialize the set
550 FD_SET(m_handle, &readset);
552 // Initialize time out struct
555 tv.tv_usec = timeout_ms * 1000;
558 result = select(m_handle+1, &readset, NULL, NULL, &tv);
562 else 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.
567 } else if (result < 0) {
568 dstream << (int) m_handle << ": Select failed: "
569 << strerror(errno) << std::endl;
572 int e = WSAGetLastError();
573 dstream << (int) m_handle << ": WSAGetLastError()="
575 if (e == 10004 /* WSAEINTR */ || e == 10009 /* WSAEBADF */) {
576 infostream << "Ignoring WSAEINTR/WSAEBADF." << std::endl;
581 throw SocketException("Select failed");
582 } else if(FD_ISSET(m_handle, &readset) == false) {