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