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