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"
35 #include "main.h" // for g_settings
38 #ifndef WIN32_LEAN_AND_MEAN
39 #define WIN32_LEAN_AND_MEAN
41 // Without this some of the network functions are not found on mingw
43 #define _WIN32_WINNT 0x0501
49 #pragma comment(lib, "ws2_32.lib")
51 typedef SOCKET socket_t;
52 typedef int socklen_t;
54 #include <sys/types.h>
55 #include <sys/socket.h>
56 #include <netinet/in.h>
60 #include <arpa/inet.h>
64 // Set to true to enable verbose debug output
65 bool socket_enable_debug_output = false;
67 bool g_sockets_initialized = false;
73 // Windows needs sockets to be initialized before use
75 if(WSAStartup( MAKEWORD(2,2), &WsaData ) != NO_ERROR)
76 throw SocketException("WSAStartup failed");
78 g_sockets_initialized = true;
81 void sockets_cleanup()
84 // On Windows, cleanup sockets after use
96 memset(&m_address, 0, sizeof(m_address));
100 Address::Address(u32 address, u16 port)
102 memset(&m_address, 0, sizeof(m_address));
107 Address::Address(u8 a, u8 b, u8 c, u8 d, u16 port)
109 memset(&m_address, 0, sizeof(m_address));
110 setAddress(a, b, c, d);
114 Address::Address(const IPv6AddressBytes * ipv6_bytes, u16 port)
116 memset(&m_address, 0, sizeof(m_address));
117 setAddress(ipv6_bytes);
121 // Equality (address family, address and port must be equal)
122 bool Address::operator==(Address &address)
124 if(address.m_addr_family != m_addr_family || address.m_port != m_port)
126 else if(m_addr_family == AF_INET)
128 return m_address.ipv4.sin_addr.s_addr ==
129 address.m_address.ipv4.sin_addr.s_addr;
131 else if(m_addr_family == AF_INET6)
133 return memcmp(m_address.ipv6.sin6_addr.s6_addr,
134 address.m_address.ipv6.sin6_addr.s6_addr, 16) == 0;
140 bool Address::operator!=(Address &address)
142 return !(*this == address);
145 void Address::Resolve(const char *name)
147 if (!name || name[0] == 0) {
148 if (m_addr_family == AF_INET) {
150 } else if (m_addr_family == AF_INET6) {
151 setAddress((IPv6AddressBytes*) 0);
156 struct addrinfo *resolved, hints;
157 memset(&hints, 0, sizeof(hints));
160 hints.ai_socktype = 0;
161 hints.ai_protocol = 0;
163 if(g_settings->getBool("enable_ipv6"))
165 // AF_UNSPEC allows both IPv6 and IPv4 addresses to be returned
166 hints.ai_family = AF_UNSPEC;
170 hints.ai_family = AF_INET;
174 int e = getaddrinfo(name, NULL, &hints, &resolved);
176 throw ResolveError(gai_strerror(e));
179 if(resolved->ai_family == AF_INET)
181 struct sockaddr_in *t = (struct sockaddr_in *) resolved->ai_addr;
182 m_addr_family = AF_INET;
185 else if(resolved->ai_family == AF_INET6)
187 struct sockaddr_in6 *t = (struct sockaddr_in6 *) resolved->ai_addr;
188 m_addr_family = AF_INET6;
193 freeaddrinfo(resolved);
194 throw ResolveError("");
196 freeaddrinfo(resolved);
199 // IP address -> textual representation
200 std::string Address::serializeString() const
202 // windows XP doesnt have inet_ntop, maybe use better func
204 if(m_addr_family == AF_INET)
208 addr = ntohl(m_address.ipv4.sin_addr.s_addr);
209 a = (addr & 0xFF000000) >> 24;
210 b = (addr & 0x00FF0000) >> 16;
211 c = (addr & 0x0000FF00) >> 8;
212 d = (addr & 0x000000FF);
213 return itos(a) + "." + itos(b) + "." + itos(c) + "." + itos(d);
215 else if(m_addr_family == AF_INET6)
217 std::ostringstream os;
218 for(int i = 0; i < 16; i += 2)
221 (m_address.ipv6.sin6_addr.s6_addr[i] << 8) |
222 (m_address.ipv6.sin6_addr.s6_addr[i + 1]);
223 os << std::hex << section;
230 return std::string("");
232 char str[INET6_ADDRSTRLEN];
233 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) {
234 return std::string("");
236 return std::string(str);
240 struct sockaddr_in Address::getAddress() const
242 return m_address.ipv4; // NOTE: NO PORT INCLUDED, use getPort()
245 struct sockaddr_in6 Address::getAddress6() const
247 return m_address.ipv6; // NOTE: NO PORT INCLUDED, use getPort()
250 u16 Address::getPort() const
255 int Address::getFamily() const
257 return m_addr_family;
260 bool Address::isIPv6() const
262 return m_addr_family == AF_INET6;
265 bool Address::isZero() const
267 if (m_addr_family == AF_INET) {
268 return m_address.ipv4.sin_addr.s_addr == 0;
269 } else if (m_addr_family == AF_INET6) {
270 static const char zero[16] = {0};
271 return memcmp(m_address.ipv6.sin6_addr.s6_addr,
277 void Address::setAddress(u32 address)
279 m_addr_family = AF_INET;
280 m_address.ipv4.sin_family = AF_INET;
281 m_address.ipv4.sin_addr.s_addr = htonl(address);
284 void Address::setAddress(u8 a, u8 b, u8 c, u8 d)
286 m_addr_family = AF_INET;
287 m_address.ipv4.sin_family = AF_INET;
288 u32 addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
289 m_address.ipv4.sin_addr.s_addr = addr;
292 void Address::setAddress(const IPv6AddressBytes * ipv6_bytes)
294 m_addr_family = AF_INET6;
295 m_address.ipv6.sin6_family = AF_INET6;
297 memcpy(m_address.ipv6.sin6_addr.s6_addr, ipv6_bytes->bytes, 16);
299 memset(m_address.ipv6.sin6_addr.s6_addr, 0, 16);
302 void Address::setPort(u16 port)
307 void Address::print(std::ostream *s) const
309 if(m_addr_family == AF_INET6)
311 (*s) << "[" << serializeString() << "]:" << m_port;
315 (*s) << serializeString() << ":" << m_port;
323 UDPSocket::UDPSocket(bool ipv6)
325 if(g_sockets_initialized == false)
326 throw SocketException("Sockets not initialized");
328 // Use IPv6 if specified
329 m_addr_family = ipv6 ? AF_INET6 : AF_INET;
330 m_handle = socket(m_addr_family, SOCK_DGRAM, IPPROTO_UDP);
332 if(socket_enable_debug_output)
334 dstream << "UDPSocket(" << (int) m_handle
335 << ")::UDPSocket(): ipv6 = "
336 << (ipv6 ? "true" : "false")
342 throw SocketException("Failed to create socket");
348 UDPSocket::~UDPSocket()
350 if(socket_enable_debug_output)
352 dstream << "UDPSocket( " << (int) m_handle << ")::~UDPSocket()"
357 closesocket(m_handle);
363 void UDPSocket::Bind(Address addr)
365 if(socket_enable_debug_output)
367 dstream << "UDPSocket(" << (int) m_handle << ")::Bind(): "
368 << addr.serializeString() << ":"
369 << addr.getPort() << std::endl;
372 if (addr.getFamily() != m_addr_family)
374 char errmsg[] = "Socket and bind address families do not match";
375 errorstream << "Bind failed: " << errmsg << std::endl;
376 throw SocketException(errmsg);
379 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)
391 dstream << (int) m_handle << ": Bind failed: "
392 << strerror(errno) << std::endl;
393 throw SocketException("Failed to bind socket");
398 struct sockaddr_in address;
399 memset(&address, 0, sizeof(address));
401 address = addr.getAddress();
402 address.sin_family = AF_INET;
403 address.sin_port = htons(addr.getPort());
405 if(bind(m_handle, (const struct sockaddr *) &address,
406 sizeof(struct sockaddr_in)) < 0)
408 dstream << (int) m_handle << ": Bind failed: "
409 << strerror(errno) << std::endl;
410 throw SocketException("Failed to bind socket");
415 void UDPSocket::Send(const Address & destination, const void * data, int size)
417 bool dumping_packet = false; // for INTERNET_SIMULATOR
419 if(INTERNET_SIMULATOR)
420 dumping_packet = (myrand() % INTERNET_SIMULATOR_PACKET_LOSS == 0);
422 if(socket_enable_debug_output)
424 // Print packet destination and size
425 dstream << (int) m_handle << " -> ";
426 destination.print(&dstream);
427 dstream << ", size=" << size;
429 // Print packet contents
430 dstream << ", data=";
431 for(int i = 0; i < size && i < 20; i++)
435 unsigned int a = ((const unsigned char *) data)[i];
436 dstream << std::hex << std::setw(2) << std::setfill('0')
444 dstream << " (DUMPED BY INTERNET_SIMULATOR)";
446 dstream << std::endl;
451 // Lol let's forget it
452 dstream << "UDPSocket::Send(): "
453 "INTERNET_SIMULATOR: dumping packet."
458 if(destination.getFamily() != m_addr_family)
459 throw SendFailedException("Address family mismatch");
462 if(m_addr_family == AF_INET6)
464 struct sockaddr_in6 address = destination.getAddress6();
465 address.sin6_port = htons(destination.getPort());
466 sent = sendto(m_handle, (const char *) data, size,
467 0, (struct sockaddr *) &address, sizeof(struct sockaddr_in6));
471 struct sockaddr_in address = destination.getAddress();
472 address.sin_port = htons(destination.getPort());
473 sent = sendto(m_handle, (const char *) data, size,
474 0, (struct sockaddr *) &address, sizeof(struct sockaddr_in));
479 throw SendFailedException("Failed to send packet");
483 int UDPSocket::Receive(Address & sender, void * data, int size)
486 if(WaitData(m_timeout_ms) == false)
492 if(m_addr_family == AF_INET6)
494 struct sockaddr_in6 address;
495 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 u16 address_port = ntohs(address.sin6_port);
505 IPv6AddressBytes bytes;
506 memcpy(bytes.bytes, address.sin6_addr.s6_addr, 16);
507 sender = Address(&bytes, address_port);
511 struct sockaddr_in address;
512 memset(&address, 0, sizeof(address));
514 socklen_t address_len = sizeof(address);
516 received = recvfrom(m_handle, (char *) data,
517 size, 0, (struct sockaddr *) &address, &address_len);
522 u32 address_ip = ntohl(address.sin_addr.s_addr);
523 u16 address_port = ntohs(address.sin_port);
525 sender = Address(address_ip, address_port);
528 if(socket_enable_debug_output)
530 // Print packet sender and size
531 dstream << (int) m_handle << " <- ";
532 sender.print(&dstream);
533 dstream << ", size=" << received;
535 // Print packet contents
536 dstream << ", data=";
537 for(int i = 0; i < received && i < 20; i++)
541 unsigned int a = ((const unsigned char *) data)[i];
542 dstream << std::hex << std::setw(2) << std::setfill('0')
548 dstream << std::endl;
554 int UDPSocket::GetHandle()
559 void UDPSocket::setTimeoutMs(int timeout_ms)
561 m_timeout_ms = timeout_ms;
564 bool UDPSocket::WaitData(int timeout_ms)
569 // Initialize the set
571 FD_SET(m_handle, &readset);
573 // Initialize time out struct
576 tv.tv_usec = timeout_ms * 1000;
579 result = select(m_handle+1, &readset, NULL, NULL, &tv);
583 else if(result < 0 && (errno == EINTR || errno == EBADF))
584 // N.B. select() fails when sockets are destroyed on Connection's dtor
585 // with EBADF. Instead of doing tricky synchronization, allow this
586 // thread to exit but don't throw an exception.
590 dstream << (int) m_handle << ": Select failed: "
591 << strerror(errno) << std::endl;
594 int e = WSAGetLastError();
595 dstream << (int) m_handle << ": WSAGetLastError()="
597 if(e == 10004 /* = WSAEINTR */ || e == 10009 /*WSAEBADF*/)
599 dstream << "WARNING: Ignoring WSAEINTR/WSAEBADF." << std::endl;
604 throw SocketException("Select failed");
606 else if(FD_ISSET(m_handle, &readset) == false)