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