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
59 #include "util/string.h"
60 #include "util/numeric.h"
62 // Set to true to enable verbose debug output
63 bool socket_enable_debug_output = false;
65 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
94 memset(&m_address, 0, sizeof m_address);
98 Address::Address(u32 address, u16 port)
104 Address::Address(u8 a, u8 b, u8 c, u8 d, u16 port)
106 setAddress(a, b, c, d);
110 Address::Address(const IPv6AddressBytes * ipv6_bytes, u16 port)
112 setAddress(ipv6_bytes);
116 // Equality (address family, address and port must be equal)
117 bool Address::operator==(Address &address)
119 if(address.m_addr_family != m_addr_family || address.m_port != m_port)
121 else if(m_addr_family == AF_INET)
123 return m_address.ipv4.sin_addr.s_addr ==
124 address.m_address.ipv4.sin_addr.s_addr;
126 else if(m_addr_family == AF_INET6)
128 return memcmp(m_address.ipv6.sin6_addr.s6_addr,
129 address.m_address.ipv6.sin6_addr.s6_addr, 16) == 0;
135 bool Address::operator!=(Address &address)
137 return !(*this == address);
140 void Address::Resolve(const char *name)
142 struct addrinfo *resolved, hints;
143 memset(&hints, 0, sizeof(hints));
146 hints.ai_socktype = 0;
147 hints.ai_protocol = 0;
149 if(g_settings->getBool("enable_ipv6"))
151 // AF_UNSPEC allows both IPv6 and IPv4 addresses to be returned
152 hints.ai_family = AF_UNSPEC;
156 hints.ai_family = AF_INET;
160 int e = getaddrinfo(name, NULL, &hints, &resolved);
162 throw ResolveError(gai_strerror(e));
165 if(resolved->ai_family == AF_INET)
167 struct sockaddr_in *t = (struct sockaddr_in *) resolved->ai_addr;
168 m_addr_family = AF_INET;
171 else if(resolved->ai_family == AF_INET6)
173 struct sockaddr_in6 *t = (struct sockaddr_in6 *) resolved->ai_addr;
174 m_addr_family = AF_INET6;
179 freeaddrinfo(resolved);
180 throw ResolveError("");
182 freeaddrinfo(resolved);
185 // IP address -> textual representation
186 std::string Address::serializeString() const
188 // windows XP doesnt have inet_ntop, maybe use better func
190 if(m_addr_family == AF_INET)
193 addr = ntohl(m_address.ipv4.sin_addr.s_addr);
194 a = (addr & 0xFF000000) >> 24;
195 b = (addr & 0x00FF0000) >> 16;
196 c = (addr & 0x0000FF00) >> 8;
197 d = (addr & 0x000000FF);
198 return itos(a) + "." + itos(b) + "." + itos(c) + "." + itos(d);
200 else if(m_addr_family == AF_INET6)
202 std::ostringstream os;
203 for(int i = 0; i < 16; i += 2)
206 (m_address.ipv6.sin6_addr.s6_addr[i] << 8) |
207 (m_address.ipv6.sin6_addr.s6_addr[i + 1]);
208 os << std::hex << section;
215 return std::string("");
217 char str[INET6_ADDRSTRLEN];
218 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) {
219 return std::string("");
221 return std::string(str);
225 struct sockaddr_in Address::getAddress() const
227 return m_address.ipv4; // NOTE: NO PORT INCLUDED, use getPort()
230 struct sockaddr_in6 Address::getAddress6() const
232 return m_address.ipv6; // NOTE: NO PORT INCLUDED, use getPort()
235 u16 Address::getPort() const
240 int Address::getFamily() const
242 return m_addr_family;
245 bool Address::isIPv6() const
247 return m_addr_family == AF_INET6;
250 void Address::setAddress(u32 address)
252 m_addr_family = AF_INET;
253 m_address.ipv4.sin_family = AF_INET;
254 m_address.ipv4.sin_addr.s_addr = htonl(address);
257 void Address::setAddress(u8 a, u8 b, u8 c, u8 d)
259 m_addr_family = AF_INET;
260 m_address.ipv4.sin_family = AF_INET;
261 u32 addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
262 m_address.ipv4.sin_addr.s_addr = addr;
265 void Address::setAddress(const IPv6AddressBytes * ipv6_bytes)
267 m_addr_family = AF_INET6;
268 m_address.ipv6.sin6_family = AF_INET6;
270 memcpy(m_address.ipv6.sin6_addr.s6_addr, ipv6_bytes->bytes, 16);
272 memset(m_address.ipv6.sin6_addr.s6_addr, 0, 16);
275 void Address::setPort(u16 port)
280 void Address::print(std::ostream *s) const
282 if(m_addr_family == AF_INET6)
284 (*s) << "[" << serializeString() << "]:" << m_port;
288 (*s) << serializeString() << ":" << m_port;
296 UDPSocket::UDPSocket(bool ipv6)
298 if(g_sockets_initialized == false)
299 throw SocketException("Sockets not initialized");
301 // Use IPv6 if specified
302 m_addr_family = ipv6 ? AF_INET6 : AF_INET;
303 m_handle = socket(m_addr_family, SOCK_DGRAM, IPPROTO_UDP);
305 if(socket_enable_debug_output)
307 dstream << "UDPSocket(" << (int) m_handle
308 << ")::UDPSocket(): ipv6 = "
309 << (ipv6 ? "true" : "false")
315 throw SocketException("Failed to create socket");
321 UDPSocket::~UDPSocket()
323 if(socket_enable_debug_output)
325 dstream << "UDPSocket( " << (int) m_handle << ")::~UDPSocket()"
330 closesocket(m_handle);
336 void UDPSocket::Bind(u16 port)
338 if(socket_enable_debug_output)
340 dstream << "UDPSocket(" << (int) m_handle << ")::Bind(): "
341 << "port=" << port << std::endl;
344 if(m_addr_family == AF_INET6)
346 struct sockaddr_in6 address;
347 address.sin6_family = AF_INET6;
348 address.sin6_addr = in6addr_any;
349 address.sin6_port = htons(port);
351 if(bind(m_handle, (const struct sockaddr *) &address,
352 sizeof(struct sockaddr_in6)) < 0)
354 dstream << (int) m_handle << ": Bind failed: "
355 << strerror(errno) << std::endl;
356 throw SocketException("Failed to bind socket");
361 struct sockaddr_in address;
362 address.sin_family = AF_INET;
363 address.sin_addr.s_addr = INADDR_ANY;
364 address.sin_port = htons(port);
366 if(bind(m_handle, (const struct sockaddr *) &address,
367 sizeof(struct sockaddr_in)) < 0)
369 dstream << (int) m_handle << ": Bind failed: "
370 << strerror(errno) << std::endl;
371 throw SocketException("Failed to bind socket");
376 void UDPSocket::Send(const Address & destination, const void * data, int size)
378 bool dumping_packet = false; // for INTERNET_SIMULATOR
380 if(INTERNET_SIMULATOR)
381 dumping_packet = (myrand() % INTERNET_SIMULATOR_PACKET_LOSS == 0);
383 if(socket_enable_debug_output)
385 // Print packet destination and size
386 dstream << (int) m_handle << " -> ";
387 destination.print(&dstream);
388 dstream << ", size=" << size;
390 // Print packet contents
391 dstream << ", data=";
392 for(int i = 0; i < size && i < 20; i++)
396 unsigned int a = ((const unsigned char *) data)[i];
397 DEBUGPRINT("%.2X", a);
404 dstream << " (DUMPED BY INTERNET_SIMULATOR)";
406 dstream << std::endl;
411 // Lol let's forget it
412 dstream << "UDPSocket::Send(): "
413 "INTERNET_SIMULATOR: dumping packet."
418 if(destination.getFamily() != m_addr_family)
419 throw SendFailedException("Address family mismatch");
422 if(m_addr_family == AF_INET6)
424 struct sockaddr_in6 address = destination.getAddress6();
425 address.sin6_port = htons(destination.getPort());
426 sent = sendto(m_handle, (const char *) data, size,
427 0, (struct sockaddr *) &address, sizeof(struct sockaddr_in6));
431 struct sockaddr_in address = destination.getAddress();
432 address.sin_port = htons(destination.getPort());
433 sent = sendto(m_handle, (const char *) data, size,
434 0, (struct sockaddr *) &address, sizeof(struct sockaddr_in));
439 throw SendFailedException("Failed to send packet");
443 int UDPSocket::Receive(Address & sender, void * data, int size)
446 if(WaitData(m_timeout_ms) == false)
452 if(m_addr_family == AF_INET6)
454 struct sockaddr_in6 address;
455 socklen_t address_len = sizeof(address);
457 received = recvfrom(m_handle, (char *) data,
458 size, 0, (struct sockaddr *) &address, &address_len);
463 u16 address_port = ntohs(address.sin6_port);
464 IPv6AddressBytes bytes;
465 memcpy(bytes.bytes, address.sin6_addr.s6_addr, 16);
466 sender = Address(&bytes, address_port);
470 struct sockaddr_in address;
471 socklen_t address_len = sizeof(address);
473 received = recvfrom(m_handle, (char *) data,
474 size, 0, (struct sockaddr *) &address, &address_len);
479 u32 address_ip = ntohl(address.sin_addr.s_addr);
480 u16 address_port = ntohs(address.sin_port);
482 sender = Address(address_ip, address_port);
485 if(socket_enable_debug_output)
487 // Print packet sender and size
488 dstream << (int) m_handle << " <- ";
489 sender.print(&dstream);
490 dstream << ", size=" << received;
492 // Print packet contents
493 dstream << ", data=";
494 for(int i = 0; i < received && i < 20; i++)
498 unsigned int a = ((const unsigned char *) data)[i];
499 DEBUGPRINT("%.2X", a);
504 dstream << std::endl;
510 int UDPSocket::GetHandle()
515 void UDPSocket::setTimeoutMs(int timeout_ms)
517 m_timeout_ms = timeout_ms;
520 bool UDPSocket::WaitData(int timeout_ms)
525 // Initialize the set
527 FD_SET(m_handle, &readset);
529 // Initialize time out struct
532 tv.tv_usec = timeout_ms * 1000;
535 result = select(m_handle+1, &readset, NULL, NULL, &tv);
539 else if(result < 0 && errno == EINTR)
543 dstream << (int) m_handle << ": Select failed: "
544 << strerror(errno) << std::endl;
547 int e = WSAGetLastError();
548 dstream << (int) m_handle << ": WSAGetLastError()="
550 if(e == 10004 /* = WSAEINTR */)
552 dstream << "WARNING: Ignoring WSAEINTR." << std::endl;
557 throw SocketException("Select failed");
559 else if(FD_ISSET(m_handle, &readset) == false)