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)
105 Address::Address(u8 a, u8 b, u8 c, u8 d, u16 port)
107 setAddress(a, b, c, d);
111 Address::Address(const IPv6AddressBytes * ipv6_bytes, u16 port)
113 setAddress(ipv6_bytes);
117 // Equality (address family, address and port must be equal)
118 bool Address::operator==(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!=(Address &address)
138 return !(*this == address);
141 void Address::Resolve(const char *name)
143 struct addrinfo *resolved, hints;
144 memset(&hints, 0, sizeof(hints));
147 hints.ai_socktype = 0;
148 hints.ai_protocol = 0;
150 if(g_settings->getBool("enable_ipv6"))
152 // AF_UNSPEC allows both IPv6 and IPv4 addresses to be returned
153 hints.ai_family = AF_UNSPEC;
157 hints.ai_family = AF_INET;
161 int e = getaddrinfo(name, NULL, &hints, &resolved);
163 throw ResolveError(gai_strerror(e));
166 if(resolved->ai_family == AF_INET)
168 struct sockaddr_in *t = (struct sockaddr_in *) resolved->ai_addr;
169 m_addr_family = AF_INET;
172 else if(resolved->ai_family == AF_INET6)
174 struct sockaddr_in6 *t = (struct sockaddr_in6 *) resolved->ai_addr;
175 m_addr_family = AF_INET6;
180 freeaddrinfo(resolved);
181 throw ResolveError("");
183 freeaddrinfo(resolved);
186 // IP address -> textual representation
187 std::string Address::serializeString() const
189 // windows XP doesnt have inet_ntop, maybe use better func
191 if(m_addr_family == AF_INET)
194 addr = ntohl(m_address.ipv4.sin_addr.s_addr);
195 a = (addr & 0xFF000000) >> 24;
196 b = (addr & 0x00FF0000) >> 16;
197 c = (addr & 0x0000FF00) >> 8;
198 d = (addr & 0x000000FF);
199 return itos(a) + "." + itos(b) + "." + itos(c) + "." + itos(d);
201 else if(m_addr_family == AF_INET6)
203 std::ostringstream os;
204 for(int i = 0; i < 16; i += 2)
207 (m_address.ipv6.sin6_addr.s6_addr[i] << 8) |
208 (m_address.ipv6.sin6_addr.s6_addr[i + 1]);
209 os << std::hex << section;
216 return std::string("");
218 char str[INET6_ADDRSTRLEN];
219 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) {
220 return std::string("");
222 return std::string(str);
226 struct sockaddr_in Address::getAddress() const
228 return m_address.ipv4; // NOTE: NO PORT INCLUDED, use getPort()
231 struct sockaddr_in6 Address::getAddress6() const
233 return m_address.ipv6; // NOTE: NO PORT INCLUDED, use getPort()
236 u16 Address::getPort() const
241 int Address::getFamily() const
243 return m_addr_family;
246 bool Address::isIPv6() const
248 return m_addr_family == AF_INET6;
251 void Address::setAddress(u32 address)
253 m_addr_family = AF_INET;
254 m_address.ipv4.sin_family = AF_INET;
255 m_address.ipv4.sin_addr.s_addr = htonl(address);
258 void Address::setAddress(u8 a, u8 b, u8 c, u8 d)
260 m_addr_family = AF_INET;
261 m_address.ipv4.sin_family = AF_INET;
262 u32 addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
263 m_address.ipv4.sin_addr.s_addr = addr;
266 void Address::setAddress(const IPv6AddressBytes * ipv6_bytes)
268 m_addr_family = AF_INET6;
269 m_address.ipv6.sin6_family = AF_INET6;
271 memcpy(m_address.ipv6.sin6_addr.s6_addr, ipv6_bytes->bytes, 16);
273 memset(m_address.ipv6.sin6_addr.s6_addr, 0, 16);
276 void Address::setPort(u16 port)
281 void Address::print(std::ostream *s) const
283 if(m_addr_family == AF_INET6)
285 (*s) << "[" << serializeString() << "]:" << m_port;
289 (*s) << serializeString() << ":" << m_port;
297 UDPSocket::UDPSocket(bool ipv6)
299 if(g_sockets_initialized == false)
300 throw SocketException("Sockets not initialized");
302 // Use IPv6 if specified
303 m_addr_family = ipv6 ? AF_INET6 : AF_INET;
304 m_handle = socket(m_addr_family, SOCK_DGRAM, IPPROTO_UDP);
306 if(socket_enable_debug_output)
308 dstream << "UDPSocket(" << (int) m_handle
309 << ")::UDPSocket(): ipv6 = "
310 << (ipv6 ? "true" : "false")
316 throw SocketException("Failed to create socket");
322 UDPSocket::~UDPSocket()
324 if(socket_enable_debug_output)
326 dstream << "UDPSocket( " << (int) m_handle << ")::~UDPSocket()"
331 closesocket(m_handle);
337 void UDPSocket::Bind(u16 port)
339 if(socket_enable_debug_output)
341 dstream << "UDPSocket(" << (int) m_handle << ")::Bind(): "
342 << "port=" << port << std::endl;
345 if(m_addr_family == AF_INET6)
347 struct sockaddr_in6 address;
348 address.sin6_family = AF_INET6;
349 address.sin6_addr = in6addr_any;
350 address.sin6_port = htons(port);
352 if(bind(m_handle, (const struct sockaddr *) &address,
353 sizeof(struct sockaddr_in6)) < 0)
355 dstream << (int) m_handle << ": Bind failed: "
356 << strerror(errno) << std::endl;
357 throw SocketException("Failed to bind socket");
362 struct sockaddr_in address;
363 address.sin_family = AF_INET;
364 address.sin_addr.s_addr = INADDR_ANY;
365 address.sin_port = htons(port);
367 if(bind(m_handle, (const struct sockaddr *) &address,
368 sizeof(struct sockaddr_in)) < 0)
370 dstream << (int) m_handle << ": Bind failed: "
371 << strerror(errno) << std::endl;
372 throw SocketException("Failed to bind socket");
377 void UDPSocket::Send(const Address & destination, const void * data, int size)
379 bool dumping_packet = false; // for INTERNET_SIMULATOR
381 if(INTERNET_SIMULATOR)
382 dumping_packet = (myrand() % INTERNET_SIMULATOR_PACKET_LOSS == 0);
384 if(socket_enable_debug_output)
386 // Print packet destination and size
387 dstream << (int) m_handle << " -> ";
388 destination.print(&dstream);
389 dstream << ", size=" << size;
391 // Print packet contents
392 dstream << ", data=";
393 for(int i = 0; i < size && i < 20; i++)
397 unsigned int a = ((const unsigned char *) data)[i];
398 dstream << std::hex << std::setw(2) << std::setfill('0')
406 dstream << " (DUMPED BY INTERNET_SIMULATOR)";
408 dstream << std::endl;
413 // Lol let's forget it
414 dstream << "UDPSocket::Send(): "
415 "INTERNET_SIMULATOR: dumping packet."
420 if(destination.getFamily() != m_addr_family)
421 throw SendFailedException("Address family mismatch");
424 if(m_addr_family == AF_INET6)
426 struct sockaddr_in6 address = destination.getAddress6();
427 address.sin6_port = htons(destination.getPort());
428 sent = sendto(m_handle, (const char *) data, size,
429 0, (struct sockaddr *) &address, sizeof(struct sockaddr_in6));
433 struct sockaddr_in address = destination.getAddress();
434 address.sin_port = htons(destination.getPort());
435 sent = sendto(m_handle, (const char *) data, size,
436 0, (struct sockaddr *) &address, sizeof(struct sockaddr_in));
441 throw SendFailedException("Failed to send packet");
445 int UDPSocket::Receive(Address & sender, void * data, int size)
448 if(WaitData(m_timeout_ms) == false)
454 if(m_addr_family == AF_INET6)
456 struct sockaddr_in6 address;
457 socklen_t address_len = sizeof(address);
459 received = recvfrom(m_handle, (char *) data,
460 size, 0, (struct sockaddr *) &address, &address_len);
465 u16 address_port = ntohs(address.sin6_port);
466 IPv6AddressBytes bytes;
467 memcpy(bytes.bytes, address.sin6_addr.s6_addr, 16);
468 sender = Address(&bytes, address_port);
472 struct sockaddr_in address;
473 socklen_t address_len = sizeof(address);
475 received = recvfrom(m_handle, (char *) data,
476 size, 0, (struct sockaddr *) &address, &address_len);
481 u32 address_ip = ntohl(address.sin_addr.s_addr);
482 u16 address_port = ntohs(address.sin_port);
484 sender = Address(address_ip, address_port);
487 if(socket_enable_debug_output)
489 // Print packet sender and size
490 dstream << (int) m_handle << " <- ";
491 sender.print(&dstream);
492 dstream << ", size=" << received;
494 // Print packet contents
495 dstream << ", data=";
496 for(int i = 0; i < received && i < 20; i++)
500 unsigned int a = ((const unsigned char *) data)[i];
501 dstream << std::hex << std::setw(2) << std::setfill('0')
507 dstream << std::endl;
513 int UDPSocket::GetHandle()
518 void UDPSocket::setTimeoutMs(int timeout_ms)
520 m_timeout_ms = timeout_ms;
523 bool UDPSocket::WaitData(int timeout_ms)
528 // Initialize the set
530 FD_SET(m_handle, &readset);
532 // Initialize time out struct
535 tv.tv_usec = timeout_ms * 1000;
538 result = select(m_handle+1, &readset, NULL, NULL, &tv);
542 else if(result < 0 && errno == EINTR)
546 dstream << (int) m_handle << ": Select failed: "
547 << strerror(errno) << std::endl;
550 int e = WSAGetLastError();
551 dstream << (int) m_handle << ": WSAGetLastError()="
553 if(e == 10004 /* = WSAEINTR */)
555 dstream << "WARNING: Ignoring WSAEINTR." << std::endl;
560 throw SocketException("Select failed");
562 else if(FD_ISSET(m_handle, &readset) == false)