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