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