reorganized a lot of stuff and modified mapgen and objects slightly while doing it
[oweals/minetest.git] / src / socket.cpp
1 /*
2 Minetest-c55
3 Copyright (C) 2010 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 General Public License as published by
7 the Free Software Foundation; either version 2 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 General Public License for more details.
14
15 You should have received a copy of the GNU 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 #include "debug.h"
22 #include <stdio.h>
23 #include <iostream>
24 #include <stdlib.h>
25 #include <errno.h>
26 #include "utility.h"
27
28 // Debug printing options
29 // Set to 1 for debug output
30 #define DP 0
31 // This is prepended to everything printed here
32 #define DPS ""
33
34 bool g_sockets_initialized = false;
35
36 void sockets_init()
37 {
38 #ifdef _WIN32
39         WSADATA WsaData;
40         if(WSAStartup( MAKEWORD(2,2), &WsaData ) != NO_ERROR)
41                 throw SocketException("WSAStartup failed");
42 #else
43 #endif
44         g_sockets_initialized = true;
45 }
46
47 void sockets_cleanup()
48 {
49 #ifdef _WIN32
50         WSACleanup();
51 #endif
52 }
53
54 Address::Address()
55 {
56         m_address = 0;
57         m_port = 0;
58 }
59
60 Address::Address(unsigned int address, unsigned short port)
61 {
62         m_address = address;
63         m_port = port;
64 }
65
66 Address::Address(unsigned int a, unsigned int b,
67                 unsigned int c, unsigned int d,
68                 unsigned short port)
69 {
70         m_address = (a<<24) | (b<<16) | ( c<<8) | d;
71         m_port = port;
72 }
73
74 bool Address::operator==(Address &address)
75 {
76         return (m_address == address.m_address
77                         && m_port == address.m_port);
78 }
79
80 bool Address::operator!=(Address &address)
81 {
82         return !(*this == address);
83 }
84
85 void Address::Resolve(const char *name)
86 {
87         struct addrinfo *resolved;
88         int e = getaddrinfo(name, NULL, NULL, &resolved);
89         if(e != 0)
90                 throw ResolveError("");
91         /*
92                 FIXME: This is an ugly hack; change the whole class
93                 to store the address as sockaddr
94         */
95         struct sockaddr_in *t = (struct sockaddr_in*)resolved->ai_addr;
96         m_address = ntohl(t->sin_addr.s_addr);
97         freeaddrinfo(resolved);
98 }
99
100 unsigned int Address::getAddress() const
101 {
102         return m_address;
103 }
104
105 unsigned short Address::getPort() const
106 {
107         return m_port;
108 }
109
110 void Address::setAddress(unsigned int address)
111 {
112         m_address = address;
113 }
114
115 void Address::setAddress(unsigned int a, unsigned int b,
116                 unsigned int c, unsigned int d)
117 {
118         m_address = (a<<24) | (b<<16) | ( c<<8) | d;
119 }
120
121 void Address::setPort(unsigned short port)
122 {
123         m_port = port;
124 }
125
126 void Address::print(std::ostream *s) const
127 {
128         (*s)<<((m_address>>24)&0xff)<<"."
129                         <<((m_address>>16)&0xff)<<"."
130                         <<((m_address>>8)&0xff)<<"."
131                         <<((m_address>>0)&0xff)<<":"
132                         <<m_port;
133 }
134
135 void Address::print() const
136 {
137         print(&dstream);
138 }
139
140 UDPSocket::UDPSocket()
141 {
142         if(g_sockets_initialized == false)
143                 throw SocketException("Sockets not initialized");
144         
145     m_handle = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
146         
147         if(DP)
148         dstream<<DPS<<"UDPSocket("<<(int)m_handle<<")::UDPSocket()"<<std::endl;
149         
150     if(m_handle <= 0)
151     {
152                 throw SocketException("Failed to create socket");
153     }
154
155 /*#ifdef _WIN32
156         DWORD nonblocking = 0;
157         if(ioctlsocket(m_handle, FIONBIO, &nonblocking) != 0)
158         {
159                 throw SocketException("Failed set non-blocking mode");
160         }
161 #else
162         int nonblocking = 0;
163         if(fcntl(m_handle, F_SETFL, O_NONBLOCK, nonblocking) == -1)
164         {
165                 throw SocketException("Failed set non-blocking mode");
166         }
167 #endif*/
168
169         setTimeoutMs(0);
170 }
171
172 UDPSocket::~UDPSocket()
173 {
174         if(DP)
175         dstream<<DPS<<"UDPSocket("<<(int)m_handle<<")::~UDPSocket()"<<std::endl;
176
177 #ifdef _WIN32
178         closesocket(m_handle);
179 #else
180         close(m_handle);
181 #endif
182 }
183
184 void UDPSocket::Bind(unsigned short port)
185 {
186         if(DP)
187         dstream<<DPS<<"UDPSocket("<<(int)m_handle
188                         <<")::Bind(): port="<<port<<std::endl;
189
190     sockaddr_in address;
191     address.sin_family = AF_INET;
192     address.sin_addr.s_addr = INADDR_ANY;
193     address.sin_port = htons(port);
194
195     if(bind(m_handle, (const sockaddr*)&address, sizeof(sockaddr_in)) < 0)
196     {
197 #ifndef DISABLE_ERRNO
198                 dstream<<(int)m_handle<<": Bind failed: "<<strerror(errno)<<std::endl;
199 #endif
200                 throw SocketException("Failed to bind socket");
201     }
202 }
203
204 void UDPSocket::Send(const Address & destination, const void * data, int size)
205 {
206         bool dumping_packet = false;
207         if(INTERNET_SIMULATOR)
208                 dumping_packet = (myrand()%10==0); //easy
209                 //dumping_packet = (myrand()%4==0); // hard
210
211         if(DP){
212                 /*dstream<<DPS<<"UDPSocket("<<(int)m_handle
213                                 <<")::Send(): destination=";*/
214                 dstream<<DPS;
215                 dstream<<(int)m_handle<<" -> ";
216                 destination.print();
217                 dstream<<", size="<<size<<", data=";
218                 for(int i=0; i<size && i<20; i++){
219                         if(i%2==0) DEBUGPRINT(" ");
220                         DEBUGPRINT("%.2X", ((int)((const char*)data)[i])&0xff);
221                 }
222                 if(size>20)
223                         dstream<<"...";
224                 if(dumping_packet)
225                         dstream<<" (DUMPED BY INTERNET_SIMULATOR)";
226                 dstream<<std::endl;
227         }
228         else if(dumping_packet)
229         {
230                 // Lol let's forget it
231                 dstream<<"UDPSocket::Send(): "
232                                 "INTERNET_SIMULATOR: dumping packet."
233                                 <<std::endl;
234         }
235
236         if(dumping_packet)
237                 return;
238
239         sockaddr_in address;
240         address.sin_family = AF_INET;
241         address.sin_addr.s_addr = htonl(destination.getAddress());
242         address.sin_port = htons(destination.getPort());
243
244         int sent = sendto(m_handle, (const char*)data, size,
245                 0, (sockaddr*)&address, sizeof(sockaddr_in));
246
247     if(sent != size)
248     {
249                 throw SendFailedException("Failed to send packet");
250     }
251 }
252
253 int UDPSocket::Receive(Address & sender, void * data, int size)
254 {
255         if(WaitData(m_timeout_ms) == false)
256         {
257                 return -1;
258         }
259
260         sockaddr_in address;
261         socklen_t address_len = sizeof(address);
262
263         int received = recvfrom(m_handle, (char*)data,
264                         size, 0, (sockaddr*)&address, &address_len);
265
266         if(received < 0)
267                 return -1;
268
269         unsigned int address_ip = ntohl(address.sin_addr.s_addr);
270         unsigned int address_port = ntohs(address.sin_port);
271
272         sender = Address(address_ip, address_port);
273
274         if(DP){
275                 //dstream<<DPS<<"UDPSocket("<<(int)m_handle<<")::Receive(): sender=";
276                 dstream<<DPS<<(int)m_handle<<" <- ";
277                 sender.print();
278                 //dstream<<", received="<<received<<std::endl;
279                 dstream<<", size="<<received<<", data=";
280                 for(int i=0; i<received && i<20; i++){
281                         if(i%2==0) DEBUGPRINT(" ");
282                         DEBUGPRINT("%.2X", ((int)((const char*)data)[i])&0xff);
283                 }
284                 if(received>20)
285                         dstream<<"...";
286                 dstream<<std::endl;
287         }
288
289         return received;
290 }
291
292 int UDPSocket::GetHandle()
293 {
294         return m_handle;
295 }
296
297 void UDPSocket::setTimeoutMs(int timeout_ms)
298 {
299         m_timeout_ms = timeout_ms;
300 }
301
302 bool UDPSocket::WaitData(int timeout_ms)
303 {
304         fd_set readset;
305         int result;
306
307         // Initialize the set
308         FD_ZERO(&readset);
309         FD_SET(m_handle, &readset);
310
311         // Initialize time out struct
312         struct timeval tv;
313         tv.tv_sec = 0;
314         tv.tv_usec = timeout_ms * 1000;
315         // select()
316         result = select(m_handle+1, &readset, NULL, NULL, &tv);
317
318         if(result == 0){
319                 // Timeout
320                 /*dstream<<"Select timed out (timeout_ms="
321                                 <<timeout_ms<<")"<<std::endl;*/
322                 return false;
323         }
324         else if(result < 0){
325                 // Error
326 #ifndef DISABLE_ERRNO
327                 dstream<<(int)m_handle<<": Select failed: "<<strerror(errno)<<std::endl;
328 #endif
329 #ifdef _WIN32
330                 int e = WSAGetLastError();
331                 dstream<<(int)m_handle<<": WSAGetLastError()="<<e<<std::endl;
332                 if(e == 10004 /*=WSAEINTR*/)
333                 {
334                         dstream<<"WARNING: Ignoring WSAEINTR."<<std::endl;
335                         return false;
336                 }
337 #endif
338                 throw SocketException("Select failed");
339         }
340         else if(FD_ISSET(m_handle, &readset) == false){
341                 // No data
342                 //dstream<<"Select reported no data in m_handle"<<std::endl;
343                 return false;
344         }
345         
346         // There is data
347         //dstream<<"Select reported data in m_handle"<<std::endl;
348         return true;
349 }
350
351