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