]> git.lizzy.rs Git - minetest.git/blob - src/socket.cpp
Add an option to disable object <-> object collision for Lua entities
[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 // windows XP doesnt have inet_ntop, maybe use better func
189 #ifdef _WIN32
190         if(m_addr_family == AF_INET)
191         {
192                 u8 a, b, c, d, addr;
193                 addr = ntohl(m_address.ipv4.sin_addr.s_addr);
194                 a = (addr & 0xFF000000) >> 24;
195                 b = (addr & 0x00FF0000) >> 16;
196                 c = (addr & 0x0000FF00) >> 8;
197                 d = (addr & 0x000000FF);
198                 return itos(a) + "." + itos(b) + "." + itos(c) + "." + itos(d);
199         }
200         else if(m_addr_family == AF_INET6)
201         {
202                 std::ostringstream os;
203                 for(int i = 0; i < 16; i += 2)
204                 {
205                         u16 section =
206                         (m_address.ipv6.sin6_addr.s6_addr[i] << 8) |
207                         (m_address.ipv6.sin6_addr.s6_addr[i + 1]);
208                         os << std::hex << section;
209                         if(i < 14)
210                                 os << ":";
211                 }
212                 return os.str();
213         }
214         else
215                 return std::string("");
216 #else
217         char str[INET6_ADDRSTRLEN];
218         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) {
219                 return std::string("");
220         }
221         return std::string(str);
222 #endif
223 }
224
225 struct sockaddr_in Address::getAddress() const
226 {
227         return m_address.ipv4; // NOTE: NO PORT INCLUDED, use getPort()
228 }
229
230 struct sockaddr_in6 Address::getAddress6() const
231 {
232         return m_address.ipv6; // NOTE: NO PORT INCLUDED, use getPort()
233 }
234
235 u16 Address::getPort() const
236 {
237         return m_port;
238 }
239
240 int Address::getFamily() const
241 {
242         return m_addr_family;
243 }
244
245 bool Address::isIPv6() const
246 {
247         return m_addr_family == AF_INET6;
248 }
249
250 void Address::setAddress(u32 address)
251 {
252         m_addr_family = AF_INET;
253         m_address.ipv4.sin_family = AF_INET;
254         m_address.ipv4.sin_addr.s_addr = htonl(address);
255 }
256
257 void Address::setAddress(u8 a, u8 b, u8 c, u8 d)
258 {
259         m_addr_family = AF_INET;
260         m_address.ipv4.sin_family = AF_INET;
261         u32 addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
262         m_address.ipv4.sin_addr.s_addr = addr;
263 }
264
265 void Address::setAddress(const IPv6AddressBytes * ipv6_bytes)
266 {
267         m_addr_family = AF_INET6;
268         m_address.ipv6.sin6_family = AF_INET6;
269         if(ipv6_bytes)
270                 memcpy(m_address.ipv6.sin6_addr.s6_addr, ipv6_bytes->bytes, 16);
271         else
272                 memset(m_address.ipv6.sin6_addr.s6_addr, 0, 16);
273 }
274
275 void Address::setPort(u16 port)
276 {
277         m_port = port;
278 }
279
280 void Address::print(std::ostream *s) const
281 {
282         if(m_addr_family == AF_INET6)
283         {
284                 (*s) << "[" << serializeString() << "]:" << m_port;
285         }
286         else
287         {
288                 (*s) << serializeString() << ":" << m_port;
289         }
290 }
291
292 /*
293         UDPSocket
294 */
295
296 UDPSocket::UDPSocket(bool ipv6)
297 {
298         if(g_sockets_initialized == false)
299                 throw SocketException("Sockets not initialized");
300
301         // Use IPv6 if specified
302         m_addr_family = ipv6 ? AF_INET6 : AF_INET;
303         m_handle = socket(m_addr_family, SOCK_DGRAM, IPPROTO_UDP);
304         
305         if(socket_enable_debug_output)
306         {
307                 dstream << "UDPSocket(" << (int) m_handle
308                         << ")::UDPSocket(): ipv6 = "
309                         << (ipv6 ? "true" : "false")
310                         << std::endl;
311         }
312
313         if(m_handle <= 0)
314         {
315                 throw SocketException("Failed to create socket");
316         }
317
318         setTimeoutMs(0);
319 }
320
321 UDPSocket::~UDPSocket()
322 {
323         if(socket_enable_debug_output)
324         {
325                 dstream << "UDPSocket( " << (int) m_handle << ")::~UDPSocket()"
326                         << std::endl;
327         }
328
329 #ifdef _WIN32
330         closesocket(m_handle);
331 #else
332         close(m_handle);
333 #endif
334 }
335
336 void UDPSocket::Bind(u16 port)
337 {
338         if(socket_enable_debug_output)
339         {
340                 dstream << "UDPSocket(" << (int) m_handle << ")::Bind(): "
341                         << "port=" << port << std::endl;
342         }
343
344         if(m_addr_family == AF_INET6)
345         {
346                 struct sockaddr_in6 address;
347                 address.sin6_family = AF_INET6;
348                 address.sin6_addr   = in6addr_any;
349                 address.sin6_port   = htons(port);
350
351                 if(bind(m_handle, (const struct sockaddr *) &address,
352                         sizeof(struct sockaddr_in6)) < 0)
353                 {
354                         dstream << (int) m_handle << ": Bind failed: "
355                                 << strerror(errno) << std::endl;
356                         throw SocketException("Failed to bind socket");
357                 }
358         }
359         else
360         {
361                 struct sockaddr_in address;
362                 address.sin_family      = AF_INET;
363                 address.sin_addr.s_addr = INADDR_ANY;
364                 address.sin_port        = htons(port);
365
366                 if(bind(m_handle, (const struct sockaddr *) &address,
367                         sizeof(struct sockaddr_in)) < 0)
368                 {
369                         dstream << (int) m_handle << ": Bind failed: "
370                                 << strerror(errno) << std::endl;
371                         throw SocketException("Failed to bind socket");
372                 }
373         }
374 }
375
376 void UDPSocket::Send(const Address & destination, const void * data, int size)
377 {
378         bool dumping_packet = false; // for INTERNET_SIMULATOR
379
380         if(INTERNET_SIMULATOR)
381                 dumping_packet = (myrand() % INTERNET_SIMULATOR_PACKET_LOSS == 0);
382
383         if(socket_enable_debug_output)
384         {
385                 // Print packet destination and size
386                 dstream << (int) m_handle << " -> ";
387                 destination.print(&dstream);
388                 dstream << ", size=" << size;
389                 
390                 // Print packet contents
391                 dstream << ", data=";
392                 for(int i = 0; i < size && i < 20; i++)
393                 {
394                         if(i % 2 == 0)
395                                 DEBUGPRINT(" ");
396                         unsigned int a = ((const unsigned char *) data)[i];
397                         DEBUGPRINT("%.2X", a);
398                 }
399                 
400                 if(size > 20)
401                         dstream << "...";
402                 
403                 if(dumping_packet)
404                         dstream << " (DUMPED BY INTERNET_SIMULATOR)";
405                 
406                 dstream << std::endl;
407         }
408
409         if(dumping_packet)
410         {
411                 // Lol let's forget it
412                 dstream << "UDPSocket::Send(): "
413                                    "INTERNET_SIMULATOR: dumping packet."
414                                 << std::endl;
415                 return;
416         }
417
418         if(destination.getFamily() != m_addr_family)
419                 throw SendFailedException("Address family mismatch");
420
421         int sent;
422         if(m_addr_family == AF_INET6)
423         {
424                 struct sockaddr_in6 address = destination.getAddress6();
425                 address.sin6_port = htons(destination.getPort());
426                 sent = sendto(m_handle, (const char *) data, size,
427                         0, (struct sockaddr *) &address, sizeof(struct sockaddr_in6));
428         }
429         else
430         {
431                 struct sockaddr_in address = destination.getAddress();
432                 address.sin_port = htons(destination.getPort());
433                 sent = sendto(m_handle, (const char *) data, size,
434                         0, (struct sockaddr *) &address, sizeof(struct sockaddr_in));
435         }
436
437         if(sent != size)
438         {
439                 throw SendFailedException("Failed to send packet");
440         }
441 }
442
443 int UDPSocket::Receive(Address & sender, void * data, int size)
444 {
445         // Return on timeout
446         if(WaitData(m_timeout_ms) == false)
447         {
448                 return -1;
449         }
450
451         int received;
452         if(m_addr_family == AF_INET6)
453         {
454                 struct sockaddr_in6 address;
455                 socklen_t address_len = sizeof(address);
456
457                 received = recvfrom(m_handle, (char *) data,
458                                 size, 0, (struct sockaddr *) &address, &address_len);
459
460                 if(received < 0)
461                         return -1;
462
463                 u16 address_port = ntohs(address.sin6_port);
464                 IPv6AddressBytes bytes;
465                 memcpy(bytes.bytes, address.sin6_addr.s6_addr, 16);
466                 sender = Address(&bytes, address_port);
467         }
468         else
469         {
470                 struct sockaddr_in address;
471                 socklen_t address_len = sizeof(address);
472
473                 received = recvfrom(m_handle, (char *) data,
474                                 size, 0, (struct sockaddr *) &address, &address_len);
475
476                 if(received < 0)
477                         return -1;
478
479                 u32 address_ip = ntohl(address.sin_addr.s_addr);
480                 u16 address_port = ntohs(address.sin_port);
481
482                 sender = Address(address_ip, address_port);
483         }
484
485         if(socket_enable_debug_output)
486         {
487                 // Print packet sender and size
488                 dstream << (int) m_handle << " <- ";
489                 sender.print(&dstream);
490                 dstream << ", size=" << received;
491                 
492                 // Print packet contents
493                 dstream << ", data=";
494                 for(int i = 0; i < received && i < 20; i++)
495                 {
496                         if(i % 2 == 0)
497                                 DEBUGPRINT(" ");
498                         unsigned int a = ((const unsigned char *) data)[i];
499                         DEBUGPRINT("%.2X", a);
500                 }
501                 if(received > 20)
502                         dstream << "...";
503                 
504                 dstream << std::endl;
505         }
506
507         return received;
508 }
509
510 int UDPSocket::GetHandle()
511 {
512         return m_handle;
513 }
514
515 void UDPSocket::setTimeoutMs(int timeout_ms)
516 {
517         m_timeout_ms = timeout_ms;
518 }
519
520 bool UDPSocket::WaitData(int timeout_ms)
521 {
522         fd_set readset;
523         int result;
524
525         // Initialize the set
526         FD_ZERO(&readset);
527         FD_SET(m_handle, &readset);
528
529         // Initialize time out struct
530         struct timeval tv;
531         tv.tv_sec = 0;
532         tv.tv_usec = timeout_ms * 1000;
533
534         // select()
535         result = select(m_handle+1, &readset, NULL, NULL, &tv);
536
537         if(result == 0)
538                 return false;
539         else if(result < 0 && errno == EINTR)
540                 return false;
541         else if(result < 0)
542         {
543                 dstream << (int) m_handle << ": Select failed: "
544                         << strerror(errno) << std::endl;
545
546 #ifdef _WIN32
547                 int e = WSAGetLastError();
548                 dstream << (int) m_handle << ": WSAGetLastError()="
549                         << e << std::endl;
550                 if(e == 10004 /* = WSAEINTR */)
551                 {
552                         dstream << "WARNING: Ignoring WSAEINTR." << std::endl;
553                         return false;
554                 }
555 #endif
556
557                 throw SocketException("Select failed");
558         }
559         else if(FD_ISSET(m_handle, &readset) == false)
560         {
561                 // No data
562                 return false;
563         }
564         
565         // There is data
566         return true;
567 }
568
569