]> git.lizzy.rs Git - dragonfireclient.git/blob - src/socket.cpp
Replace SimpleThread by JThread now implementing same features
[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 #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         setAddress(address);
102         setPort(port);
103 }
104
105 Address::Address(u8 a, u8 b, u8 c, u8 d, u16 port)
106 {
107         setAddress(a, b, c, d);
108         setPort(port);
109 }
110
111 Address::Address(const IPv6AddressBytes * ipv6_bytes, u16 port)
112 {
113         setAddress(ipv6_bytes);
114         setPort(port);
115 }
116
117 // Equality (address family, address and port must be equal)
118 bool Address::operator==(Address &address)
119 {
120         if(address.m_addr_family != m_addr_family || address.m_port != m_port)
121                 return false;
122         else if(m_addr_family == AF_INET)
123         {
124                 return m_address.ipv4.sin_addr.s_addr ==
125                        address.m_address.ipv4.sin_addr.s_addr;
126         }
127         else if(m_addr_family == AF_INET6)
128         {
129                 return memcmp(m_address.ipv6.sin6_addr.s6_addr,
130                               address.m_address.ipv6.sin6_addr.s6_addr, 16) == 0;
131         }
132         else
133                 return false;
134 }
135
136 bool Address::operator!=(Address &address)
137 {
138         return !(*this == address);
139 }
140
141 void Address::Resolve(const char *name)
142 {
143         struct addrinfo *resolved, hints;
144         memset(&hints, 0, sizeof(hints));
145         
146         // Setup hints
147         hints.ai_socktype = 0;
148         hints.ai_protocol = 0;
149         hints.ai_flags    = 0;
150         if(g_settings->getBool("enable_ipv6"))
151         {
152                 // AF_UNSPEC allows both IPv6 and IPv4 addresses to be returned
153                 hints.ai_family = AF_UNSPEC;
154         }
155         else
156         {
157                 hints.ai_family = AF_INET;
158         }
159         
160         // Do getaddrinfo()
161         int e = getaddrinfo(name, NULL, &hints, &resolved);
162         if(e != 0)
163                 throw ResolveError(gai_strerror(e));
164
165         // Copy data
166         if(resolved->ai_family == AF_INET)
167         {
168                 struct sockaddr_in *t = (struct sockaddr_in *) resolved->ai_addr;
169                 m_addr_family = AF_INET;
170                 m_address.ipv4 = *t;
171         }
172         else if(resolved->ai_family == AF_INET6)
173         {
174                 struct sockaddr_in6 *t = (struct sockaddr_in6 *) resolved->ai_addr;
175                 m_addr_family = AF_INET6;
176                 m_address.ipv6 = *t;
177         }
178         else
179         {
180                 freeaddrinfo(resolved);
181                 throw ResolveError("");
182         }
183         freeaddrinfo(resolved);
184 }
185
186 // IP address -> textual representation
187 std::string Address::serializeString() const
188 {
189 // windows XP doesnt have inet_ntop, maybe use better func
190 #ifdef _WIN32
191         if(m_addr_family == AF_INET)
192         {
193                 u8 a, b, c, d, addr;
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);
200         }
201         else if(m_addr_family == AF_INET6)
202         {
203                 std::ostringstream os;
204                 for(int i = 0; i < 16; i += 2)
205                 {
206                         u16 section =
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;
210                         if(i < 14)
211                                 os << ":";
212                 }
213                 return os.str();
214         }
215         else
216                 return std::string("");
217 #else
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("");
221         }
222         return std::string(str);
223 #endif
224 }
225
226 struct sockaddr_in Address::getAddress() const
227 {
228         return m_address.ipv4; // NOTE: NO PORT INCLUDED, use getPort()
229 }
230
231 struct sockaddr_in6 Address::getAddress6() const
232 {
233         return m_address.ipv6; // NOTE: NO PORT INCLUDED, use getPort()
234 }
235
236 u16 Address::getPort() const
237 {
238         return m_port;
239 }
240
241 int Address::getFamily() const
242 {
243         return m_addr_family;
244 }
245
246 bool Address::isIPv6() const
247 {
248         return m_addr_family == AF_INET6;
249 }
250
251 void Address::setAddress(u32 address)
252 {
253         m_addr_family = AF_INET;
254         m_address.ipv4.sin_family = AF_INET;
255         m_address.ipv4.sin_addr.s_addr = htonl(address);
256 }
257
258 void Address::setAddress(u8 a, u8 b, u8 c, u8 d)
259 {
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;
264 }
265
266 void Address::setAddress(const IPv6AddressBytes * ipv6_bytes)
267 {
268         m_addr_family = AF_INET6;
269         m_address.ipv6.sin6_family = AF_INET6;
270         if(ipv6_bytes)
271                 memcpy(m_address.ipv6.sin6_addr.s6_addr, ipv6_bytes->bytes, 16);
272         else
273                 memset(m_address.ipv6.sin6_addr.s6_addr, 0, 16);
274 }
275
276 void Address::setPort(u16 port)
277 {
278         m_port = port;
279 }
280
281 void Address::print(std::ostream *s) const
282 {
283         if(m_addr_family == AF_INET6)
284         {
285                 (*s) << "[" << serializeString() << "]:" << m_port;
286         }
287         else
288         {
289                 (*s) << serializeString() << ":" << m_port;
290         }
291 }
292
293 /*
294         UDPSocket
295 */
296
297 UDPSocket::UDPSocket(bool ipv6)
298 {
299         if(g_sockets_initialized == false)
300                 throw SocketException("Sockets not initialized");
301
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);
305         
306         if(socket_enable_debug_output)
307         {
308                 dstream << "UDPSocket(" << (int) m_handle
309                         << ")::UDPSocket(): ipv6 = "
310                         << (ipv6 ? "true" : "false")
311                         << std::endl;
312         }
313
314         if(m_handle <= 0)
315         {
316                 throw SocketException("Failed to create socket");
317         }
318
319         setTimeoutMs(0);
320 }
321
322 UDPSocket::~UDPSocket()
323 {
324         if(socket_enable_debug_output)
325         {
326                 dstream << "UDPSocket( " << (int) m_handle << ")::~UDPSocket()"
327                         << std::endl;
328         }
329
330 #ifdef _WIN32
331         closesocket(m_handle);
332 #else
333         close(m_handle);
334 #endif
335 }
336
337 void UDPSocket::Bind(u16 port)
338 {
339         if(socket_enable_debug_output)
340         {
341                 dstream << "UDPSocket(" << (int) m_handle << ")::Bind(): "
342                         << "port=" << port << std::endl;
343         }
344
345         if(m_addr_family == AF_INET6)
346         {
347                 struct sockaddr_in6 address;
348                 memset(&address, 0, sizeof(address));
349
350                 address.sin6_family = AF_INET6;
351                 address.sin6_addr   = in6addr_any;
352                 address.sin6_port   = htons(port);
353
354                 if(bind(m_handle, (const struct sockaddr *) &address,
355                         sizeof(struct sockaddr_in6)) < 0)
356                 {
357                         dstream << (int) m_handle << ": Bind failed: "
358                                 << strerror(errno) << std::endl;
359                         throw SocketException("Failed to bind socket");
360                 }
361         }
362         else
363         {
364                 struct sockaddr_in address;
365                 memset(&address, 0, sizeof(address));
366
367                 address.sin_family      = AF_INET;
368                 address.sin_addr.s_addr = INADDR_ANY;
369                 address.sin_port        = htons(port);
370
371                 if(bind(m_handle, (const struct sockaddr *) &address,
372                         sizeof(struct sockaddr_in)) < 0)
373                 {
374                         dstream << (int) m_handle << ": Bind failed: "
375                                 << strerror(errno) << std::endl;
376                         throw SocketException("Failed to bind socket");
377                 }
378         }
379 }
380
381 void UDPSocket::Send(const Address & destination, const void * data, int size)
382 {
383         bool dumping_packet = false; // for INTERNET_SIMULATOR
384
385         if(INTERNET_SIMULATOR)
386                 dumping_packet = (myrand() % INTERNET_SIMULATOR_PACKET_LOSS == 0);
387
388         if(socket_enable_debug_output)
389         {
390                 // Print packet destination and size
391                 dstream << (int) m_handle << " -> ";
392                 destination.print(&dstream);
393                 dstream << ", size=" << size;
394                 
395                 // Print packet contents
396                 dstream << ", data=";
397                 for(int i = 0; i < size && i < 20; i++)
398                 {
399                         if(i % 2 == 0)
400                                 dstream << " ";
401                         unsigned int a = ((const unsigned char *) data)[i];
402                         dstream << std::hex << std::setw(2) << std::setfill('0')
403                                 << a;
404                 }
405                 
406                 if(size > 20)
407                         dstream << "...";
408                 
409                 if(dumping_packet)
410                         dstream << " (DUMPED BY INTERNET_SIMULATOR)";
411                 
412                 dstream << std::endl;
413         }
414
415         if(dumping_packet)
416         {
417                 // Lol let's forget it
418                 dstream << "UDPSocket::Send(): "
419                                    "INTERNET_SIMULATOR: dumping packet."
420                                 << std::endl;
421                 return;
422         }
423
424         if(destination.getFamily() != m_addr_family)
425                 throw SendFailedException("Address family mismatch");
426
427         int sent;
428         if(m_addr_family == AF_INET6)
429         {
430                 struct sockaddr_in6 address = destination.getAddress6();
431                 address.sin6_port = htons(destination.getPort());
432                 sent = sendto(m_handle, (const char *) data, size,
433                         0, (struct sockaddr *) &address, sizeof(struct sockaddr_in6));
434         }
435         else
436         {
437                 struct sockaddr_in address = destination.getAddress();
438                 address.sin_port = htons(destination.getPort());
439                 sent = sendto(m_handle, (const char *) data, size,
440                         0, (struct sockaddr *) &address, sizeof(struct sockaddr_in));
441         }
442
443         if(sent != size)
444         {
445                 throw SendFailedException("Failed to send packet");
446         }
447 }
448
449 int UDPSocket::Receive(Address & sender, void * data, int size)
450 {
451         // Return on timeout
452         if(WaitData(m_timeout_ms) == false)
453         {
454                 return -1;
455         }
456
457         int received;
458         if(m_addr_family == AF_INET6)
459         {
460                 struct sockaddr_in6 address;
461                 memset(&address, 0, sizeof(address));
462                 socklen_t address_len = sizeof(address);
463
464                 received = recvfrom(m_handle, (char *) data,
465                                 size, 0, (struct sockaddr *) &address, &address_len);
466
467                 if(received < 0)
468                         return -1;
469
470                 u16 address_port = ntohs(address.sin6_port);
471                 IPv6AddressBytes bytes;
472                 memcpy(bytes.bytes, address.sin6_addr.s6_addr, 16);
473                 sender = Address(&bytes, address_port);
474         }
475         else
476         {
477                 struct sockaddr_in address;
478                 memset(&address, 0, sizeof(address));
479
480                 socklen_t address_len = sizeof(address);
481
482                 received = recvfrom(m_handle, (char *) data,
483                                 size, 0, (struct sockaddr *) &address, &address_len);
484
485                 if(received < 0)
486                         return -1;
487
488                 u32 address_ip = ntohl(address.sin_addr.s_addr);
489                 u16 address_port = ntohs(address.sin_port);
490
491                 sender = Address(address_ip, address_port);
492         }
493
494         if(socket_enable_debug_output)
495         {
496                 // Print packet sender and size
497                 dstream << (int) m_handle << " <- ";
498                 sender.print(&dstream);
499                 dstream << ", size=" << received;
500                 
501                 // Print packet contents
502                 dstream << ", data=";
503                 for(int i = 0; i < received && i < 20; i++)
504                 {
505                         if(i % 2 == 0)
506                                 dstream << " ";
507                         unsigned int a = ((const unsigned char *) data)[i];
508                         dstream << std::hex << std::setw(2) << std::setfill('0')
509                                 << a;
510                 }
511                 if(received > 20)
512                         dstream << "...";
513                 
514                 dstream << std::endl;
515         }
516
517         return received;
518 }
519
520 int UDPSocket::GetHandle()
521 {
522         return m_handle;
523 }
524
525 void UDPSocket::setTimeoutMs(int timeout_ms)
526 {
527         m_timeout_ms = timeout_ms;
528 }
529
530 bool UDPSocket::WaitData(int timeout_ms)
531 {
532         fd_set readset;
533         int result;
534
535         // Initialize the set
536         FD_ZERO(&readset);
537         FD_SET(m_handle, &readset);
538
539         // Initialize time out struct
540         struct timeval tv;
541         tv.tv_sec = 0;
542         tv.tv_usec = timeout_ms * 1000;
543
544         // select()
545         result = select(m_handle+1, &readset, NULL, NULL, &tv);
546
547         if(result == 0)
548                 return false;
549         else if(result < 0 && errno == EINTR)
550                 return false;
551         else if(result < 0)
552         {
553                 dstream << (int) m_handle << ": Select failed: "
554                         << strerror(errno) << std::endl;
555
556 #ifdef _WIN32
557                 int e = WSAGetLastError();
558                 dstream << (int) m_handle << ": WSAGetLastError()="
559                         << e << std::endl;
560                 if(e == 10004 /* = WSAEINTR */)
561                 {
562                         dstream << "WARNING: Ignoring WSAEINTR." << std::endl;
563                         return false;
564                 }
565 #endif
566
567                 throw SocketException("Select failed");
568         }
569         else if(FD_ISSET(m_handle, &readset) == false)
570         {
571                 // No data
572                 return false;
573         }
574         
575         // There is data
576         return true;
577 }