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