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