00856fb0094133890cf6754ef073d560591ef7a5
[oweals/minetest.git] / src / socket.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
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.
9
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.
14
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.
18 */
19
20 #include "socket.h"
21
22 #ifdef _WIN32
23         #ifndef WIN32_LEAN_AND_MEAN
24                 #define WIN32_LEAN_AND_MEAN
25         #endif
26         // Without this some of the network functions are not found on mingw
27         #ifndef _WIN32_WINNT
28                 #define _WIN32_WINNT 0x0501
29         #endif
30         #include <windows.h>
31         #include <winsock2.h>
32         #include <ws2tcpip.h>
33         #ifdef _MSC_VER
34                 #pragma comment(lib, "ws2_32.lib")
35         #endif
36 typedef SOCKET socket_t;
37 typedef int socklen_t;
38 #else
39         #include <sys/types.h>
40         #include <sys/socket.h>
41         #include <netinet/in.h>
42         #include <fcntl.h>
43         #include <netdb.h>
44         #include <unistd.h>
45         #include <arpa/inet.h>
46 typedef int socket_t;
47 #endif
48
49 #include "constants.h"
50 #include "debug.h"
51 #include "settings.h"
52 #include "main.h" // for g_settings
53 #include <stdio.h>
54 #include <iostream>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <errno.h>
58 #include <sstream>
59 #include <iomanip>
60 #include "util/string.h"
61 #include "util/numeric.h"
62
63 // Set to true to enable verbose debug output
64 bool socket_enable_debug_output = false;
65
66 bool g_sockets_initialized = false;
67
68 // Initialize sockets
69 void sockets_init()
70 {
71 #ifdef _WIN32
72         // Windows needs sockets to be initialized before use
73         WSADATA WsaData;
74         if(WSAStartup( MAKEWORD(2,2), &WsaData ) != NO_ERROR)
75                 throw SocketException("WSAStartup failed");
76 #endif
77         g_sockets_initialized = true;
78 }
79
80 void sockets_cleanup()
81 {
82 #ifdef _WIN32
83         // On Windows, cleanup sockets after use
84         WSACleanup();
85 #endif
86 }
87
88 /*
89         Address
90 */
91
92 Address::Address()
93 {
94         m_addr_family = 0;
95         memset(&m_address, 0, sizeof(m_address));
96         m_port = 0;
97 }
98
99 Address::Address(u32 address, u16 port)
100 {
101         memset(&m_address, 0, sizeof(m_address));
102         setAddress(address);
103         setPort(port);
104 }
105
106 Address::Address(u8 a, u8 b, u8 c, u8 d, u16 port)
107 {
108         memset(&m_address, 0, sizeof(m_address));
109         setAddress(a, b, c, d);
110         setPort(port);
111 }
112
113 Address::Address(const IPv6AddressBytes * ipv6_bytes, u16 port)
114 {
115         memset(&m_address, 0, sizeof(m_address));
116         setAddress(ipv6_bytes);
117         setPort(port);
118 }
119
120 // Equality (address family, address and port must be equal)
121 bool Address::operator==(Address &address)
122 {
123         if(address.m_addr_family != m_addr_family || address.m_port != m_port)
124                 return false;
125         else if(m_addr_family == AF_INET)
126         {
127                 return m_address.ipv4.sin_addr.s_addr ==
128                        address.m_address.ipv4.sin_addr.s_addr;
129         }
130         else if(m_addr_family == AF_INET6)
131         {
132                 return memcmp(m_address.ipv6.sin6_addr.s6_addr,
133                               address.m_address.ipv6.sin6_addr.s6_addr, 16) == 0;
134         }
135         else
136                 return false;
137 }
138
139 bool Address::operator!=(Address &address)
140 {
141         return !(*this == address);
142 }
143
144 void Address::Resolve(const char *name)
145 {
146         struct addrinfo *resolved, hints;
147         memset(&hints, 0, sizeof(hints));
148         
149         // Setup hints
150         hints.ai_socktype = 0;
151         hints.ai_protocol = 0;
152         hints.ai_flags    = 0;
153         if(g_settings->getBool("enable_ipv6"))
154         {
155                 // AF_UNSPEC allows both IPv6 and IPv4 addresses to be returned
156                 hints.ai_family = AF_UNSPEC;
157         }
158         else
159         {
160                 hints.ai_family = AF_INET;
161         }
162         
163         // Do getaddrinfo()
164         int e = getaddrinfo(name, NULL, &hints, &resolved);
165         if(e != 0)
166                 throw ResolveError(gai_strerror(e));
167
168         // Copy data
169         if(resolved->ai_family == AF_INET)
170         {
171                 struct sockaddr_in *t = (struct sockaddr_in *) resolved->ai_addr;
172                 m_addr_family = AF_INET;
173                 m_address.ipv4 = *t;
174         }
175         else if(resolved->ai_family == AF_INET6)
176         {
177                 struct sockaddr_in6 *t = (struct sockaddr_in6 *) resolved->ai_addr;
178                 m_addr_family = AF_INET6;
179                 m_address.ipv6 = *t;
180         }
181         else
182         {
183                 freeaddrinfo(resolved);
184                 throw ResolveError("");
185         }
186         freeaddrinfo(resolved);
187 }
188
189 // IP address -> textual representation
190 std::string Address::serializeString() const
191 {
192 // windows XP doesnt have inet_ntop, maybe use better func
193 #ifdef _WIN32
194         if(m_addr_family == AF_INET)
195         {
196                 u8 a, b, c, d, addr;
197                 addr = ntohl(m_address.ipv4.sin_addr.s_addr);
198                 a = (addr & 0xFF000000) >> 24;
199                 b = (addr & 0x00FF0000) >> 16;
200                 c = (addr & 0x0000FF00) >> 8;
201                 d = (addr & 0x000000FF);
202                 return itos(a) + "." + itos(b) + "." + itos(c) + "." + itos(d);
203         }
204         else if(m_addr_family == AF_INET6)
205         {
206                 std::ostringstream os;
207                 for(int i = 0; i < 16; i += 2)
208                 {
209                         u16 section =
210                         (m_address.ipv6.sin6_addr.s6_addr[i] << 8) |
211                         (m_address.ipv6.sin6_addr.s6_addr[i + 1]);
212                         os << std::hex << section;
213                         if(i < 14)
214                                 os << ":";
215                 }
216                 return os.str();
217         }
218         else
219                 return std::string("");
220 #else
221         char str[INET6_ADDRSTRLEN];
222         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) {
223                 return std::string("");
224         }
225         return std::string(str);
226 #endif
227 }
228
229 struct sockaddr_in Address::getAddress() const
230 {
231         return m_address.ipv4; // NOTE: NO PORT INCLUDED, use getPort()
232 }
233
234 struct sockaddr_in6 Address::getAddress6() const
235 {
236         return m_address.ipv6; // NOTE: NO PORT INCLUDED, use getPort()
237 }
238
239 u16 Address::getPort() const
240 {
241         return m_port;
242 }
243
244 int Address::getFamily() const
245 {
246         return m_addr_family;
247 }
248
249 bool Address::isIPv6() const
250 {
251         return m_addr_family == AF_INET6;
252 }
253
254 void Address::setAddress(u32 address)
255 {
256         m_addr_family = AF_INET;
257         m_address.ipv4.sin_family = AF_INET;
258         m_address.ipv4.sin_addr.s_addr = htonl(address);
259 }
260
261 void Address::setAddress(u8 a, u8 b, u8 c, u8 d)
262 {
263         m_addr_family = AF_INET;
264         m_address.ipv4.sin_family = AF_INET;
265         u32 addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
266         m_address.ipv4.sin_addr.s_addr = addr;
267 }
268
269 void Address::setAddress(const IPv6AddressBytes * ipv6_bytes)
270 {
271         m_addr_family = AF_INET6;
272         m_address.ipv6.sin6_family = AF_INET6;
273         if(ipv6_bytes)
274                 memcpy(m_address.ipv6.sin6_addr.s6_addr, ipv6_bytes->bytes, 16);
275         else
276                 memset(m_address.ipv6.sin6_addr.s6_addr, 0, 16);
277 }
278
279 void Address::setPort(u16 port)
280 {
281         m_port = port;
282 }
283
284 void Address::print(std::ostream *s) const
285 {
286         if(m_addr_family == AF_INET6)
287         {
288                 (*s) << "[" << serializeString() << "]:" << m_port;
289         }
290         else
291         {
292                 (*s) << serializeString() << ":" << m_port;
293         }
294 }
295
296 /*
297         UDPSocket
298 */
299
300 UDPSocket::UDPSocket(bool ipv6)
301 {
302         if(g_sockets_initialized == false)
303                 throw SocketException("Sockets not initialized");
304
305         // Use IPv6 if specified
306         m_addr_family = ipv6 ? AF_INET6 : AF_INET;
307         m_handle = socket(m_addr_family, SOCK_DGRAM, IPPROTO_UDP);
308         
309         if(socket_enable_debug_output)
310         {
311                 dstream << "UDPSocket(" << (int) m_handle
312                         << ")::UDPSocket(): ipv6 = "
313                         << (ipv6 ? "true" : "false")
314                         << std::endl;
315         }
316
317         if(m_handle <= 0)
318         {
319                 throw SocketException("Failed to create socket");
320         }
321
322         setTimeoutMs(0);
323 }
324
325 UDPSocket::~UDPSocket()
326 {
327         if(socket_enable_debug_output)
328         {
329                 dstream << "UDPSocket( " << (int) m_handle << ")::~UDPSocket()"
330                         << std::endl;
331         }
332
333 #ifdef _WIN32
334         closesocket(m_handle);
335 #else
336         close(m_handle);
337 #endif
338 }
339
340 void UDPSocket::Bind(Address addr)
341 {
342         if(socket_enable_debug_output)
343         {
344                 dstream << "UDPSocket(" << (int) m_handle << ")::Bind(): "
345                         << addr.serializeString() << ":"
346                         << addr.getPort() << std::endl;
347         }
348
349         if (addr.getFamily() != m_addr_family)
350         {
351                 char errmsg[] = "Socket and bind address families do not match";
352                 errorstream << "Bind failed: " << errmsg << std::endl;
353                 throw SocketException(errmsg);
354         }
355
356         if(m_addr_family == AF_INET6)
357         {
358                 struct sockaddr_in6 address;
359                 memset(&address, 0, sizeof(address));
360
361                 address             = addr.getAddress6();
362                 address.sin6_family = AF_INET6;
363                 address.sin6_port   = htons(addr.getPort());
364
365                 if(bind(m_handle, (const struct sockaddr *) &address,
366                                 sizeof(struct sockaddr_in6)) < 0)
367                 {
368                         dstream << (int) m_handle << ": Bind failed: "
369                                 << strerror(errno) << std::endl;
370                         throw SocketException("Failed to bind socket");
371                 }
372         }
373         else
374         {
375                 struct sockaddr_in address;
376                 memset(&address, 0, sizeof(address));
377
378                 address                 = addr.getAddress();
379                 address.sin_family      = AF_INET;
380                 address.sin_port        = htons(addr.getPort());
381
382                 if(bind(m_handle, (const struct sockaddr *) &address,
383                         sizeof(struct sockaddr_in)) < 0)
384                 {
385                         dstream << (int) m_handle << ": Bind failed: "
386                                 << strerror(errno) << std::endl;
387                         throw SocketException("Failed to bind socket");
388                 }
389         }
390 }
391
392 void UDPSocket::Send(const Address & destination, const void * data, int size)
393 {
394         bool dumping_packet = false; // for INTERNET_SIMULATOR
395
396         if(INTERNET_SIMULATOR)
397                 dumping_packet = (myrand() % INTERNET_SIMULATOR_PACKET_LOSS == 0);
398
399         if(socket_enable_debug_output)
400         {
401                 // Print packet destination and size
402                 dstream << (int) m_handle << " -> ";
403                 destination.print(&dstream);
404                 dstream << ", size=" << size;
405                 
406                 // Print packet contents
407                 dstream << ", data=";
408                 for(int i = 0; i < size && i < 20; i++)
409                 {
410                         if(i % 2 == 0)
411                                 dstream << " ";
412                         unsigned int a = ((const unsigned char *) data)[i];
413                         dstream << std::hex << std::setw(2) << std::setfill('0')
414                                 << a;
415                 }
416                 
417                 if(size > 20)
418                         dstream << "...";
419                 
420                 if(dumping_packet)
421                         dstream << " (DUMPED BY INTERNET_SIMULATOR)";
422                 
423                 dstream << std::endl;
424         }
425
426         if(dumping_packet)
427         {
428                 // Lol let's forget it
429                 dstream << "UDPSocket::Send(): "
430                                    "INTERNET_SIMULATOR: dumping packet."
431                                 << std::endl;
432                 return;
433         }
434
435         if(destination.getFamily() != m_addr_family)
436                 throw SendFailedException("Address family mismatch");
437
438         int sent;
439         if(m_addr_family == AF_INET6)
440         {
441                 struct sockaddr_in6 address = destination.getAddress6();
442                 address.sin6_port = htons(destination.getPort());
443                 sent = sendto(m_handle, (const char *) data, size,
444                         0, (struct sockaddr *) &address, sizeof(struct sockaddr_in6));
445         }
446         else
447         {
448                 struct sockaddr_in address = destination.getAddress();
449                 address.sin_port = htons(destination.getPort());
450                 sent = sendto(m_handle, (const char *) data, size,
451                         0, (struct sockaddr *) &address, sizeof(struct sockaddr_in));
452         }
453
454         if(sent != size)
455         {
456                 throw SendFailedException("Failed to send packet");
457         }
458 }
459
460 int UDPSocket::Receive(Address & sender, void * data, int size)
461 {
462         // Return on timeout
463         if(WaitData(m_timeout_ms) == false)
464         {
465                 return -1;
466         }
467
468         int received;
469         if(m_addr_family == AF_INET6)
470         {
471                 struct sockaddr_in6 address;
472                 memset(&address, 0, sizeof(address));
473                 socklen_t address_len = sizeof(address);
474
475                 received = recvfrom(m_handle, (char *) data,
476                                 size, 0, (struct sockaddr *) &address, &address_len);
477
478                 if(received < 0)
479                         return -1;
480
481                 u16 address_port = ntohs(address.sin6_port);
482                 IPv6AddressBytes bytes;
483                 memcpy(bytes.bytes, address.sin6_addr.s6_addr, 16);
484                 sender = Address(&bytes, address_port);
485         }
486         else
487         {
488                 struct sockaddr_in address;
489                 memset(&address, 0, sizeof(address));
490
491                 socklen_t address_len = sizeof(address);
492
493                 received = recvfrom(m_handle, (char *) data,
494                                 size, 0, (struct sockaddr *) &address, &address_len);
495
496                 if(received < 0)
497                         return -1;
498
499                 u32 address_ip = ntohl(address.sin_addr.s_addr);
500                 u16 address_port = ntohs(address.sin_port);
501
502                 sender = Address(address_ip, address_port);
503         }
504
505         if(socket_enable_debug_output)
506         {
507                 // Print packet sender and size
508                 dstream << (int) m_handle << " <- ";
509                 sender.print(&dstream);
510                 dstream << ", size=" << received;
511                 
512                 // Print packet contents
513                 dstream << ", data=";
514                 for(int i = 0; i < received && i < 20; i++)
515                 {
516                         if(i % 2 == 0)
517                                 dstream << " ";
518                         unsigned int a = ((const unsigned char *) data)[i];
519                         dstream << std::hex << std::setw(2) << std::setfill('0')
520                                 << a;
521                 }
522                 if(received > 20)
523                         dstream << "...";
524                 
525                 dstream << std::endl;
526         }
527
528         return received;
529 }
530
531 int UDPSocket::GetHandle()
532 {
533         return m_handle;
534 }
535
536 void UDPSocket::setTimeoutMs(int timeout_ms)
537 {
538         m_timeout_ms = timeout_ms;
539 }
540
541 bool UDPSocket::WaitData(int timeout_ms)
542 {
543         fd_set readset;
544         int result;
545
546         // Initialize the set
547         FD_ZERO(&readset);
548         FD_SET(m_handle, &readset);
549
550         // Initialize time out struct
551         struct timeval tv;
552         tv.tv_sec = 0;
553         tv.tv_usec = timeout_ms * 1000;
554
555         // select()
556         result = select(m_handle+1, &readset, NULL, NULL, &tv);
557
558         if(result == 0)
559                 return false;
560         else if(result < 0 && (errno == EINTR || errno == EBADF))
561                 // N.B. select() fails when sockets are destroyed on Connection's dtor
562                 // with EBADF.  Instead of doing tricky synchronization, allow this
563                 // thread to exit but don't throw an exception.
564                 return false;
565         else if(result < 0)
566         {
567                 dstream << (int) m_handle << ": Select failed: "
568                         << strerror(errno) << std::endl;
569
570 #ifdef _WIN32
571                 int e = WSAGetLastError();
572                 dstream << (int) m_handle << ": WSAGetLastError()="
573                         << e << std::endl;
574                 if(e == 10004 /* = WSAEINTR */ || e == 10009 /*WSAEBADF*/)
575                 {
576                         dstream << "WARNING: Ignoring WSAEINTR/WSAEBADF." << std::endl;
577                         return false;
578                 }
579 #endif
580
581                 throw SocketException("Select failed");
582         }
583         else if(FD_ISSET(m_handle, &readset) == false)
584         {
585                 // No data
586                 return false;
587         }
588         
589         // There is data
590         return true;
591 }