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