fixed STANDALONETEST so it works again
[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                                                 socklen_t namelen = address->addresstype == LHNETADDRESSTYPE_INET6 ? sizeof(lhnetsocket->address.addressdata.inet6) : sizeof(lhnetsocket->address.addressdata.inet4);
463                                                 if (bind(lhnetsocket->inetsocket, (void *)&lhnetsocket->address.addressdata, namelen) != -1)
464                                                 {
465                                                         getsockname(lhnetsocket->inetsocket, (void *)&lhnetsocket->address.addressdata, &namelen);
466                                                         lhnetsocket->next = &lhnet_socketlist;
467                                                         lhnetsocket->prev = lhnetsocket->next->prev;
468                                                         lhnetsocket->next->prev = lhnetsocket;
469                                                         lhnetsocket->prev->next = lhnetsocket;
470                                                         return lhnetsocket;
471                                                 }
472                                                 else
473                                                         Con_Printf("LHNET_OpenSocket_Connectionless: bind returned error: %s\n", LHNETPRIVATE_StrError());
474                                         }
475                                         else
476                                                 Con_Printf("LHNET_OpenSocket_Connectionless: ioctlsocket returned error: %s\n", LHNETPRIVATE_StrError());
477 #ifdef WIN32
478                                         closesocket(lhnetsocket->inetsocket);
479 #else
480                                         close(lhnetsocket->inetsocket);
481 #endif
482                                 }
483                                 else
484                                         Con_Printf("LHNET_OpenSocket_Connectionless: socket returned error: %s\n", LHNETPRIVATE_StrError());
485 #ifdef WIN32
486                         }
487                         else
488                                 Con_Print("LHNET_OpenSocket_Connectionless: WSAStartup failed\n");
489 #endif
490                         break;
491                 default:
492                         break;
493                 }
494                 Z_Free(lhnetsocket);
495         }
496         return NULL;
497 }
498
499 void LHNET_CloseSocket(lhnetsocket_t *lhnetsocket)
500 {
501         if (lhnetsocket)
502         {
503                 // unlink from socket list
504                 if (lhnetsocket->next == NULL)
505                         return; // invalid!
506                 lhnetsocket->next->prev = lhnetsocket->prev;
507                 lhnetsocket->prev->next = lhnetsocket->next;
508                 lhnetsocket->next = NULL;
509                 lhnetsocket->prev = NULL;
510
511                 // no special close code for loopback, just inet
512                 if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4 || lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
513                 {
514 #ifdef WIN32
515                         closesocket(lhnetsocket->inetsocket);
516 #else
517                         close(lhnetsocket->inetsocket);
518 #endif
519                 }
520 #ifdef WIN32
521                 if (lhnet_socketlist.next == &lhnet_socketlist && lhnet_didWSAStartup)
522                 {
523                         lhnet_didWSAStartup = 0;
524                         WSACleanup();
525                 }
526 #endif
527                 Z_Free(lhnetsocket);
528         }
529 }
530
531 lhnetaddress_t *LHNET_AddressFromSocket(lhnetsocket_t *sock)
532 {
533         if (sock)
534                 return &sock->address;
535         else
536                 return NULL;
537 }
538
539 int LHNET_Read(lhnetsocket_t *lhnetsocket, void *content, int maxcontentlength, lhnetaddress_t *address)
540 {
541         int value = 0;
542         if (!lhnetsocket || !address || !content || maxcontentlength < 1)
543                 return -1;
544         if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_LOOP)
545         {
546                 time_t currenttime;
547                 lhnetpacket_t *p, *pnext;
548                 // scan for any old packets to timeout while searching for a packet
549                 // that is waiting to be delivered to this socket
550                 currenttime = time(NULL);
551                 for (p = lhnet_packetlist.next;p != &lhnet_packetlist;p = pnext)
552                 {
553                         pnext = p->next;
554                         if (p->timeout < currenttime)
555                         {
556                                 // unlink and free
557                                 p->next->prev = p->prev;
558                                 p->prev->next = p->next;
559                                 Z_Free(p);
560                                 continue;
561                         }
562 #ifndef STANDALONETEST
563                         if (p->sentdoubletime && Sys_DoubleTime() < p->sentdoubletime)
564                                 continue;
565 #endif
566                         if (value == 0 && p->destinationport == lhnetsocket->address.addressdata.loop.port)
567                         {
568                                 if (p->length <= maxcontentlength)
569                                 {
570                                         *address = lhnetsocket->address;
571                                         address->addressdata.loop.port = p->sourceport;
572                                         memcpy(content, p->data, p->length);
573                                         value = p->length;
574                                 }
575                                 else
576                                         value = -1;
577                                 // unlink and free
578                                 p->next->prev = p->prev;
579                                 p->prev->next = p->next;
580                                 Z_Free(p);
581                         }
582                 }
583         }
584         else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4)
585         {
586                 int inetaddresslength;
587                 address->addresstype = LHNETADDRESSTYPE_NONE;
588                 inetaddresslength = sizeof(address->addressdata.inet4);
589                 value = recvfrom(lhnetsocket->inetsocket, content, maxcontentlength, 0, (struct sockaddr *)&address->addressdata.inet4, &inetaddresslength);
590                 if (value > 0)
591                 {
592                         address->addresstype = LHNETADDRESSTYPE_INET4;
593                         return value;
594                 }
595                 else if (value == -1)
596                 {
597 #ifdef WIN32
598                         int e = WSAGetLastError();
599                         if (e == WSAEWOULDBLOCK)
600                                 return 0;
601                         switch (e)
602                         {
603                                 case WSAECONNREFUSED:
604                                         Con_Print("Connection refused\n");
605                                         return 0;
606                         }
607 #else
608                         if (errno == EWOULDBLOCK)
609                                 return 0;
610                         switch (errno)
611                         {
612                                 case ECONNREFUSED:
613                                         Con_Print("Connection refused\n");
614                                         return 0;
615                         }
616 #endif
617                 }
618         }
619         else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
620         {
621                 int inetaddresslength;
622                 address->addresstype = LHNETADDRESSTYPE_NONE;
623                 inetaddresslength = sizeof(address->addressdata.inet6);
624                 value = recvfrom(lhnetsocket->inetsocket, content, maxcontentlength, 0, (struct sockaddr *)&address->addressdata.inet6, &inetaddresslength);
625                 if (value > 0)
626                 {
627                         address->addresstype = LHNETADDRESSTYPE_INET6;
628                         return value;
629                 }
630                 else if (value == -1)
631                 {
632 #ifdef WIN32
633                         int e = WSAGetLastError();
634                         if (e == WSAEWOULDBLOCK)
635                                 return 0;
636                         switch (e)
637                         {
638                                 case WSAECONNREFUSED:
639                                         Con_Print("Connection refused\n");
640                                         return 0;
641                         }
642 #else
643                         if (errno == EWOULDBLOCK)
644                                 return 0;
645                         switch (errno)
646                         {
647                                 case ECONNREFUSED:
648                                         Con_Print("Connection refused\n");
649                                         return 0;
650                         }
651 #endif
652                 }
653         }
654         return value;
655 }
656
657 int LHNET_Write(lhnetsocket_t *lhnetsocket, const void *content, int contentlength, const lhnetaddress_t *address)
658 {
659         int value = -1;
660         if (!lhnetsocket || !address || !content || contentlength < 1)
661                 return -1;
662         if (lhnetsocket->address.addresstype != address->addresstype)
663                 return -1;
664         if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_LOOP)
665         {
666                 lhnetpacket_t *p;
667                 p = Z_Malloc(sizeof(*p) + contentlength);
668                 p->data = (void *)(p + 1);
669                 memcpy(p->data, content, contentlength);
670                 p->length = contentlength;
671                 p->sourceport = lhnetsocket->address.addressdata.loop.port;
672                 p->destinationport = address->addressdata.loop.port;
673                 p->timeout = time(NULL) + 10;
674                 p->next = &lhnet_packetlist;
675                 p->prev = p->next->prev;
676                 p->next->prev = p;
677                 p->prev->next = p;
678 #ifndef STANDALONETEST
679                 if (cl_netlocalping_min.value || cl_netlocalping_max.value)
680                         p->sentdoubletime = Sys_DoubleTime() + lhrandom(cl_netlocalping_min.value, cl_netlocalping_max.value) * (0.5 / 1000.0);
681 #endif
682                 value = contentlength;
683         }
684         else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4)
685         {
686                 value = sendto(lhnetsocket->inetsocket, content, contentlength, 0, (struct sockaddr *)&address->addressdata.inet4, sizeof(address->addressdata.inet4));
687                 if (value == -1)
688                 {
689 #ifdef WIN32
690                         int e = WSAGetLastError();
691                         if (e == WSAEWOULDBLOCK)
692                                 return 0;
693 #else
694                         if (errno == EWOULDBLOCK)
695                                 return 0;
696 #endif
697                 }
698         }
699         else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
700         {
701                 value = sendto(lhnetsocket->inetsocket, content, contentlength, 0, (struct sockaddr *)&address->addressdata.inet6, sizeof(address->addressdata.inet6));
702                 if (value == -1)
703                 {
704 #ifdef WIN32
705                         int e = WSAGetLastError();
706                         if (e == WSAEWOULDBLOCK)
707                                 return 0;
708 #else
709                         if (errno == EWOULDBLOCK)
710                                 return 0;
711 #endif
712                 }
713         }
714         return value;
715 }
716
717 #ifdef STANDALONETEST
718 int main(int argc, char **argv)
719 {
720         lhnetsocket_t *sock[16], *sendsock;
721         int i;
722         int numsockets;
723         int count;
724         int length;
725         int port;
726         time_t oldtime;
727         time_t newtime;
728         char *sendmessage;
729         int sendmessagelength;
730         lhnetaddress_t destaddress;
731         lhnetaddress_t receiveaddress;
732         lhnetaddress_t sockaddress[16];
733         char buffer[1536], addressstring[128], addressstring2[128];
734         if ((argc == 2 || argc == 5) && (port = atoi(argv[1])) >= 1 && port < 65535)
735         {
736                 printf("calling LHNET_Init()\n");
737                 LHNET_Init();
738
739                 numsockets = 0;
740                 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_LOOP, port);
741                 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_INET4, port);
742                 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_INET6, port+1);
743
744                 sendsock = NULL;
745                 sendmessage = NULL;
746                 sendmessagelength = 0;
747
748                 for (i = 0;i < numsockets;i++)
749                 {
750                         LHNETADDRESS_ToString(&sockaddress[i], addressstring, sizeof(addressstring), 1);
751                         printf("calling LHNET_OpenSocket_Connectionless(<%s>)\n", addressstring);
752                         if ((sock[i] = LHNET_OpenSocket_Connectionless(&sockaddress[i])))
753                         {
754                                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
755                                 printf("opened socket successfully (address \"%s\")\n", addressstring2);
756                         }
757                         else
758                         {
759                                 printf("failed to open socket\n");
760                                 if (i == 0)
761                                 {
762                                         LHNET_Shutdown();
763                                         return -1;
764                                 }
765                         }
766                 }
767                 count = 0;
768                 if (argc == 5)
769                 {
770                         count = atoi(argv[2]);
771                         if (LHNETADDRESS_FromString(&destaddress, argv[3], -1))
772                         {
773                                 sendmessage = argv[4];
774                                 sendmessagelength = strlen(sendmessage);
775                                 sendsock = NULL;
776                                 for (i = 0;i < numsockets;i++)
777                                         if (sock[i] && LHNETADDRESS_GetAddressType(&destaddress) == LHNETADDRESS_GetAddressType(&sockaddress[i]))
778                                                 sendsock = sock[i];
779                                 if (sendsock == NULL)
780                                 {
781                                         printf("Could not find an open socket matching the addresstype (%i) of destination address, switching to listen only mode\n", LHNETADDRESS_GetAddressType(&destaddress));
782                                         argc = 2;
783                                 }
784                         }
785                         else
786                         {
787                                 printf("LHNETADDRESS_FromString did not like the address \"%s\", switching to listen only mode\n", argv[3]);
788                                 argc = 2;
789                         }
790                 }
791                 printf("started, now listening for \"exit\" on the opened sockets\n");
792                 oldtime = time(NULL);
793                 for(;;)
794                 {
795 #ifdef WIN32
796                         Sleep(1);
797 #else
798                         usleep(1);
799 #endif
800                         for (i = 0;i < numsockets;i++)
801                         {
802                                 if (sock[i])
803                                 {
804                                         length = LHNET_Read(sock[i], buffer, sizeof(buffer), &receiveaddress);
805                                         if (length < 0)
806                                                 printf("localsock read error: length < 0");
807                                         else if (length > 0 && length < (int)sizeof(buffer))
808                                         {
809                                                 buffer[length] = 0;
810                                                 LHNETADDRESS_ToString(&receiveaddress, addressstring, sizeof(addressstring), 1);
811                                                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
812                                                 printf("received message \"%s\" from \"%s\" on socket \"%s\"\n", buffer, addressstring, addressstring2);
813                                                 if (!strcmp(buffer, "exit"))
814                                                         break;
815                                         }
816                                 }
817                         }
818                         if (i < numsockets)
819                                 break;
820                         if (argc == 5 && count > 0)
821                         {
822                                 newtime = time(NULL);
823                                 if (newtime != oldtime)
824                                 {
825                                         LHNETADDRESS_ToString(&destaddress, addressstring, sizeof(addressstring), 1);
826                                         LHNETADDRESS_ToString(LHNET_AddressFromSocket(sendsock), addressstring2, sizeof(addressstring2), 1);
827                                         printf("calling LHNET_Write(<%s>, \"%s\", %i, <%s>)\n", addressstring2, sendmessage, sendmessagelength, addressstring);
828                                         length = LHNET_Write(sendsock, sendmessage, sendmessagelength, &destaddress);
829                                         if (length == sendmessagelength)
830                                                 printf("sent successfully\n");
831                                         else
832                                                 printf("LH_Write failed, returned %i (length of message was %i)\n", length, strlen(argv[4]));
833                                         oldtime = newtime;
834                                         count--;
835                                         if (count <= 0)
836                                                 printf("Done sending, still listening for \"exit\"\n");
837                                 }
838                         }
839                 }
840                 for (i = 0;i < numsockets;i++)
841                 {
842                         if (sock[i])
843                         {
844                                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
845                                 printf("calling LHNET_CloseSocket(<%s>)\n", addressstring2);
846                                 LHNET_CloseSocket(sock[i]);
847                         }
848                 }
849                 printf("calling LHNET_Shutdown()\n");
850                 LHNET_Shutdown();
851                 return 0;
852         }
853         printf("Testing code for lhnet.c\nusage: lhnettest <localportnumber> [<sendnumberoftimes> <sendaddress:port> <sendmessage>]\n");
854         return -1;
855 }
856 #endif
857