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