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