]> git.lizzy.rs Git - dragonfireclient.git/blob - src/socket.cpp
Omnicleanup: header cleanup, add ModApiUtil shared between game and mainmenu
[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                 address.sin6_family = AF_INET6;
349                 address.sin6_addr   = in6addr_any;
350                 address.sin6_port   = htons(port);
351
352                 if(bind(m_handle, (const struct sockaddr *) &address,
353                         sizeof(struct sockaddr_in6)) < 0)
354                 {
355                         dstream << (int) m_handle << ": Bind failed: "
356                                 << strerror(errno) << std::endl;
357                         throw SocketException("Failed to bind socket");
358                 }
359         }
360         else
361         {
362                 struct sockaddr_in address;
363                 address.sin_family      = AF_INET;
364                 address.sin_addr.s_addr = INADDR_ANY;
365                 address.sin_port        = htons(port);
366
367                 if(bind(m_handle, (const struct sockaddr *) &address,
368                         sizeof(struct sockaddr_in)) < 0)
369                 {
370                         dstream << (int) m_handle << ": Bind failed: "
371                                 << strerror(errno) << std::endl;
372                         throw SocketException("Failed to bind socket");
373                 }
374         }
375 }
376
377 void UDPSocket::Send(const Address & destination, const void * data, int size)
378 {
379         bool dumping_packet = false; // for INTERNET_SIMULATOR
380
381         if(INTERNET_SIMULATOR)
382                 dumping_packet = (myrand() % INTERNET_SIMULATOR_PACKET_LOSS == 0);
383
384         if(socket_enable_debug_output)
385         {
386                 // Print packet destination and size
387                 dstream << (int) m_handle << " -> ";
388                 destination.print(&dstream);
389                 dstream << ", size=" << size;
390                 
391                 // Print packet contents
392                 dstream << ", data=";
393                 for(int i = 0; i < size && i < 20; i++)
394                 {
395                         if(i % 2 == 0)
396                                 dstream << " ";
397                         unsigned int a = ((const unsigned char *) data)[i];
398                         dstream << std::hex << std::setw(2) << std::setfill('0')
399                                 << a;
400                 }
401                 
402                 if(size > 20)
403                         dstream << "...";
404                 
405                 if(dumping_packet)
406                         dstream << " (DUMPED BY INTERNET_SIMULATOR)";
407                 
408                 dstream << std::endl;
409         }
410
411         if(dumping_packet)
412         {
413                 // Lol let's forget it
414                 dstream << "UDPSocket::Send(): "
415                                    "INTERNET_SIMULATOR: dumping packet."
416                                 << std::endl;
417                 return;
418         }
419
420         if(destination.getFamily() != m_addr_family)
421                 throw SendFailedException("Address family mismatch");
422
423         int sent;
424         if(m_addr_family == AF_INET6)
425         {
426                 struct sockaddr_in6 address = destination.getAddress6();
427                 address.sin6_port = htons(destination.getPort());
428                 sent = sendto(m_handle, (const char *) data, size,
429                         0, (struct sockaddr *) &address, sizeof(struct sockaddr_in6));
430         }
431         else
432         {
433                 struct sockaddr_in address = destination.getAddress();
434                 address.sin_port = htons(destination.getPort());
435                 sent = sendto(m_handle, (const char *) data, size,
436                         0, (struct sockaddr *) &address, sizeof(struct sockaddr_in));
437         }
438
439         if(sent != size)
440         {
441                 throw SendFailedException("Failed to send packet");
442         }
443 }
444
445 int UDPSocket::Receive(Address & sender, void * data, int size)
446 {
447         // Return on timeout
448         if(WaitData(m_timeout_ms) == false)
449         {
450                 return -1;
451         }
452
453         int received;
454         if(m_addr_family == AF_INET6)
455         {
456                 struct sockaddr_in6 address;
457                 socklen_t address_len = sizeof(address);
458
459                 received = recvfrom(m_handle, (char *) data,
460                                 size, 0, (struct sockaddr *) &address, &address_len);
461
462                 if(received < 0)
463                         return -1;
464
465                 u16 address_port = ntohs(address.sin6_port);
466                 IPv6AddressBytes bytes;
467                 memcpy(bytes.bytes, address.sin6_addr.s6_addr, 16);
468                 sender = Address(&bytes, address_port);
469         }
470         else
471         {
472                 struct sockaddr_in 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                 u32 address_ip = ntohl(address.sin_addr.s_addr);
482                 u16 address_port = ntohs(address.sin_port);
483
484                 sender = Address(address_ip, address_port);
485         }
486
487         if(socket_enable_debug_output)
488         {
489                 // Print packet sender and size
490                 dstream << (int) m_handle << " <- ";
491                 sender.print(&dstream);
492                 dstream << ", size=" << received;
493                 
494                 // Print packet contents
495                 dstream << ", data=";
496                 for(int i = 0; i < received && i < 20; i++)
497                 {
498                         if(i % 2 == 0)
499                                 dstream << " ";
500                         unsigned int a = ((const unsigned char *) data)[i];
501                         dstream << std::hex << std::setw(2) << std::setfill('0')
502                                 << a;
503                 }
504                 if(received > 20)
505                         dstream << "...";
506                 
507                 dstream << std::endl;
508         }
509
510         return received;
511 }
512
513 int UDPSocket::GetHandle()
514 {
515         return m_handle;
516 }
517
518 void UDPSocket::setTimeoutMs(int timeout_ms)
519 {
520         m_timeout_ms = timeout_ms;
521 }
522
523 bool UDPSocket::WaitData(int timeout_ms)
524 {
525         fd_set readset;
526         int result;
527
528         // Initialize the set
529         FD_ZERO(&readset);
530         FD_SET(m_handle, &readset);
531
532         // Initialize time out struct
533         struct timeval tv;
534         tv.tv_sec = 0;
535         tv.tv_usec = timeout_ms * 1000;
536
537         // select()
538         result = select(m_handle+1, &readset, NULL, NULL, &tv);
539
540         if(result == 0)
541                 return false;
542         else if(result < 0 && errno == EINTR)
543                 return false;
544         else if(result < 0)
545         {
546                 dstream << (int) m_handle << ": Select failed: "
547                         << strerror(errno) << std::endl;
548
549 #ifdef _WIN32
550                 int e = WSAGetLastError();
551                 dstream << (int) m_handle << ": WSAGetLastError()="
552                         << e << std::endl;
553                 if(e == 10004 /* = WSAEINTR */)
554                 {
555                         dstream << "WARNING: Ignoring WSAEINTR." << std::endl;
556                         return false;
557                 }
558 #endif
559
560                 throw SocketException("Select failed");
561         }
562         else if(FD_ISSET(m_handle, &readset) == false)
563         {
564                 // No data
565                 return false;
566         }
567         
568         // There is data
569         return true;
570 }
571
572