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