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