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