]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - lhnet.c
changed the Sys_Error to a Con_Printf. LordHavoc, please check if the equation REALLY...
[xonotic/darkplaces.git] / lhnet.c
1
2 // Written by Forest Hale 2003-06-15 and placed into public domain.
3
4 #ifndef STANDALONETEST
5 #include "quakedef.h"
6 #endif
7
8 #include <stdlib.h>
9 #include <stdio.h>
10 #include <time.h>
11 #include <string.h>
12 #ifdef WIN32
13 #include <winsock.h>
14 #else
15 #include <unistd.h>
16 #include <sys/socket.h>
17 #include <sys/ioctl.h>
18 #include <errno.h>
19 #include <netdb.h>
20 #include <netinet/in.h>
21 #include <arpa/inet.h>
22 #endif
23
24 #ifdef __MORPHOS__
25 #include <proto/socket.h>
26 #endif
27
28 // for Z_Malloc/Z_Free in quake
29 #ifndef STANDALONETEST
30 #include "zone.h"
31 #include "sys.h"
32 #include "netconn.h"
33 #else
34 #define Con_Print printf
35 #define Con_Printf printf
36 #define Z_Malloc malloc
37 #define Z_Free free
38 #endif
39
40 #include "lhnet.h"
41
42 #if defined(WIN32)
43 #define EWOULDBLOCK WSAEWOULDBLOCK
44 #define ECONNREFUSED WSAECONNREFUSED
45
46 #define SOCKETERRNO WSAGetLastError()
47
48 #define IOC_VENDOR 0x18000000
49 #define _WSAIOW(x,y) (IOC_IN|(x)|(y))
50 #define SIO_UDP_CONNRESET _WSAIOW(IOC_VENDOR,12)
51
52 #define SOCKLEN_T int
53 #elif defined(__MORPHOS__)
54 #define ioctlsocket IoctlSocket
55 #define closesocket CloseSocket
56 #define SOCKETERRNO Errno()
57
58 #define SOCKLEN_T int
59 #else
60 #define ioctlsocket ioctl
61 #define closesocket close
62 #define SOCKETERRNO errno
63
64 #define SOCKLEN_T socklen_t
65 #endif
66
67 // to make LHNETADDRESS_FromString resolve repeated hostnames faster, cache them
68 #define MAX_NAMECACHE 64
69 static struct namecache_s
70 {
71         lhnetaddress_t address;
72         double expirationtime;
73         char name[64];
74 }
75 namecache[MAX_NAMECACHE];
76 static int namecacheposition = 0;
77
78 int LHNETADDRESS_FromPort(lhnetaddress_t *address, int addresstype, int port)
79 {
80         if (!address)
81                 return 0;
82         switch(addresstype)
83         {
84         case LHNETADDRESSTYPE_LOOP:
85                 // local:port  (loopback)
86                 memset(address, 0, sizeof(*address));
87                 address->addresstype = LHNETADDRESSTYPE_LOOP;
88                 address->addressdata.loop.port = port;
89                 return 1;
90         case LHNETADDRESSTYPE_INET4:
91                 // 0.0.0.0:port  (INADDR_ANY, binds to all interfaces)
92                 memset(address, 0, sizeof(*address));
93                 address->addresstype = LHNETADDRESSTYPE_INET4;
94                 address->addressdata.inet4.family = LHNETADDRESSTYPE_INET4_FAMILY;
95                 address->addressdata.inet4.port = htons((unsigned short)port);
96                 return 1;
97         case LHNETADDRESSTYPE_INET6:
98                 // [0:0:0:0:0:0:0:0]:port  (IN6ADDR_ANY, binds to all interfaces)
99                 memset(address, 0, sizeof(*address));
100                 address->addresstype = LHNETADDRESSTYPE_INET6;
101                 address->addressdata.inet6.family = LHNETADDRESSTYPE_INET6_FAMILY;
102                 address->addressdata.inet6.port = htons((unsigned short)port);
103                 return 1;
104         }
105         return 0;
106 }
107
108 int LHNETADDRESS_FromString(lhnetaddress_t *address, const char *string, int defaultport)
109 {
110         int i, port, namelen, d1, d2, d3, d4;
111         struct hostent *hostentry;
112         const char *colon;
113         char name[128];
114         if (!address || !string || !*string)
115                 return 0;
116         memset(address, 0, sizeof(*address));
117         address->addresstype = LHNETADDRESSTYPE_NONE;
118         port = 0;
119         colon = strrchr(string, ':');
120         if (colon)
121                 port = atoi(colon + 1);
122         else
123                 colon = string + strlen(string);
124         if (port == 0)
125                 port = defaultport;
126         namelen = colon - string;
127         if (namelen > 127)
128                 namelen = 127;
129         if (string[0] == '[' && namelen > 0 && string[namelen-1] == ']') // ipv6
130         {
131                 string++;
132                 namelen -= 2;
133         }
134         memcpy(name, string, namelen);
135         name[namelen] = 0;
136         // handle loopback
137         if (!strcmp(name, "local"))
138         {
139                 address->addresstype = LHNETADDRESSTYPE_LOOP;
140                 address->addressdata.loop.port = port;
141                 return 1;
142         }
143         // try to parse as dotted decimal ipv4 address first
144         // note this supports partial ip addresses
145         d1 = d2 = d3 = d4 = 0;
146 #if _MSC_VER >= 1400
147 #define sscanf sscanf_s
148 #endif
149         if (sscanf(name, "%d.%d.%d.%d", &d1, &d2, &d3, &d4) >= 1 && (unsigned int)d1 < 256 && (unsigned int)d2 < 256 && (unsigned int)d3 < 256 && (unsigned int)d4 < 256)
150         {
151                 // parsed a valid ipv4 address
152                 address->addresstype = LHNETADDRESSTYPE_INET4;
153                 address->addressdata.inet4.family = LHNETADDRESSTYPE_INET4_FAMILY;
154                 address->addressdata.inet4.port = htons((unsigned short)port);
155                 address->addressdata.inet4.address[0] = (unsigned char)d1;
156                 address->addressdata.inet4.address[1] = (unsigned char)d2;
157                 address->addressdata.inet4.address[2] = (unsigned char)d3;
158                 address->addressdata.inet4.address[3] = (unsigned char)d4;
159 #ifdef STANDALONETEST
160                 printf("manual parsing of ipv4 dotted decimal address \"%s\" successful: %d.%d.%d.%d:%d\n", string, (int)address->addressdata.inet4.address[0], (int)address->addressdata.inet4.address[1], (int)address->addressdata.inet4.address[2], (int)address->addressdata.inet4.address[3], (int)ntohs(address->addressdata.inet4.port));
161 #endif
162                 return 1;
163         }
164         for (i = 0;i < MAX_NAMECACHE;i++)
165                 if (!strcmp(namecache[i].name, name))
166                         break;
167 #ifdef STANDALONETEST
168         if (i < MAX_NAMECACHE)
169 #else
170         if (i < MAX_NAMECACHE && realtime < namecache[i].expirationtime)
171 #endif
172         {
173                 *address = namecache[i].address;
174                 if (address->addresstype == LHNETADDRESSTYPE_INET6)
175                 {
176                         address->addressdata.inet6.port = htons((unsigned short)port);
177                         return 1;
178                 }
179                 else if (address->addresstype == LHNETADDRESSTYPE_INET4)
180                 {
181                         address->addressdata.inet4.port = htons((unsigned short)port);
182                         return 1;
183                 }
184                 return 0;
185         }
186         // try gethostbyname (handles dns and other ip formats)
187         hostentry = gethostbyname(name);
188         if (hostentry)
189         {
190                 if (hostentry->h_addrtype == LHNETADDRESSTYPE_INET6_FAMILY)
191                 {
192                         // great it worked
193                         address->addresstype = LHNETADDRESSTYPE_INET6;
194                         address->addressdata.inet6.family = hostentry->h_addrtype;
195                         address->addressdata.inet6.port = htons((unsigned short)port);
196                         memcpy(address->addressdata.inet6.address, hostentry->h_addr_list[0], sizeof(address->addressdata.inet6.address));
197                         for (i = 0;i < (int)sizeof(namecache[namecacheposition].name)-1 && name[i];i++)
198                                 namecache[namecacheposition].name[i] = name[i];
199                         namecache[namecacheposition].name[i] = 0;
200 #ifndef STANDALONETEST
201                         namecache[namecacheposition].expirationtime = realtime + 12 * 3600; // 12 hours
202 #endif
203                         namecache[namecacheposition].address = *address;
204                         namecacheposition = (namecacheposition + 1) % MAX_NAMECACHE;
205 #ifdef STANDALONETEST
206                         printf("gethostbyname(\"%s\") returned ipv6 address [%x:%x:%x:%x:%x:%x:%x:%x]:%d\n", name, (int)address->addressdata.inet6.address[0], (int)address->addressdata.inet6.address[1], (int)address->addressdata.inet6.address[2], (int)address->addressdata.inet6.address[3], (int)address->addressdata.inet6.address[4], (int)address->addressdata.inet6.address[5], (int)address->addressdata.inet6.address[6], (int)address->addressdata.inet6.address[7], (int)ntohs(address->addressdata.inet6.port));
207 #endif
208                         return 1;
209                 }
210                 else if (hostentry->h_addrtype == LHNETADDRESSTYPE_INET4_FAMILY)
211                 {
212                         // great it worked
213                         address->addresstype = LHNETADDRESSTYPE_INET4;
214                         address->addressdata.inet4.family = hostentry->h_addrtype;
215                         address->addressdata.inet4.port = htons((unsigned short)port);
216                         memcpy(address->addressdata.inet4.address, hostentry->h_addr_list[0], sizeof(address->addressdata.inet4.address));
217                         for (i = 0;i < (int)sizeof(namecache[namecacheposition].name)-1 && name[i];i++)
218                                 namecache[namecacheposition].name[i] = name[i];
219                         namecache[namecacheposition].name[i] = 0;
220 #ifndef STANDALONETEST
221                         namecache[namecacheposition].expirationtime = realtime + 12 * 3600; // 12 hours
222 #endif
223                         namecache[namecacheposition].address = *address;
224                         namecacheposition = (namecacheposition + 1) % MAX_NAMECACHE;
225 #ifdef STANDALONETEST
226                         printf("gethostbyname(\"%s\") returned ipv4 address %d.%d.%d.%d:%d\n", name, (int)address->addressdata.inet4.address[0], (int)address->addressdata.inet4.address[1], (int)address->addressdata.inet4.address[2], (int)address->addressdata.inet4.address[3], (int)ntohs(address->addressdata.inet4.port));
227 #endif
228                         return 1;
229                 }
230         }
231 #ifdef STANDALONETEST
232         printf("gethostbyname failed on address \"%s\"\n", name);
233 #endif
234         for (i = 0;i < (int)sizeof(namecache[namecacheposition].name)-1 && name[i];i++)
235                 namecache[namecacheposition].name[i] = name[i];
236         namecache[namecacheposition].name[i] = 0;
237 #ifndef STANDALONETEST
238         namecache[namecacheposition].expirationtime = realtime + 12 * 3600; // 12 hours
239 #endif
240         namecache[namecacheposition].address.addresstype = LHNETADDRESSTYPE_NONE;
241         namecacheposition = (namecacheposition + 1) % MAX_NAMECACHE;
242         return 0;
243 }
244
245 int LHNETADDRESS_ToString(const lhnetaddress_t *address, char *string, int stringbuffersize, int includeport)
246 {
247         *string = 0;
248         if (!address || !string || stringbuffersize < 1)
249                 return 0;
250         switch(address->addresstype)
251         {
252         default:
253                 break;
254         case LHNETADDRESSTYPE_LOOP:
255                 if (includeport)
256                 {
257                         if (stringbuffersize >= 12)
258                         {
259                                 dpsnprintf(string, stringbuffersize, "local:%d", (int)address->addressdata.loop.port);
260                                 return 1;
261                         }
262                 }
263                 else
264                 {
265                         if (stringbuffersize >= 6)
266                         {
267                                 memcpy(string, "local", 6);
268                                 return 1;
269                         }
270                 }
271                 break;
272         case LHNETADDRESSTYPE_INET4:
273                 if (includeport)
274                 {
275                         if (stringbuffersize >= 22)
276                         {
277                                 dpsnprintf(string, stringbuffersize, "%d.%d.%d.%d:%d", (int)address->addressdata.inet4.address[0], (int)address->addressdata.inet4.address[1], (int)address->addressdata.inet4.address[2], (int)address->addressdata.inet4.address[3], (int)ntohs(address->addressdata.inet4.port));
278                                 return 1;
279                         }
280                 }
281                 else
282                 {
283                         if (stringbuffersize >= 16)
284                         {
285                                 dpsnprintf(string, stringbuffersize, "%d.%d.%d.%d", (int)address->addressdata.inet4.address[0], (int)address->addressdata.inet4.address[1], (int)address->addressdata.inet4.address[2], (int)address->addressdata.inet4.address[3]);
286                                 return 1;
287                         }
288                 }
289                 break;
290         case LHNETADDRESSTYPE_INET6:
291                 if (includeport)
292                 {
293                         if (stringbuffersize >= 88)
294                         {
295                                 dpsnprintf(string, stringbuffersize, "[%x:%x:%x:%x:%x:%x:%x:%x]:%d", (int)address->addressdata.inet6.address[0], (int)address->addressdata.inet6.address[1], (int)address->addressdata.inet6.address[2], (int)address->addressdata.inet6.address[3], (int)address->addressdata.inet6.address[4], (int)address->addressdata.inet6.address[5], (int)address->addressdata.inet6.address[6], (int)address->addressdata.inet6.address[7], (int)ntohs(address->addressdata.inet6.port));
296                                 return 1;
297                         }
298                 }
299                 else
300                 {
301                         if (stringbuffersize >= 80)
302                         {
303                                 dpsnprintf(string, stringbuffersize, "%x:%x:%x:%x:%x:%x:%x:%x", (int)address->addressdata.inet6.address[0], (int)address->addressdata.inet6.address[1], (int)address->addressdata.inet6.address[2], (int)address->addressdata.inet6.address[3], (int)address->addressdata.inet6.address[4], (int)address->addressdata.inet6.address[5], (int)address->addressdata.inet6.address[6], (int)address->addressdata.inet6.address[7]);
304                                 return 1;
305                         }
306                 }
307                 break;
308         }
309         return 0;
310 }
311
312 int LHNETADDRESS_GetAddressType(const lhnetaddress_t *address)
313 {
314         if (address)
315                 return address->addresstype;
316         else
317                 return LHNETADDRESSTYPE_NONE;
318 }
319
320 int LHNETADDRESS_GetPort(const lhnetaddress_t *address)
321 {
322         if (!address)
323                 return -1;
324         switch(address->addresstype)
325         {
326         case LHNETADDRESSTYPE_LOOP:
327                 return address->addressdata.loop.port;
328         case LHNETADDRESSTYPE_INET4:
329                 return ntohs(address->addressdata.inet4.port);
330         case LHNETADDRESSTYPE_INET6:
331                 return ntohs(address->addressdata.inet6.port);
332         default:
333                 return -1;
334         }
335 }
336
337 int LHNETADDRESS_SetPort(lhnetaddress_t *address, int port)
338 {
339         if (!address)
340                 return 0;
341         switch(address->addresstype)
342         {
343         case LHNETADDRESSTYPE_LOOP:
344                 address->addressdata.loop.port = port;
345                 return 1;
346         case LHNETADDRESSTYPE_INET4:
347                 address->addressdata.inet4.port = htons((unsigned short)port);
348                 return 1;
349         case LHNETADDRESSTYPE_INET6:
350                 address->addressdata.inet6.port = htons((unsigned short)port);
351                 return 1;
352         default:
353                 return 0;
354         }
355 }
356
357 int LHNETADDRESS_Compare(const lhnetaddress_t *address1, const lhnetaddress_t *address2)
358 {
359         if (!address1 || !address2)
360                 return 1;
361         if (address1->addresstype != address2->addresstype)
362                 return 1;
363         switch(address1->addresstype)
364         {
365         case LHNETADDRESSTYPE_LOOP:
366                 if (address1->addressdata.loop.port != address2->addressdata.loop.port)
367                         return -1;
368                 return 0;
369         case LHNETADDRESSTYPE_INET4:
370                 if (address1->addressdata.inet4.family != address2->addressdata.inet4.family)
371                         return 1;
372                 if (memcmp(address1->addressdata.inet4.address, address2->addressdata.inet4.address, sizeof(address1->addressdata.inet4.address)))
373                         return 1;
374                 if (address1->addressdata.inet4.port != address2->addressdata.inet4.port)
375                         return -1;
376                 return 0;
377         case LHNETADDRESSTYPE_INET6:
378                 if (address1->addressdata.inet6.family != address2->addressdata.inet6.family)
379                         return 1;
380                 if (memcmp(address1->addressdata.inet6.address, address2->addressdata.inet6.address, sizeof(address1->addressdata.inet6.address)))
381                         return 1;
382                 if (address1->addressdata.inet6.port != address2->addressdata.inet6.port)
383                         return -1;
384                 return 0;
385         default:
386                 return 1;
387         }
388 }
389
390 typedef struct lhnetpacket_s
391 {
392         void *data;
393         int length;
394         int sourceport;
395         int destinationport;
396         time_t timeout;
397 #ifndef STANDALONETEST
398         double sentdoubletime;
399 #endif
400         struct lhnetpacket_s *next, *prev;
401 }
402 lhnetpacket_t;
403
404 static int lhnet_active;
405 static lhnetsocket_t lhnet_socketlist;
406 static lhnetpacket_t lhnet_packetlist;
407 #ifdef WIN32
408 static int lhnet_didWSAStartup = 0;
409 static WSADATA lhnet_winsockdata;
410 #endif
411
412 void LHNET_Init(void)
413 {
414         if (lhnet_active)
415                 return;
416         lhnet_socketlist.next = lhnet_socketlist.prev = &lhnet_socketlist;
417         lhnet_packetlist.next = lhnet_packetlist.prev = &lhnet_packetlist;
418         lhnet_active = 1;
419 #ifdef WIN32
420         lhnet_didWSAStartup = !WSAStartup(MAKEWORD(1, 1), &lhnet_winsockdata);
421         if (!lhnet_didWSAStartup)
422                 Con_Print("LHNET_Init: WSAStartup failed, networking disabled\n");
423 #endif
424 }
425
426 void LHNET_Shutdown(void)
427 {
428         lhnetpacket_t *p;
429         if (!lhnet_active)
430                 return;
431         while (lhnet_socketlist.next != &lhnet_socketlist)
432                 LHNET_CloseSocket(lhnet_socketlist.next);
433         while (lhnet_packetlist.next != &lhnet_packetlist)
434         {
435                 p = lhnet_packetlist.next;
436                 p->prev->next = p->next;
437                 p->next->prev = p->prev;
438                 Z_Free(p);
439         }
440 #ifdef WIN32
441         if (lhnet_didWSAStartup)
442         {
443                 lhnet_didWSAStartup = 0;
444                 WSACleanup();
445         }
446 #endif
447         lhnet_active = 0;
448 }
449
450 static const char *LHNETPRIVATE_StrError(void)
451 {
452 #ifdef WIN32
453         int i = WSAGetLastError();
454         switch (i)
455         {
456                 case WSAEINTR:           return "WSAEINTR";
457                 case WSAEBADF:           return "WSAEBADF";
458                 case WSAEACCES:          return "WSAEACCES";
459                 case WSAEFAULT:          return "WSAEFAULT";
460                 case WSAEINVAL:          return "WSAEINVAL";
461                 case WSAEMFILE:          return "WSAEMFILE";
462                 case WSAEWOULDBLOCK:     return "WSAEWOULDBLOCK";
463                 case WSAEINPROGRESS:     return "WSAEINPROGRESS";
464                 case WSAEALREADY:        return "WSAEALREADY";
465                 case WSAENOTSOCK:        return "WSAENOTSOCK";
466                 case WSAEDESTADDRREQ:    return "WSAEDESTADDRREQ";
467                 case WSAEMSGSIZE:        return "WSAEMSGSIZE";
468                 case WSAEPROTOTYPE:      return "WSAEPROTOTYPE";
469                 case WSAENOPROTOOPT:     return "WSAENOPROTOOPT";
470                 case WSAEPROTONOSUPPORT: return "WSAEPROTONOSUPPORT";
471                 case WSAESOCKTNOSUPPORT: return "WSAESOCKTNOSUPPORT";
472                 case WSAEOPNOTSUPP:      return "WSAEOPNOTSUPP";
473                 case WSAEPFNOSUPPORT:    return "WSAEPFNOSUPPORT";
474                 case WSAEAFNOSUPPORT:    return "WSAEAFNOSUPPORT";
475                 case WSAEADDRINUSE:      return "WSAEADDRINUSE";
476                 case WSAEADDRNOTAVAIL:   return "WSAEADDRNOTAVAIL";
477                 case WSAENETDOWN:        return "WSAENETDOWN";
478                 case WSAENETUNREACH:     return "WSAENETUNREACH";
479                 case WSAENETRESET:       return "WSAENETRESET";
480                 case WSAECONNABORTED:    return "WSAECONNABORTED";
481                 case WSAECONNRESET:      return "WSAECONNRESET";
482                 case WSAENOBUFS:         return "WSAENOBUFS";
483                 case WSAEISCONN:         return "WSAEISCONN";
484                 case WSAENOTCONN:        return "WSAENOTCONN";
485                 case WSAESHUTDOWN:       return "WSAESHUTDOWN";
486                 case WSAETOOMANYREFS:    return "WSAETOOMANYREFS";
487                 case WSAETIMEDOUT:       return "WSAETIMEDOUT";
488                 case WSAECONNREFUSED:    return "WSAECONNREFUSED";
489                 case WSAELOOP:           return "WSAELOOP";
490                 case WSAENAMETOOLONG:    return "WSAENAMETOOLONG";
491                 case WSAEHOSTDOWN:       return "WSAEHOSTDOWN";
492                 case WSAEHOSTUNREACH:    return "WSAEHOSTUNREACH";
493                 case WSAENOTEMPTY:       return "WSAENOTEMPTY";
494                 case WSAEPROCLIM:        return "WSAEPROCLIM";
495                 case WSAEUSERS:          return "WSAEUSERS";
496                 case WSAEDQUOT:          return "WSAEDQUOT";
497                 case WSAESTALE:          return "WSAESTALE";
498                 case WSAEREMOTE:         return "WSAEREMOTE";
499                 case WSAEDISCON:         return "WSAEDISCON";
500                 case 0:                  return "no error";
501                 default:                 return "unknown WSAE error";
502         }
503 #else
504         return strerror(errno);
505 #endif
506 }
507
508 void LHNET_SleepUntilPacket_Microseconds(int microseconds)
509 {
510         fd_set fdreadset;
511         struct timeval tv;
512         int lastfd;
513         lhnetsocket_t *s;
514         FD_ZERO(&fdreadset);
515         lastfd = 0;
516         for (s = lhnet_socketlist.next;s != &lhnet_socketlist;s = s->next)
517         {
518                 if (s->address.addresstype == LHNETADDRESSTYPE_INET4 || s->address.addresstype == LHNETADDRESSTYPE_INET6)
519                 {
520                         if (lastfd < s->inetsocket)
521                                 lastfd = s->inetsocket;
522                         FD_SET((unsigned int)s->inetsocket, &fdreadset);
523                 }
524         }
525         tv.tv_sec = microseconds / 1000000;
526         tv.tv_usec = microseconds % 1000000;
527         select(lastfd + 1, &fdreadset, NULL, NULL, &tv);
528 }
529
530 lhnetsocket_t *LHNET_OpenSocket_Connectionless(lhnetaddress_t *address)
531 {
532         lhnetsocket_t *lhnetsocket, *s;
533         if (!address)
534                 return NULL;
535         lhnetsocket = (lhnetsocket_t *)Z_Malloc(sizeof(*lhnetsocket));
536         if (lhnetsocket)
537         {
538                 memset(lhnetsocket, 0, sizeof(*lhnetsocket));
539                 lhnetsocket->address = *address;
540                 switch(lhnetsocket->address.addresstype)
541                 {
542                 case LHNETADDRESSTYPE_LOOP:
543                         if (lhnetsocket->address.addressdata.loop.port == 0)
544                         {
545                                 // allocate a port dynamically
546                                 // this search will always terminate because there is never
547                                 // an allocated socket with port 0, so if the number wraps it
548                                 // will find the port is unused, and then refuse to use port
549                                 // 0, causing an intentional failure condition
550                                 lhnetsocket->address.addressdata.loop.port = 1024;
551                                 for (;;)
552                                 {
553                                         for (s = lhnet_socketlist.next;s != &lhnet_socketlist;s = s->next)
554                                                 if (s->address.addresstype == lhnetsocket->address.addresstype && s->address.addressdata.loop.port == lhnetsocket->address.addressdata.loop.port)
555                                                         break;
556                                         if (s == &lhnet_socketlist)
557                                                 break;
558                                         lhnetsocket->address.addressdata.loop.port++;
559                                 }
560                         }
561                         // check if the port is available
562                         for (s = lhnet_socketlist.next;s != &lhnet_socketlist;s = s->next)
563                                 if (s->address.addresstype == lhnetsocket->address.addresstype && s->address.addressdata.loop.port == lhnetsocket->address.addressdata.loop.port)
564                                         break;
565                         if (s == &lhnet_socketlist && lhnetsocket->address.addressdata.loop.port != 0)
566                         {
567                                 lhnetsocket->next = &lhnet_socketlist;
568                                 lhnetsocket->prev = lhnetsocket->next->prev;
569                                 lhnetsocket->next->prev = lhnetsocket;
570                                 lhnetsocket->prev->next = lhnetsocket;
571                                 return lhnetsocket;
572                         }
573                         break;
574                 case LHNETADDRESSTYPE_INET4:
575                 case LHNETADDRESSTYPE_INET6:
576 #ifdef WIN32
577                         if (lhnet_didWSAStartup)
578                         {
579 #endif
580                                 if ((lhnetsocket->inetsocket = socket(address->addresstype == LHNETADDRESSTYPE_INET6 ? LHNETADDRESSTYPE_INET6_FAMILY : LHNETADDRESSTYPE_INET4_FAMILY, SOCK_DGRAM, IPPROTO_UDP)) != -1)
581                                 {
582 #ifdef WIN32
583                                         u_long _true = 1;
584                                         u_long _false = 0;
585 #else
586                                         char _true = 1;
587 #endif
588                                         if (ioctlsocket(lhnetsocket->inetsocket, FIONBIO, &_true) != -1)
589                                         {
590                                                 SOCKLEN_T namelen;
591                                                 namelen = address->addresstype == LHNETADDRESSTYPE_INET6 ? sizeof(lhnetsocket->address.addressdata.inet6) : sizeof(lhnetsocket->address.addressdata.inet4);
592                                                 if (bind(lhnetsocket->inetsocket, (struct sockaddr *)&lhnetsocket->address.addressdata, namelen) != -1)
593                                                 {
594                                                         int i = 1;
595                                                         getsockname(lhnetsocket->inetsocket, (struct sockaddr *)&lhnetsocket->address.addressdata, &namelen);
596                                                         // enable broadcast on this socket
597                                                         setsockopt(lhnetsocket->inetsocket, SOL_SOCKET, SO_BROADCAST, (char *)&i, sizeof(i));
598                                                         lhnetsocket->next = &lhnet_socketlist;
599                                                         lhnetsocket->prev = lhnetsocket->next->prev;
600                                                         lhnetsocket->next->prev = lhnetsocket;
601                                                         lhnetsocket->prev->next = lhnetsocket;
602 #ifdef WIN32
603                                                         if (ioctlsocket(lhnetsocket->inetsocket, SIO_UDP_CONNRESET, &_false) == -1)
604                                                                 Con_DPrintf("LHNET_OpenSocket_Connectionless: ioctlsocket SIO_UDP_CONNRESET returned error: %s\n", LHNETPRIVATE_StrError());
605 #endif
606                                                         return lhnetsocket;
607                                                 }
608                                                 else
609                                                         Con_Printf("LHNET_OpenSocket_Connectionless: bind returned error: %s\n", LHNETPRIVATE_StrError());
610                                         }
611                                         else
612                                                 Con_Printf("LHNET_OpenSocket_Connectionless: ioctlsocket returned error: %s\n", LHNETPRIVATE_StrError());
613                                         closesocket(lhnetsocket->inetsocket);
614                                 }
615                                 else
616                                         Con_Printf("LHNET_OpenSocket_Connectionless: socket returned error: %s\n", LHNETPRIVATE_StrError());
617 #ifdef WIN32
618                         }
619                         else
620                                 Con_Print("LHNET_OpenSocket_Connectionless: can't open a socket (WSAStartup failed during LHNET_Init)\n");
621 #endif
622                         break;
623                 default:
624                         break;
625                 }
626                 Z_Free(lhnetsocket);
627         }
628         return NULL;
629 }
630
631 void LHNET_CloseSocket(lhnetsocket_t *lhnetsocket)
632 {
633         if (lhnetsocket)
634         {
635                 // unlink from socket list
636                 if (lhnetsocket->next == NULL)
637                         return; // invalid!
638                 lhnetsocket->next->prev = lhnetsocket->prev;
639                 lhnetsocket->prev->next = lhnetsocket->next;
640                 lhnetsocket->next = NULL;
641                 lhnetsocket->prev = NULL;
642
643                 // no special close code for loopback, just inet
644                 if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4 || lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
645                 {
646                         closesocket(lhnetsocket->inetsocket);
647                 }
648                 Z_Free(lhnetsocket);
649         }
650 }
651
652 lhnetaddress_t *LHNET_AddressFromSocket(lhnetsocket_t *sock)
653 {
654         if (sock)
655                 return &sock->address;
656         else
657                 return NULL;
658 }
659
660 int LHNET_Read(lhnetsocket_t *lhnetsocket, void *content, int maxcontentlength, lhnetaddress_t *address)
661 {
662         int value = 0;
663         if (!lhnetsocket || !address || !content || maxcontentlength < 1)
664                 return -1;
665         if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_LOOP)
666         {
667                 time_t currenttime;
668                 lhnetpacket_t *p, *pnext;
669                 // scan for any old packets to timeout while searching for a packet
670                 // that is waiting to be delivered to this socket
671                 currenttime = time(NULL);
672                 for (p = lhnet_packetlist.next;p != &lhnet_packetlist;p = pnext)
673                 {
674                         pnext = p->next;
675                         if (p->timeout < currenttime)
676                         {
677                                 // unlink and free
678                                 p->next->prev = p->prev;
679                                 p->prev->next = p->next;
680                                 Z_Free(p);
681                                 continue;
682                         }
683 #ifndef STANDALONETEST
684                         if (cl_netlocalping.value && (realtime - cl_netlocalping.value * (1.0 / 2000.0)) < p->sentdoubletime)
685                                 continue;
686 #endif
687                         if (value == 0 && p->destinationport == lhnetsocket->address.addressdata.loop.port)
688                         {
689                                 if (p->length <= maxcontentlength)
690                                 {
691                                         *address = lhnetsocket->address;
692                                         address->addressdata.loop.port = p->sourceport;
693                                         memcpy(content, p->data, p->length);
694                                         value = p->length;
695                                 }
696                                 else
697                                         value = -1;
698                                 // unlink and free
699                                 p->next->prev = p->prev;
700                                 p->prev->next = p->next;
701                                 Z_Free(p);
702                         }
703                 }
704         }
705         else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4)
706         {
707                 unsigned int inetaddresslength;
708                 address->addresstype = LHNETADDRESSTYPE_NONE;
709                 inetaddresslength = sizeof(address->addressdata.inet4);
710                 value = recvfrom(lhnetsocket->inetsocket, content, maxcontentlength, 0, (struct sockaddr *)&address->addressdata.inet4, &inetaddresslength);
711                 if (value > 0)
712                 {
713                         address->addresstype = LHNETADDRESSTYPE_INET4;
714                         return value;
715                 }
716                 else if (value == -1)
717                 {
718                         int e = SOCKETERRNO;
719                         if (e == EWOULDBLOCK)
720                                 return 0;
721                         switch (e)
722                         {
723                                 case ECONNREFUSED:
724                                         Con_Print("Connection refused\n");
725                                         return 0;
726                         }
727                         Con_Printf("LHNET_Read: recvfrom returned error: %s\n", LHNETPRIVATE_StrError());
728                 }
729         }
730         else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
731         {
732                 unsigned int inetaddresslength;
733                 address->addresstype = LHNETADDRESSTYPE_NONE;
734                 inetaddresslength = sizeof(address->addressdata.inet6);
735                 value = recvfrom(lhnetsocket->inetsocket, content, maxcontentlength, 0, (struct sockaddr *)&address->addressdata.inet6, &inetaddresslength);
736                 if (value > 0)
737                 {
738                         address->addresstype = LHNETADDRESSTYPE_INET6;
739                         return value;
740                 }
741                 else if (value == -1)
742                 {
743                         int e = SOCKETERRNO;
744                         if (e == EWOULDBLOCK)
745                                 return 0;
746                         switch (e)
747                         {
748                                 case ECONNREFUSED:
749                                         Con_Print("Connection refused\n");
750                                         return 0;
751                         }
752                         Con_Printf("LHNET_Read: recvfrom returned error: %s\n", LHNETPRIVATE_StrError());
753                 }
754         }
755         return value;
756 }
757
758 int LHNET_Write(lhnetsocket_t *lhnetsocket, const void *content, int contentlength, const lhnetaddress_t *address)
759 {
760         int value = -1;
761         if (!lhnetsocket || !address || !content || contentlength < 1)
762                 return -1;
763         if (lhnetsocket->address.addresstype != address->addresstype)
764                 return -1;
765         if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_LOOP)
766         {
767                 lhnetpacket_t *p;
768                 p = (lhnetpacket_t *)Z_Malloc(sizeof(*p) + contentlength);
769                 p->data = (void *)(p + 1);
770                 memcpy(p->data, content, contentlength);
771                 p->length = contentlength;
772                 p->sourceport = lhnetsocket->address.addressdata.loop.port;
773                 p->destinationport = address->addressdata.loop.port;
774                 p->timeout = time(NULL) + 10;
775                 p->next = &lhnet_packetlist;
776                 p->prev = p->next->prev;
777                 p->next->prev = p;
778                 p->prev->next = p;
779 #ifndef STANDALONETEST
780                 p->sentdoubletime = realtime;
781 #endif
782                 value = contentlength;
783         }
784         else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4)
785         {
786                 value = sendto(lhnetsocket->inetsocket, content, contentlength, 0, (struct sockaddr *)&address->addressdata.inet4, sizeof(address->addressdata.inet4));
787                 if (value == -1)
788                 {
789                         if (SOCKETERRNO == EWOULDBLOCK)
790                                 return 0;
791                         Con_Printf("LHNET_Write: sendto returned error: %s\n", LHNETPRIVATE_StrError());
792                 }
793         }
794         else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
795         {
796                 value = sendto(lhnetsocket->inetsocket, content, contentlength, 0, (struct sockaddr *)&address->addressdata.inet6, sizeof(address->addressdata.inet6));
797                 if (value == -1)
798                 {
799                         if (SOCKETERRNO == EWOULDBLOCK)
800                                 return 0;
801                         Con_Printf("LHNET_Write: sendto returned error: %s\n", LHNETPRIVATE_StrError());
802                 }
803         }
804         return value;
805 }
806
807 #ifdef STANDALONETEST
808 int main(int argc, char **argv)
809 {
810 #if 1
811         char *buffer = "test", buffer2[1024];
812         int blen = strlen(buffer);
813         int b2len = 1024;
814         lhnetsocket_t *sock1;
815         lhnetsocket_t *sock2;
816         lhnetaddress_t myaddy1;
817         lhnetaddress_t myaddy2;
818         lhnetaddress_t myaddy3;
819         lhnetaddress_t localhostaddy1;
820         lhnetaddress_t localhostaddy2;
821         int test1;
822         int test2;
823
824         printf("calling LHNET_Init\n");
825         LHNET_Init();
826
827         printf("calling LHNET_FromPort twice to create two local addresses\n");
828         LHNETADDRESS_FromPort(&myaddy1, LHNETADDRESSTYPE_INET4, 4000);
829         LHNETADDRESS_FromPort(&myaddy2, LHNETADDRESSTYPE_INET4, 4001);
830         LHNETADDRESS_FromString(&localhostaddy1, "127.0.0.1", 4000);
831         LHNETADDRESS_FromString(&localhostaddy2, "127.0.0.1", 4001);
832
833         printf("calling LHNET_OpenSocket_Connectionless twice to create two local sockets\n");
834         sock1 = LHNET_OpenSocket_Connectionless(&myaddy1);
835         sock2 = LHNET_OpenSocket_Connectionless(&myaddy2);
836
837         printf("calling LHNET_Write to send a packet from the first socket to the second socket\n");
838         test1 = LHNET_Write(sock1, buffer, blen, &localhostaddy2);
839         printf("sleeping briefly\n");
840 #ifdef WIN32
841         Sleep (100);
842 #else
843         usleep (100000);
844 #endif
845         printf("calling LHNET_Read on the second socket to read the packet sent from the first socket\n");
846         test2 = LHNET_Read(sock2, buffer2, b2len - 1, &myaddy3);
847         if (test2 > 0)
848                 Con_Printf("socket to socket test succeeded\n");
849         else
850                 Con_Printf("socket to socket test failed\n");
851
852 #ifdef WIN32
853         printf("press any key to exit\n");
854         getchar();
855 #endif
856
857         printf("calling LHNET_Shutdown\n");
858         LHNET_Shutdown();
859         printf("exiting\n");
860         return 0;
861 #else
862         lhnetsocket_t *sock[16], *sendsock;
863         int i;
864         int numsockets;
865         int count;
866         int length;
867         int port;
868         time_t oldtime;
869         time_t newtime;
870         char *sendmessage;
871         int sendmessagelength;
872         lhnetaddress_t destaddress;
873         lhnetaddress_t receiveaddress;
874         lhnetaddress_t sockaddress[16];
875         char buffer[1536], addressstring[128], addressstring2[128];
876         if ((argc == 2 || argc == 5) && (port = atoi(argv[1])) >= 1 && port < 65535)
877         {
878                 printf("calling LHNET_Init()\n");
879                 LHNET_Init();
880
881                 numsockets = 0;
882                 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_LOOP, port);
883                 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_INET4, port);
884                 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_INET6, port+1);
885
886                 sendsock = NULL;
887                 sendmessage = NULL;
888                 sendmessagelength = 0;
889
890                 for (i = 0;i < numsockets;i++)
891                 {
892                         LHNETADDRESS_ToString(&sockaddress[i], addressstring, sizeof(addressstring), 1);
893                         printf("calling LHNET_OpenSocket_Connectionless(<%s>)\n", addressstring);
894                         if ((sock[i] = LHNET_OpenSocket_Connectionless(&sockaddress[i])))
895                         {
896                                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
897                                 printf("opened socket successfully (address \"%s\")\n", addressstring2);
898                         }
899                         else
900                         {
901                                 printf("failed to open socket\n");
902                                 if (i == 0)
903                                 {
904                                         LHNET_Shutdown();
905                                         return -1;
906                                 }
907                         }
908                 }
909                 count = 0;
910                 if (argc == 5)
911                 {
912                         count = atoi(argv[2]);
913                         if (LHNETADDRESS_FromString(&destaddress, argv[3], -1))
914                         {
915                                 sendmessage = argv[4];
916                                 sendmessagelength = strlen(sendmessage);
917                                 sendsock = NULL;
918                                 for (i = 0;i < numsockets;i++)
919                                         if (sock[i] && LHNETADDRESS_GetAddressType(&destaddress) == LHNETADDRESS_GetAddressType(&sockaddress[i]))
920                                                 sendsock = sock[i];
921                                 if (sendsock == NULL)
922                                 {
923                                         printf("Could not find an open socket matching the addresstype (%i) of destination address, switching to listen only mode\n", LHNETADDRESS_GetAddressType(&destaddress));
924                                         argc = 2;
925                                 }
926                         }
927                         else
928                         {
929                                 printf("LHNETADDRESS_FromString did not like the address \"%s\", switching to listen only mode\n", argv[3]);
930                                 argc = 2;
931                         }
932                 }
933                 printf("started, now listening for \"exit\" on the opened sockets\n");
934                 oldtime = time(NULL);
935                 for(;;)
936                 {
937 #ifdef WIN32
938                         Sleep(1);
939 #else
940                         usleep(1);
941 #endif
942                         for (i = 0;i < numsockets;i++)
943                         {
944                                 if (sock[i])
945                                 {
946                                         length = LHNET_Read(sock[i], buffer, sizeof(buffer), &receiveaddress);
947                                         if (length < 0)
948                                                 printf("localsock read error: length < 0");
949                                         else if (length > 0 && length < (int)sizeof(buffer))
950                                         {
951                                                 buffer[length] = 0;
952                                                 LHNETADDRESS_ToString(&receiveaddress, addressstring, sizeof(addressstring), 1);
953                                                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
954                                                 printf("received message \"%s\" from \"%s\" on socket \"%s\"\n", buffer, addressstring, addressstring2);
955                                                 if (!strcmp(buffer, "exit"))
956                                                         break;
957                                         }
958                                 }
959                         }
960                         if (i < numsockets)
961                                 break;
962                         if (argc == 5 && count > 0)
963                         {
964                                 newtime = time(NULL);
965                                 if (newtime != oldtime)
966                                 {
967                                         LHNETADDRESS_ToString(&destaddress, addressstring, sizeof(addressstring), 1);
968                                         LHNETADDRESS_ToString(LHNET_AddressFromSocket(sendsock), addressstring2, sizeof(addressstring2), 1);
969                                         printf("calling LHNET_Write(<%s>, \"%s\", %i, <%s>)\n", addressstring2, sendmessage, sendmessagelength, addressstring);
970                                         length = LHNET_Write(sendsock, sendmessage, sendmessagelength, &destaddress);
971                                         if (length == sendmessagelength)
972                                                 printf("sent successfully\n");
973                                         else
974                                                 printf("LH_Write failed, returned %i (length of message was %i)\n", length, strlen(argv[4]));
975                                         oldtime = newtime;
976                                         count--;
977                                         if (count <= 0)
978                                                 printf("Done sending, still listening for \"exit\"\n");
979                                 }
980                         }
981                 }
982                 for (i = 0;i < numsockets;i++)
983                 {
984                         if (sock[i])
985                         {
986                                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
987                                 printf("calling LHNET_CloseSocket(<%s>)\n", addressstring2);
988                                 LHNET_CloseSocket(sock[i]);
989                         }
990                 }
991                 printf("calling LHNET_Shutdown()\n");
992                 LHNET_Shutdown();
993                 return 0;
994         }
995         printf("Testing code for lhnet.c\nusage: lhnettest <localportnumber> [<sendnumberoftimes> <sendaddress:port> <sendmessage>]\n");
996         return -1;
997 #endif
998 }
999 #endif
1000