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.
23 #ifndef WIN32_LEAN_AND_MEAN
24 #define WIN32_LEAN_AND_MEAN
26 // Without this some of the network functions are not found on mingw
28 #define _WIN32_WINNT 0x0501
34 #pragma comment(lib, "ws2_32.lib")
36 typedef SOCKET socket_t;
37 typedef int socklen_t;
39 #include <sys/types.h>
40 #include <sys/socket.h>
41 #include <netinet/in.h>
45 #include <arpa/inet.h>
49 #include "constants.h"
52 #include "main.h" // for g_settings
60 #include "util/string.h"
61 #include "util/numeric.h"
63 // Set to true to enable verbose debug output
64 bool socket_enable_debug_output = false;
66 bool g_sockets_initialized = false;
72 // Windows needs sockets to be initialized before use
74 if(WSAStartup( MAKEWORD(2,2), &WsaData ) != NO_ERROR)
75 throw SocketException("WSAStartup failed");
77 g_sockets_initialized = true;
80 void sockets_cleanup()
83 // On Windows, cleanup sockets after use
95 memset(&m_address, 0, sizeof(m_address));
99 Address::Address(u32 address, u16 port)
101 memset(&m_address, 0, sizeof(m_address));
106 Address::Address(u8 a, u8 b, u8 c, u8 d, u16 port)
108 memset(&m_address, 0, sizeof(m_address));
109 setAddress(a, b, c, d);
113 Address::Address(const IPv6AddressBytes * ipv6_bytes, u16 port)
115 memset(&m_address, 0, sizeof(m_address));
116 setAddress(ipv6_bytes);
120 // Equality (address family, address and port must be equal)
121 bool Address::operator==(Address &address)
123 if(address.m_addr_family != m_addr_family || address.m_port != m_port)
125 else if(m_addr_family == AF_INET)
127 return m_address.ipv4.sin_addr.s_addr ==
128 address.m_address.ipv4.sin_addr.s_addr;
130 else if(m_addr_family == AF_INET6)
132 return memcmp(m_address.ipv6.sin6_addr.s6_addr,
133 address.m_address.ipv6.sin6_addr.s6_addr, 16) == 0;
139 bool Address::operator!=(Address &address)
141 return !(*this == address);
144 void Address::Resolve(const char *name)
146 if (!name || name[0] == 0) {
147 if (m_addr_family == AF_INET) {
149 } else if (m_addr_family == AF_INET6) {
150 setAddress((IPv6AddressBytes*) 0);
155 struct addrinfo *resolved, hints;
156 memset(&hints, 0, sizeof(hints));
159 hints.ai_socktype = 0;
160 hints.ai_protocol = 0;
162 if(g_settings->getBool("enable_ipv6"))
164 // AF_UNSPEC allows both IPv6 and IPv4 addresses to be returned
165 hints.ai_family = AF_UNSPEC;
169 hints.ai_family = AF_INET;
173 int e = getaddrinfo(name, NULL, &hints, &resolved);
175 throw ResolveError(gai_strerror(e));
178 if(resolved->ai_family == AF_INET)
180 struct sockaddr_in *t = (struct sockaddr_in *) resolved->ai_addr;
181 m_addr_family = AF_INET;
184 else if(resolved->ai_family == AF_INET6)
186 struct sockaddr_in6 *t = (struct sockaddr_in6 *) resolved->ai_addr;
187 m_addr_family = AF_INET6;
192 freeaddrinfo(resolved);
193 throw ResolveError("");
195 freeaddrinfo(resolved);
198 // IP address -> textual representation
199 std::string Address::serializeString() const
201 // windows XP doesnt have inet_ntop, maybe use better func
203 if(m_addr_family == AF_INET)
206 addr = ntohl(m_address.ipv4.sin_addr.s_addr);
207 a = (addr & 0xFF000000) >> 24;
208 b = (addr & 0x00FF0000) >> 16;
209 c = (addr & 0x0000FF00) >> 8;
210 d = (addr & 0x000000FF);
211 return itos(a) + "." + itos(b) + "." + itos(c) + "." + itos(d);
213 else if(m_addr_family == AF_INET6)
215 std::ostringstream os;
216 for(int i = 0; i < 16; i += 2)
219 (m_address.ipv6.sin6_addr.s6_addr[i] << 8) |
220 (m_address.ipv6.sin6_addr.s6_addr[i + 1]);
221 os << std::hex << section;
228 return std::string("");
230 char str[INET6_ADDRSTRLEN];
231 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) {
232 return std::string("");
234 return std::string(str);
238 struct sockaddr_in Address::getAddress() const
240 return m_address.ipv4; // NOTE: NO PORT INCLUDED, use getPort()
243 struct sockaddr_in6 Address::getAddress6() const
245 return m_address.ipv6; // NOTE: NO PORT INCLUDED, use getPort()
248 u16 Address::getPort() const
253 int Address::getFamily() const
255 return m_addr_family;
258 bool Address::isIPv6() const
260 return m_addr_family == AF_INET6;
263 bool Address::isZero() const
265 if (m_addr_family == AF_INET) {
266 return m_address.ipv4.sin_addr.s_addr == 0;
267 } else if (m_addr_family == AF_INET6) {
268 static const char zero[16] = {0};
269 return memcmp(m_address.ipv6.sin6_addr.s6_addr,
275 void Address::setAddress(u32 address)
277 m_addr_family = AF_INET;
278 m_address.ipv4.sin_family = AF_INET;
279 m_address.ipv4.sin_addr.s_addr = htonl(address);
282 void Address::setAddress(u8 a, u8 b, u8 c, u8 d)
284 m_addr_family = AF_INET;
285 m_address.ipv4.sin_family = AF_INET;
286 u32 addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
287 m_address.ipv4.sin_addr.s_addr = addr;
290 void Address::setAddress(const IPv6AddressBytes * ipv6_bytes)
292 m_addr_family = AF_INET6;
293 m_address.ipv6.sin6_family = AF_INET6;
295 memcpy(m_address.ipv6.sin6_addr.s6_addr, ipv6_bytes->bytes, 16);
297 memset(m_address.ipv6.sin6_addr.s6_addr, 0, 16);
300 void Address::setPort(u16 port)
305 void Address::print(std::ostream *s) const
307 if(m_addr_family == AF_INET6)
309 (*s) << "[" << serializeString() << "]:" << m_port;
313 (*s) << serializeString() << ":" << m_port;
321 UDPSocket::UDPSocket(bool ipv6)
323 if(g_sockets_initialized == false)
324 throw SocketException("Sockets not initialized");
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)
332 dstream << "UDPSocket(" << (int) m_handle
333 << ")::UDPSocket(): ipv6 = "
334 << (ipv6 ? "true" : "false")
340 throw SocketException("Failed to create socket");
346 UDPSocket::~UDPSocket()
348 if(socket_enable_debug_output)
350 dstream << "UDPSocket( " << (int) m_handle << ")::~UDPSocket()"
355 closesocket(m_handle);
361 void UDPSocket::Bind(Address addr)
363 if(socket_enable_debug_output)
365 dstream << "UDPSocket(" << (int) m_handle << ")::Bind(): "
366 << addr.serializeString() << ":"
367 << addr.getPort() << std::endl;
370 if (addr.getFamily() != m_addr_family)
372 char errmsg[] = "Socket and bind address families do not match";
373 errorstream << "Bind failed: " << errmsg << std::endl;
374 throw SocketException(errmsg);
377 if(m_addr_family == AF_INET6)
379 struct sockaddr_in6 address;
380 memset(&address, 0, sizeof(address));
382 address = addr.getAddress6();
383 address.sin6_family = AF_INET6;
384 address.sin6_port = htons(addr.getPort());
386 if(bind(m_handle, (const struct sockaddr *) &address,
387 sizeof(struct sockaddr_in6)) < 0)
389 dstream << (int) m_handle << ": Bind failed: "
390 << strerror(errno) << std::endl;
391 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)
406 dstream << (int) m_handle << ": Bind failed: "
407 << strerror(errno) << std::endl;
408 throw SocketException("Failed to bind socket");
413 void UDPSocket::Send(const Address & destination, const void * data, int size)
415 bool dumping_packet = false; // for INTERNET_SIMULATOR
417 if(INTERNET_SIMULATOR)
418 dumping_packet = (myrand() % INTERNET_SIMULATOR_PACKET_LOSS == 0);
420 if(socket_enable_debug_output)
422 // Print packet destination and size
423 dstream << (int) m_handle << " -> ";
424 destination.print(&dstream);
425 dstream << ", size=" << size;
427 // Print packet contents
428 dstream << ", data=";
429 for(int i = 0; i < size && i < 20; i++)
433 unsigned int a = ((const unsigned char *) data)[i];
434 dstream << std::hex << std::setw(2) << std::setfill('0')
442 dstream << " (DUMPED BY INTERNET_SIMULATOR)";
444 dstream << std::endl;
449 // Lol let's forget it
450 dstream << "UDPSocket::Send(): "
451 "INTERNET_SIMULATOR: dumping packet."
456 if(destination.getFamily() != m_addr_family)
457 throw SendFailedException("Address family mismatch");
460 if(m_addr_family == AF_INET6)
462 struct sockaddr_in6 address = destination.getAddress6();
463 address.sin6_port = htons(destination.getPort());
464 sent = sendto(m_handle, (const char *) data, size,
465 0, (struct sockaddr *) &address, sizeof(struct sockaddr_in6));
469 struct sockaddr_in address = destination.getAddress();
470 address.sin_port = htons(destination.getPort());
471 sent = sendto(m_handle, (const char *) data, size,
472 0, (struct sockaddr *) &address, sizeof(struct sockaddr_in));
477 throw SendFailedException("Failed to send packet");
481 int UDPSocket::Receive(Address & sender, void * data, int size)
484 if(WaitData(m_timeout_ms) == false)
490 if(m_addr_family == AF_INET6)
492 struct sockaddr_in6 address;
493 memset(&address, 0, sizeof(address));
494 socklen_t address_len = sizeof(address);
496 received = recvfrom(m_handle, (char *) data,
497 size, 0, (struct sockaddr *) &address, &address_len);
502 u16 address_port = ntohs(address.sin6_port);
503 IPv6AddressBytes bytes;
504 memcpy(bytes.bytes, address.sin6_addr.s6_addr, 16);
505 sender = Address(&bytes, address_port);
509 struct sockaddr_in address;
510 memset(&address, 0, sizeof(address));
512 socklen_t address_len = sizeof(address);
514 received = recvfrom(m_handle, (char *) data,
515 size, 0, (struct sockaddr *) &address, &address_len);
520 u32 address_ip = ntohl(address.sin_addr.s_addr);
521 u16 address_port = ntohs(address.sin_port);
523 sender = Address(address_ip, address_port);
526 if(socket_enable_debug_output)
528 // Print packet sender and size
529 dstream << (int) m_handle << " <- ";
530 sender.print(&dstream);
531 dstream << ", size=" << received;
533 // Print packet contents
534 dstream << ", data=";
535 for(int i = 0; i < received && i < 20; i++)
539 unsigned int a = ((const unsigned char *) data)[i];
540 dstream << std::hex << std::setw(2) << std::setfill('0')
546 dstream << std::endl;
552 int UDPSocket::GetHandle()
557 void UDPSocket::setTimeoutMs(int timeout_ms)
559 m_timeout_ms = timeout_ms;
562 bool UDPSocket::WaitData(int timeout_ms)
567 // Initialize the set
569 FD_SET(m_handle, &readset);
571 // Initialize time out struct
574 tv.tv_usec = timeout_ms * 1000;
577 result = select(m_handle+1, &readset, NULL, NULL, &tv);
581 else if(result < 0 && (errno == EINTR || errno == EBADF))
582 // N.B. select() fails when sockets are destroyed on Connection's dtor
583 // with EBADF. Instead of doing tricky synchronization, allow this
584 // thread to exit but don't throw an exception.
588 dstream << (int) m_handle << ": Select failed: "
589 << strerror(errno) << std::endl;
592 int e = WSAGetLastError();
593 dstream << (int) m_handle << ": WSAGetLastError()="
595 if(e == 10004 /* = WSAEINTR */ || e == 10009 /*WSAEBADF*/)
597 dstream << "WARNING: Ignoring WSAEINTR/WSAEBADF." << std::endl;
602 throw SocketException("Select failed");
604 else if(FD_ISSET(m_handle, &readset) == false)