]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - net_udp.c
fixed a bunch of signed/unsigned mismatch warnings in newer gcc versions (mostly...
[xonotic/darkplaces.git] / net_udp.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 #include "quakedef.h"
21 #include "net_udp.h"
22 #ifdef WIN32
23 #include "winquake.h"
24 #define MAXHOSTNAMELEN          256
25 #else
26 #include <unistd.h>
27 #include <sys/types.h>
28 #include <sys/socket.h>
29 #include <netinet/in.h>
30 #include <arpa/inet.h>
31 #include <netdb.h>
32 #include <sys/param.h>
33 #include <sys/ioctl.h>
34 #include <errno.h>
35
36 #ifdef __sun__
37 #include <sys/filio.h>
38 #endif
39
40 #ifdef NeXT
41 #include <libc.h>
42 #endif
43 #endif
44
45 static int net_acceptsocket = -1;               // socket for fielding new connections
46 static int net_controlsocket;
47 static int net_broadcastsocket = 0;
48 static struct qsockaddr broadcastaddr;
49
50 static union {unsigned int i;unsigned char d[4];} myAddr;
51
52 //=============================================================================
53
54 #ifdef WIN32
55 WSADATA         winsockdata;
56 #endif
57
58 int UDP_Init (void)
59 {
60         int i, j;
61         struct hostent *local;
62         char buff[MAXHOSTNAMELEN];
63
64         if (COM_CheckParm ("-noudp"))
65                 return -1;
66
67 #ifdef WIN32
68         if (WSAStartup (MAKEWORD(1, 1), &winsockdata))
69         {
70                 Con_SafePrintf ("Winsock initialization failed.\n");
71                 return -1;
72         }
73 #endif
74
75         // loopback as a worst case fallback
76         myAddr.i = htonl(INADDR_ANY);
77
78         net_controlsocket = -1;
79         for (j = 0;net_controlsocket == -1;j++)
80         {
81                 switch(j)
82                 {
83                 case 0:
84                         if ((i = COM_CheckParm("-ip")) != 0 && i < com_argc)
85                                 myAddr.i = inet_addr(com_argv[i+1]);
86                         break;
87                 case 1:
88                         myAddr.i = htonl(INADDR_ANY);
89                         break;
90                 case 2:
91                         if (gethostname(buff, MAXHOSTNAMELEN) != -1)
92                         {
93                                 buff[MAXHOSTNAMELEN - 1] = 0;
94                                 local = gethostbyname(buff);
95                                 if (local != NULL)
96                                         myAddr.i = *((int *)local->h_addr_list[0]);
97                                 else
98                                         continue;
99                         }
100                         else
101                                 continue;
102                         break;
103                 default:
104                         Con_Printf("UDP_Init: Giving up, UDP networking support disabled.\n");
105 #ifdef WIN32
106                         WSACleanup ();
107 #endif
108                         return -1;
109                 }
110
111                 if (myAddr.i == htonl(INADDR_LOOPBACK))
112                         sprintf(my_tcpip_address, "INADDR_LOOPBACK");
113                 else if (myAddr.i == htonl(INADDR_ANY))
114                         sprintf(my_tcpip_address, "INADDR_ANY");
115                 else if (myAddr.i == htonl(INADDR_NONE))
116                         sprintf(my_tcpip_address, "INADDR_NONE");
117                 else
118                         sprintf(my_tcpip_address, "%d.%d.%d.%d", myAddr.d[0], myAddr.d[1], myAddr.d[2], myAddr.d[3]);
119                 Con_Printf("UDP_Init: Binding to IP Interface Address of %s...  ", my_tcpip_address);
120                 if ((net_controlsocket = UDP_OpenSocket (0)) == -1)
121                         Con_Printf("failed\n");
122                 else
123                         Con_Printf("succeeded\n");
124         }
125
126         ((struct sockaddr_in *)&broadcastaddr)->sin_family = AF_INET;
127         ((struct sockaddr_in *)&broadcastaddr)->sin_addr.s_addr = htonl(INADDR_BROADCAST);
128         ((struct sockaddr_in *)&broadcastaddr)->sin_port = htons((unsigned short)net_hostport);
129
130         Con_Printf("UDP Initialized\n");
131         tcpipAvailable = true;
132
133         return net_controlsocket;
134 }
135
136 //=============================================================================
137
138 void UDP_Shutdown (void)
139 {
140         UDP_Listen (false);
141         UDP_CloseSocket (net_controlsocket);
142 #ifdef WIN32
143         WSACleanup ();
144 #endif
145 }
146
147 //=============================================================================
148
149 void UDP_Listen (qboolean state)
150 {
151         // enable listening
152         if (state)
153         {
154                 if (net_acceptsocket != -1)
155                         return;
156                 if ((net_acceptsocket = UDP_OpenSocket (net_hostport)) == -1)
157                         Sys_Error ("UDP_Listen: Unable to open accept socket\n");
158                 return;
159         }
160
161         // disable listening
162         if (net_acceptsocket == -1)
163                 return;
164         UDP_CloseSocket (net_acceptsocket);
165         net_acceptsocket = -1;
166 }
167
168 //=============================================================================
169
170 int UDP_OpenSocket (int port)
171 {
172         int newsocket;
173         struct sockaddr_in address;
174
175         if ((newsocket = socket (PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
176                 return -1;
177
178         {
179 #ifdef WIN32
180                 u_long _true = 1;
181                 if (ioctlsocket (newsocket, FIONBIO, &_true) == -1)
182                 {
183                         closesocket (newsocket);
184 #else
185                 char _true = 1;
186                 if (ioctl (newsocket, FIONBIO, &_true) == -1)
187                 {
188                         close (newsocket);
189 #endif
190                         Sys_Error("UDP_OpenSocket: unable to do a ioctl FIONBIO on the socket\n");
191                 }
192         }
193
194         address.sin_family = AF_INET;
195         address.sin_addr.s_addr = myAddr.i;
196         address.sin_port = htons((unsigned short)port);
197         if (bind(newsocket, (void *)&address, sizeof(address)) == -1)
198         {
199 #ifdef WIN32
200                 closesocket(newsocket);
201 #else
202                 close(newsocket);
203 #endif
204                 Sys_Error ("UDP_OpenSocket: Unable to bind to %s", UDP_AddrToString((struct qsockaddr *)&address));
205         }
206
207         return newsocket;
208 }
209
210 //=============================================================================
211
212 int UDP_CloseSocket (int socket)
213 {
214         if (net_broadcastsocket == socket)
215                 net_broadcastsocket = 0;
216 #ifdef WIN32
217         return closesocket (socket);
218 #else
219         return close (socket);
220 #endif
221 }
222
223 //=============================================================================
224
225 int UDP_Connect (int socket, struct qsockaddr *addr)
226 {
227         return 0;
228 }
229
230 //=============================================================================
231
232 int UDP_CheckNewConnections (void)
233 {
234         char buf[4096];
235 #ifndef WIN32
236         unsigned long   available;
237         struct sockaddr_in      from;
238         socklen_t                       fromlen;
239 #endif
240
241         if (net_acceptsocket == -1)
242                 return -1;
243
244 #ifdef WIN32
245         if (recvfrom (net_acceptsocket, buf, sizeof(buf), MSG_PEEK, NULL, NULL) >= 0)
246                 return net_acceptsocket;
247 #else
248         if (ioctl (net_acceptsocket, FIONREAD, &available) == -1)
249                 Sys_Error ("UDP: ioctlsocket (FIONREAD) failed\n");
250         if (available)
251                 return net_acceptsocket;
252         recvfrom (net_acceptsocket, buf, 0, 0, (struct sockaddr *) &from, &fromlen);
253 #endif
254         return -1;
255 }
256
257 //=============================================================================
258
259 int UDP_Recv (qbyte *buf, int len, struct qsockaddr *addr)
260 {
261         return UDP_Read (net_acceptsocket, buf, len, addr);
262 }
263
264 //=============================================================================
265
266 int UDP_Send (qbyte *buf, int len, struct qsockaddr *addr)
267 {
268         return UDP_Write (net_acceptsocket, buf, len, addr);
269 }
270
271 //=============================================================================
272
273 int UDP_Read (int socket, qbyte *buf, int len, struct qsockaddr *addr)
274 {
275         int addrlen = sizeof (struct qsockaddr);
276         int ret;
277
278         ret = recvfrom (socket, buf, len, 0, (struct sockaddr *)addr, &addrlen);
279         if (ret == -1)
280         {
281 #ifdef WIN32
282                 int e = WSAGetLastError();
283                 if (e == WSAEWOULDBLOCK || e == WSAECONNREFUSED)
284                         return 0;
285                 Con_Printf("UDP_Read(%i, %p, %i, <%s>): WSAGetLastError == %i\n", socket, buf, len, UDP_AddrToString(addr), e);
286 #else
287                 if (errno == EWOULDBLOCK || errno == ECONNREFUSED)
288                         return 0;
289                 Con_Printf("UDP_Read(%i, %p, %i, <%s>): errno == %i (%s)\n", socket, buf, len, UDP_AddrToString(addr), errno, strerror(errno));
290 #endif
291         }
292         else if (developer_networking.integer)
293         {
294                 Con_Printf("UDP_Read(%i, %p, %i, <%s>) = %i\n", socket, buf, len, UDP_AddrToString(addr), ret);
295                 Com_HexDumpToConsole(buf, ret);
296         }
297
298         return ret;
299 }
300
301 //=============================================================================
302
303 int UDP_MakeSocketBroadcastCapable (int socket)
304 {
305         int i = 1;
306
307         // make this socket broadcast capable
308         if (setsockopt(socket, SOL_SOCKET, SO_BROADCAST, (char *)&i, sizeof(i)) < 0)
309                 return -1;
310         net_broadcastsocket = socket;
311
312         return 0;
313 }
314
315 //=============================================================================
316
317 int UDP_Broadcast (int socket, qbyte *buf, int len)
318 {
319         int ret;
320
321         if (socket != net_broadcastsocket)
322         {
323                 if (net_broadcastsocket != 0)
324                         Sys_Error("Attempted to use multiple broadcasts sockets\n");
325                 ret = UDP_MakeSocketBroadcastCapable (socket);
326                 if (ret == -1)
327                 {
328                         Con_Printf("Unable to make socket broadcast capable\n");
329                         return ret;
330                 }
331         }
332
333         return UDP_Write (socket, buf, len, &broadcastaddr);
334 }
335
336 //=============================================================================
337
338 int UDP_Write (int socket, qbyte *buf, int len, struct qsockaddr *addr)
339 {
340         int ret;
341
342         if (developer_networking.integer)
343         {
344                 Con_Printf("UDP_Write(%i, %p, %i, <%s>)\n", socket, buf, len, UDP_AddrToString(addr));
345                 Com_HexDumpToConsole(buf, len);
346         }
347
348         ret = sendto (socket, buf, len, 0, (struct sockaddr *)addr, sizeof(struct qsockaddr));
349         if (ret == -1)
350         {
351 #ifdef WIN32
352                 int e = WSAGetLastError();
353                 if (e == WSAEWOULDBLOCK)
354                         return 0;
355                 Con_Printf("UDP_Write(%i, %p, %i, <%s>): WSAGetLastError == %i\n", socket, buf, len, UDP_AddrToString(addr), e);
356 #else
357                 if (errno == EWOULDBLOCK)
358                         return 0;
359                 Con_Printf("UDP_Write(%i, %p, %i, <%s>): errno == %i (%s)\n", socket, buf, len, UDP_AddrToString(addr), errno, strerror(errno));
360 #endif
361         }
362         return ret;
363 }
364
365 //=============================================================================
366
367 char *UDP_AddrToString (const struct qsockaddr *addr)
368 {
369         static char buffer[22]; // only 22 needed (3 + 1 + 3 + 1 + 3 + 1 + 3 + 1 + 5 + null)
370         unsigned char *ip = (char *)(&((struct sockaddr_in *)addr)->sin_addr.s_addr);
371         sprintf(buffer, "%d.%d.%d.%d:%d", ip[0], ip[1], ip[2], ip[3], ntohs(((struct sockaddr_in *)addr)->sin_port));
372         return buffer;
373 }
374
375 //=============================================================================
376
377 int UDP_StringToAddr (const char *string, struct qsockaddr *addr)
378 {
379         int ha[4], hp, ipaddr, j, numbers;
380         const char *colon;
381
382         hp = net_hostport;
383         colon = strrchr(string, ':');
384         if (colon)
385         {
386                 hp = atoi(colon + 1);
387                 if (hp == 0)
388                         hp = net_hostport;
389         }
390         numbers = sscanf(string, "%d.%d.%d.%d", &ha[0], &ha[1], &ha[2], &ha[3]);
391         for (ipaddr = 0, j = 0;j < numbers;j++)
392                 ipaddr = (ipaddr << 8) | ha[j];
393         // if the address is incomplete take most important numbers from myAddr
394         if (numbers < 4)
395                 ipaddr |= ntohl(myAddr.i) & (-1 << (numbers * 8));
396
397         addr->sa_family = AF_INET;
398         ((struct sockaddr_in *)addr)->sin_addr.s_addr = htonl(ipaddr);
399         ((struct sockaddr_in *)addr)->sin_port = htons((unsigned short)hp);
400         if (ipaddr == INADDR_ANY)
401                 return -1;
402         else
403                 return 0;
404 }
405
406 //=============================================================================
407
408 int UDP_GetSocketAddr (int socket, struct qsockaddr *addr)
409 {
410         int ret;
411         int addrlen = sizeof(struct qsockaddr);
412         memset(addr, 0, sizeof(struct qsockaddr));
413         ret = getsockname(socket, (struct sockaddr *)addr, &addrlen);
414         if (ret == -1)
415         {
416 #ifdef WIN32
417                 int e = WSAGetLastError();
418                 Con_Printf("UDP_GetSocketAddr: WASGetLastError == %i\n", e);
419 #else
420                 Con_Printf("UDP_GetSocketAddr: errno == %i (%s)\n", errno, strerror(errno));
421 #endif
422         }
423         return ret;
424 }
425
426 //=============================================================================
427
428 int UDP_GetNameFromAddr (const struct qsockaddr *addr, char *name)
429 {
430         struct hostent *hostentry;
431
432         hostentry = gethostbyaddr ((char *)&((struct sockaddr_in *)addr)->sin_addr, sizeof(struct in_addr), AF_INET);
433         if (hostentry)
434         {
435                 strncpy (name, (char *)hostentry->h_name, NET_NAMELEN - 1);
436                 return 0;
437         }
438
439         strcpy (name, UDP_AddrToString (addr));
440         return 0;
441 }
442
443 //=============================================================================
444
445 int UDP_GetAddrFromName(const char *name, struct qsockaddr *addr)
446 {
447         struct hostent *hostentry;
448
449         if (name[0] >= '0' && name[0] <= '9')
450                 return UDP_StringToAddr (name, addr);
451
452         hostentry = gethostbyname (name);
453         if (!hostentry)
454                 return -1;
455
456         addr->sa_family = AF_INET;
457         ((struct sockaddr_in *)addr)->sin_port = htons((unsigned short)net_hostport);
458         ((struct sockaddr_in *)addr)->sin_addr.s_addr = *(int *)hostentry->h_addr_list[0];
459
460         return 0;
461 }
462
463 //=============================================================================
464
465 int UDP_AddrCompare (const struct qsockaddr *addr1, const struct qsockaddr *addr2)
466 {
467         if (addr1->sa_family != addr2->sa_family)
468                 return -1;
469
470         if (((struct sockaddr_in *)addr1)->sin_addr.s_addr != ((struct sockaddr_in *)addr2)->sin_addr.s_addr)
471                 return -1;
472
473         if (((struct sockaddr_in *)addr1)->sin_port != ((struct sockaddr_in *)addr2)->sin_port)
474                 return 1;
475
476         return 0;
477 }
478
479 //=============================================================================
480
481 int UDP_GetSocketPort (struct qsockaddr *addr)
482 {
483         return ntohs(((struct sockaddr_in *)addr)->sin_port);
484 }
485
486
487 int UDP_SetSocketPort (struct qsockaddr *addr, int port)
488 {
489         ((struct sockaddr_in *)addr)->sin_port = htons((unsigned short)port);
490         return 0;
491 }
492