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