]> git.xonotic.org Git - xonotic/darkplaces.git/blob - lhnet.c
patch from Ozkan Sezer for compatibility with mingw64 (changed #include
[xonotic/darkplaces.git] / lhnet.c
1
2 // Written by Forest Hale 2003-06-15 and placed into public domain.
3
4 #ifdef WIN32
5 # ifdef SUPPORTIPV6
6 // Windows XP or higher is required for getaddrinfo, but the inclusion of wspiapi provides fallbacks for older versions
7 # define _WIN32_WINNT 0x0501
8 # endif
9 # include <winsock2.h>
10 # include <ws2tcpip.h>
11 # ifdef USE_WSPIAPI_H
12 #  include <wspiapi.h>
13 # endif
14 #endif
15
16 #ifndef STANDALONETEST
17 #include "quakedef.h"
18 #endif
19
20 #include <stdlib.h>
21 #include <stdio.h>
22 #include <time.h>
23 #include <string.h>
24 #ifndef WIN32
25 #include <unistd.h>
26 #include <sys/types.h>
27 #include <sys/socket.h>
28 #include <sys/ioctl.h>
29 #include <errno.h>
30 #include <netdb.h>
31 #include <netinet/in.h>
32 #include <arpa/inet.h>
33 #ifdef SUPPORTIPV6
34 #include <net/if.h>
35 #endif
36 #endif
37
38 #ifdef __MORPHOS__
39 #include <proto/socket.h>
40 #endif
41
42 // for Z_Malloc/Z_Free in quake
43 #ifndef STANDALONETEST
44 #include "zone.h"
45 #include "sys.h"
46 #include "netconn.h"
47 #else
48 #define Con_Print printf
49 #define Con_Printf printf
50 #define Z_Malloc malloc
51 #define Z_Free free
52 #endif
53
54 #include "lhnet.h"
55
56 #if defined(WIN32)
57 #define EWOULDBLOCK WSAEWOULDBLOCK
58 #define ECONNREFUSED WSAECONNREFUSED
59
60 #define SOCKETERRNO WSAGetLastError()
61
62 #define IOC_VENDOR 0x18000000
63 #define _WSAIOW(x,y) (IOC_IN|(x)|(y))
64 #define SIO_UDP_CONNRESET _WSAIOW(IOC_VENDOR,12)
65
66 #define SOCKLEN_T int
67 #elif defined(__MORPHOS__)
68 #define ioctlsocket IoctlSocket
69 #define closesocket CloseSocket
70 #define SOCKETERRNO Errno()
71
72 #define SOCKLEN_T int
73 #else
74 #define ioctlsocket ioctl
75 #define closesocket close
76 #define SOCKETERRNO errno
77
78 #define SOCKLEN_T socklen_t
79 #endif
80
81 #ifdef MSG_DONTWAIT
82 #define LHNET_RECVFROM_FLAGS MSG_DONTWAIT
83 #define LHNET_SENDTO_FLAGS 0
84 #else
85 #define LHNET_RECVFROM_FLAGS 0
86 #define LHNET_SENDTO_FLAGS 0
87 #endif
88
89 typedef struct lhnetaddressnative_s
90 {
91         lhnetaddresstype_t addresstype;
92         int port;
93         union
94         {
95                 struct sockaddr sock;
96                 struct sockaddr_in in;
97 #ifdef SUPPORTIPV6
98                 struct sockaddr_in6 in6;
99 #endif
100         }
101         addr;
102 }
103 lhnetaddressnative_t;
104
105 // to make LHNETADDRESS_FromString resolve repeated hostnames faster, cache them
106 #define MAX_NAMECACHE 64
107 static struct namecache_s
108 {
109         lhnetaddressnative_t address;
110         double expirationtime;
111         char name[64];
112 }
113 namecache[MAX_NAMECACHE];
114 static int namecacheposition = 0;
115
116 int LHNETADDRESS_FromPort(lhnetaddress_t *vaddress, lhnetaddresstype_t addresstype, int port)
117 {
118         lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
119         if (!address)
120                 return 0;
121         switch(addresstype)
122         {
123         default:
124                 break;
125         case LHNETADDRESSTYPE_LOOP:
126                 // local:port  (loopback)
127                 memset(address, 0, sizeof(*address));
128                 address->addresstype = LHNETADDRESSTYPE_LOOP;
129                 address->port = port;
130                 return 1;
131         case LHNETADDRESSTYPE_INET4:
132                 // 0.0.0.0:port  (INADDR_ANY, binds to all interfaces)
133                 memset(address, 0, sizeof(*address));
134                 address->addresstype = LHNETADDRESSTYPE_INET4;
135                 address->port = port;
136                 address->addr.in.sin_family = AF_INET;
137                 address->addr.in.sin_port = htons((unsigned short)port);
138                 return 1;
139 #ifdef SUPPORTIPV6
140         case LHNETADDRESSTYPE_INET6:
141                 // [0:0:0:0:0:0:0:0]:port  (IN6ADDR_ANY, binds to all interfaces)
142                 memset(address, 0, sizeof(*address));
143                 address->addresstype = LHNETADDRESSTYPE_INET6;
144                 address->port = port;
145                 address->addr.in6.sin6_family = AF_INET6;
146                 address->addr.in6.sin6_port = htons((unsigned short)port);
147                 return 1;
148 #endif
149         }
150         return 0;
151 }
152
153 #ifdef SUPPORTIPV6
154 int LHNETADDRESS_Resolve(lhnetaddressnative_t *address, const char *name, int port)
155 {
156         char port_buff [16];
157         struct addrinfo hints;
158         struct addrinfo* addrinf;
159         int err;
160
161         dpsnprintf (port_buff, sizeof (port_buff), "%d", port);
162         port_buff[sizeof (port_buff) - 1] = '\0';
163
164         memset(&hints, 0, sizeof (hints));
165         hints.ai_family = AF_UNSPEC;
166         hints.ai_socktype = SOCK_DGRAM;
167         //hints.ai_flags = AI_PASSIVE;
168
169         err = getaddrinfo(name, port_buff, &hints, &addrinf);
170         if (err != 0 || addrinf == NULL)
171                 return 0;
172         if (addrinf->ai_addr->sa_family != AF_INET6 && addrinf->ai_addr->sa_family != AF_INET)
173         {
174                 freeaddrinfo (addrinf);
175                 return 0;
176         }
177
178         // great it worked
179         if (addrinf->ai_addr->sa_family == AF_INET6)
180         {
181                 address->addresstype = LHNETADDRESSTYPE_INET6;
182                 memcpy(&address->addr.in6, addrinf->ai_addr, sizeof(address->addr.in6));
183         }
184         else
185         {
186                 address->addresstype = LHNETADDRESSTYPE_INET4;
187                 memcpy(&address->addr.in, addrinf->ai_addr, sizeof(address->addr.in));
188         }
189         address->port = port;
190         
191         freeaddrinfo (addrinf);
192         return 1;
193 }
194
195 int LHNETADDRESS_FromString(lhnetaddress_t *vaddress, const char *string, int defaultport)
196 {
197         lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
198         int i, port, d1, d2, d3, d4, resolved;
199         size_t namelen;
200         unsigned char *a;
201         char name[128];
202 #ifdef STANDALONETEST
203         char string2[128];
204 #endif
205         const char* addr_start;
206         const char* addr_end = NULL;
207         const char* port_name = NULL;
208         int addr_family = AF_UNSPEC;
209
210         if (!address || !string || !*string)
211                 return 0;
212         memset(address, 0, sizeof(*address));
213         address->addresstype = LHNETADDRESSTYPE_NONE;
214         port = 0;
215
216         // If it's a bracketed IPv6 address
217         if (string[0] == '[')
218         {
219                 const char* end_bracket = strchr(string, ']');
220
221                 if (end_bracket == NULL)
222                         return 0;
223
224                 if (end_bracket[1] == ':')
225                         port_name = end_bracket + 2;
226                 else if (end_bracket[1] != '\0')
227                         return 0;
228
229                 addr_family = AF_INET6;
230                 addr_start = &string[1];
231                 addr_end = end_bracket;
232         }
233         else
234         {
235                 const char* first_colon;
236
237                 addr_start = string;
238
239                 // If it's a numeric non-bracket IPv6 address (-> no port),
240                 // or it's a numeric IPv4 address, or a name, with a port
241                 first_colon = strchr(string, ':');
242                 if (first_colon != NULL)
243                 {
244                         const char* last_colon = strrchr(first_colon + 1, ':');
245
246                         // If it's an numeric IPv4 address, or a name, with a port
247                         if (last_colon == NULL)
248                         {
249                                 addr_end = first_colon;
250                                 port_name = first_colon + 1;
251                         }
252                         else
253                                 addr_family = AF_INET6;
254                 }
255         }
256
257         if (addr_end != NULL)
258                 namelen = addr_end - addr_start;
259         else
260                 namelen = strlen (addr_start);
261
262         if (namelen >= sizeof(name))
263                 namelen = sizeof(name) - 1;
264         memcpy (name, addr_start, namelen);
265         name[namelen] = 0;
266
267         if (port_name)
268                 port = atoi(port_name);
269
270         if (port == 0)
271                 port = defaultport;
272
273         // handle loopback
274         if (!strcmp(name, "local"))
275         {
276                 address->addresstype = LHNETADDRESSTYPE_LOOP;
277                 address->port = port;
278                 return 1;
279         }
280         // try to parse as dotted decimal ipv4 address first
281         // note this supports partial ip addresses
282         d1 = d2 = d3 = d4 = 0;
283 #if _MSC_VER >= 1400
284 #define sscanf sscanf_s
285 #endif
286         if (addr_family != AF_INET6 &&
287                 sscanf(name, "%d.%d.%d.%d", &d1, &d2, &d3, &d4) >= 1 && (unsigned int)d1 < 256 && (unsigned int)d2 < 256 && (unsigned int)d3 < 256 && (unsigned int)d4 < 256)
288         {
289                 // parsed a valid ipv4 address
290                 address->addresstype = LHNETADDRESSTYPE_INET4;
291                 address->port = port;
292                 address->addr.in.sin_family = AF_INET;
293                 address->addr.in.sin_port = htons((unsigned short)port);
294                 a = (unsigned char *)&address->addr.in.sin_addr;
295                 a[0] = d1;
296                 a[1] = d2;
297                 a[2] = d3;
298                 a[3] = d4;
299 #ifdef STANDALONETEST
300                 LHNETADDRESS_ToString(address, string2, sizeof(string2), 1);
301                 printf("manual parsing of ipv4 dotted decimal address \"%s\" successful: %s\n", string, string2);
302 #endif
303                 return 1;
304         }
305         for (i = 0;i < MAX_NAMECACHE;i++)
306                 if (!strcmp(namecache[i].name, name))
307                         break;
308 #ifdef STANDALONETEST
309         if (i < MAX_NAMECACHE)
310 #else
311         if (i < MAX_NAMECACHE && realtime < namecache[i].expirationtime)
312 #endif
313         {
314                 *address = namecache[i].address;
315                 address->port = port;
316                 if (address->addresstype == LHNETADDRESSTYPE_INET6)
317                 {
318                         address->addr.in6.sin6_port = htons((unsigned short)port);
319                         return 1;
320                 }
321                 else if (address->addresstype == LHNETADDRESSTYPE_INET4)
322                 {
323                         address->addr.in.sin_port = htons((unsigned short)port);
324                         return 1;
325                 }
326                 return 0;
327         }
328
329         for (i = 0;i < (int)sizeof(namecache[namecacheposition].name)-1 && name[i];i++)
330                 namecache[namecacheposition].name[i] = name[i];
331         namecache[namecacheposition].name[i] = 0;
332 #ifndef STANDALONETEST
333         namecache[namecacheposition].expirationtime = realtime + 12 * 3600; // 12 hours
334 #endif
335
336         // try resolving the address (handles dns and other ip formats)
337         resolved = LHNETADDRESS_Resolve(address, name, port);
338         if (resolved)
339         {
340 #ifdef STANDALONETEST
341                 const char *protoname;
342
343                 switch (address->addresstype)
344                 {
345                         case LHNETADDRESSTYPE_INET6:
346                                 protoname = "ipv6";
347                                 break;
348                         case LHNETADDRESSTYPE_INET4:
349                                 protoname = "ipv4";
350                                 break;
351                         default:
352                                 protoname = "UNKNOWN";
353                                 break;
354                 }
355                 LHNETADDRESS_ToString(vaddress, string2, sizeof(string2), 1);
356                 Con_Printf("LHNETADDRESS_Resolve(\"%s\") returned %s address %s\n", string, protoname, string2);
357 #endif
358                 namecache[namecacheposition].address = *address;
359         }
360         else
361         {
362 #ifdef STANDALONETEST
363                 printf("name resolution failed on address \"%s\"\n", name);
364 #endif
365                 namecache[namecacheposition].address.addresstype = LHNETADDRESSTYPE_NONE;
366         }
367         
368         namecacheposition = (namecacheposition + 1) % MAX_NAMECACHE;
369         return resolved;
370 }
371 #else
372 int LHNETADDRESS_FromString(lhnetaddress_t *vaddress, const char *string, int defaultport)
373 {
374         lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
375         int i, port, namelen, d1, d2, d3, d4;
376         struct hostent *hostentry;
377         unsigned char *a;
378         const char *colon;
379         char name[128];
380 #ifdef STANDALONETEST
381         char string2[128];
382 #endif
383         if (!address || !string || !*string)
384                 return 0;
385         memset(address, 0, sizeof(*address));
386         address->addresstype = LHNETADDRESSTYPE_NONE;
387         port = 0;
388         colon = strrchr(string, ':');
389         if (colon)
390                 port = atoi(colon + 1);
391         else
392                 colon = string + strlen(string);
393         if (port == 0)
394                 port = defaultport;
395         namelen = colon - string;
396         if (namelen > 127)
397                 namelen = 127;
398         if (string[0] == '[' && namelen > 0 && string[namelen-1] == ']') // ipv6
399         {
400                 string++;
401                 namelen -= 2;
402         }
403         memcpy(name, string, namelen);
404         name[namelen] = 0;
405         // handle loopback
406         if (!strcmp(name, "local"))
407         {
408                 address->addresstype = LHNETADDRESSTYPE_LOOP;
409                 address->port = port;
410                 return 1;
411         }
412         // try to parse as dotted decimal ipv4 address first
413         // note this supports partial ip addresses
414         d1 = d2 = d3 = d4 = 0;
415 #if _MSC_VER >= 1400
416 #define sscanf sscanf_s
417 #endif
418         if (sscanf(name, "%d.%d.%d.%d", &d1, &d2, &d3, &d4) >= 1 && (unsigned int)d1 < 256 && (unsigned int)d2 < 256 && (unsigned int)d3 < 256 && (unsigned int)d4 < 256)
419         {
420                 // parsed a valid ipv4 address
421                 address->addresstype = LHNETADDRESSTYPE_INET4;
422                 address->port = port;
423                 address->addr.in.sin_family = AF_INET;
424                 address->addr.in.sin_port = htons((unsigned short)port);
425                 a = (unsigned char *)&address->addr.in.sin_addr;
426                 a[0] = d1;
427                 a[1] = d2;
428                 a[2] = d3;
429                 a[3] = d4;
430 #ifdef STANDALONETEST
431                 LHNETADDRESS_ToString(address, string2, sizeof(string2), 1);
432                 printf("manual parsing of ipv4 dotted decimal address \"%s\" successful: %s\n", string, string2);
433 #endif
434                 return 1;
435         }
436         for (i = 0;i < MAX_NAMECACHE;i++)
437                 if (!strcmp(namecache[i].name, name))
438                         break;
439 #ifdef STANDALONETEST
440         if (i < MAX_NAMECACHE)
441 #else
442         if (i < MAX_NAMECACHE && realtime < namecache[i].expirationtime)
443 #endif
444         {
445                 *address = namecache[i].address;
446                 address->port = port;
447                 if (address->addresstype == LHNETADDRESSTYPE_INET6)
448                 {
449 #ifdef SUPPORTIPV6
450                         address->addr.in6.sin6_port = htons((unsigned short)port);
451                         return 1;
452 #endif
453                 }
454                 else if (address->addresstype == LHNETADDRESSTYPE_INET4)
455                 {
456                         address->addr.in.sin_port = htons((unsigned short)port);
457                         return 1;
458                 }
459                 return 0;
460         }
461         // try gethostbyname (handles dns and other ip formats)
462         hostentry = gethostbyname(name);
463         if (hostentry)
464         {
465                 if (hostentry->h_addrtype == AF_INET6)
466                 {
467 #ifdef SUPPORTIPV6
468                         // great it worked
469                         address->addresstype = LHNETADDRESSTYPE_INET6;
470                         address->port = port;
471                         address->addr.in6.sin6_family = hostentry->h_addrtype;
472                         address->addr.in6.sin6_port = htons((unsigned short)port);
473                         memcpy(&address->addr.in6.sin6_addr, hostentry->h_addr_list[0], sizeof(address->addr.in6.sin6_addr));
474                         for (i = 0;i < (int)sizeof(namecache[namecacheposition].name)-1 && name[i];i++)
475                                 namecache[namecacheposition].name[i] = name[i];
476                         namecache[namecacheposition].name[i] = 0;
477 #ifndef STANDALONETEST
478                         namecache[namecacheposition].expirationtime = realtime + 12 * 3600; // 12 hours
479 #endif
480                         namecache[namecacheposition].address = *address;
481                         namecacheposition = (namecacheposition + 1) % MAX_NAMECACHE;
482 #ifdef STANDALONETEST
483                         LHNETADDRESS_ToString(address, string2, sizeof(string2), 1);
484                         printf("gethostbyname(\"%s\") returned ipv6 address %s\n", string, string2);
485 #endif
486                         return 1;
487 #endif
488                 }
489                 else if (hostentry->h_addrtype == AF_INET)
490                 {
491                         // great it worked
492                         address->addresstype = LHNETADDRESSTYPE_INET4;
493                         address->port = port;
494                         address->addr.in.sin_family = hostentry->h_addrtype;
495                         address->addr.in.sin_port = htons((unsigned short)port);
496                         memcpy(&address->addr.in.sin_addr, hostentry->h_addr_list[0], sizeof(address->addr.in.sin_addr));
497                         for (i = 0;i < (int)sizeof(namecache[namecacheposition].name)-1 && name[i];i++)
498                                 namecache[namecacheposition].name[i] = name[i];
499                         namecache[namecacheposition].name[i] = 0;
500 #ifndef STANDALONETEST
501                         namecache[namecacheposition].expirationtime = realtime + 12 * 3600; // 12 hours
502 #endif
503                         namecache[namecacheposition].address = *address;
504                         namecacheposition = (namecacheposition + 1) % MAX_NAMECACHE;
505 #ifdef STANDALONETEST
506                         LHNETADDRESS_ToString(address, string2, sizeof(string2), 1);
507                         printf("gethostbyname(\"%s\") returned ipv4 address %s\n", string, string2);
508 #endif
509                         return 1;
510                 }
511         }
512 #ifdef STANDALONETEST
513         printf("gethostbyname failed on address \"%s\"\n", name);
514 #endif
515         for (i = 0;i < (int)sizeof(namecache[namecacheposition].name)-1 && name[i];i++)
516                 namecache[namecacheposition].name[i] = name[i];
517         namecache[namecacheposition].name[i] = 0;
518 #ifndef STANDALONETEST
519         namecache[namecacheposition].expirationtime = realtime + 12 * 3600; // 12 hours
520 #endif
521         namecache[namecacheposition].address.addresstype = LHNETADDRESSTYPE_NONE;
522         namecacheposition = (namecacheposition + 1) % MAX_NAMECACHE;
523         return 0;
524 }
525 #endif
526
527 int LHNETADDRESS_ToString(const lhnetaddress_t *vaddress, char *string, int stringbuffersize, int includeport)
528 {
529         lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
530         const unsigned char *a;
531         *string = 0;
532         if (!address || !string || stringbuffersize < 1)
533                 return 0;
534         switch(address->addresstype)
535         {
536         default:
537                 break;
538         case LHNETADDRESSTYPE_LOOP:
539                 if (includeport)
540                 {
541                         if (stringbuffersize >= 12)
542                         {
543                                 dpsnprintf(string, stringbuffersize, "local:%d", address->port);
544                                 return 1;
545                         }
546                 }
547                 else
548                 {
549                         if (stringbuffersize >= 6)
550                         {
551                                 memcpy(string, "local", 6);
552                                 return 1;
553                         }
554                 }
555                 break;
556         case LHNETADDRESSTYPE_INET4:
557                 a = (const unsigned char *)(&address->addr.in.sin_addr);
558                 if (includeport)
559                 {
560                         if (stringbuffersize >= 22)
561                         {
562                                 dpsnprintf(string, stringbuffersize, "%d.%d.%d.%d:%d", a[0], a[1], a[2], a[3], address->port);
563                                 return 1;
564                         }
565                 }
566                 else
567                 {
568                         if (stringbuffersize >= 16)
569                         {
570                                 dpsnprintf(string, stringbuffersize, "%d.%d.%d.%d", a[0], a[1], a[2], a[3]);
571                                 return 1;
572                         }
573                 }
574                 break;
575 #ifdef SUPPORTIPV6
576         case LHNETADDRESSTYPE_INET6:
577                 a = (const unsigned char *)(&address->addr.in6.sin6_addr);
578                 if (includeport)
579                 {
580                         if (stringbuffersize >= 88)
581                         {
582                                 dpsnprintf(string, stringbuffersize, "[%x:%x:%x:%x:%x:%x:%x:%x]:%d", a[0] * 256 + a[1], a[2] * 256 + a[3], a[4] * 256 + a[5], a[6] * 256 + a[7], a[8] * 256 + a[9], a[10] * 256 + a[11], a[12] * 256 + a[13], a[14] * 256 + a[15], address->port);
583                                 return 1;
584                         }
585                 }
586                 else
587                 {
588                         if (stringbuffersize >= 80)
589                         {
590                                 dpsnprintf(string, stringbuffersize, "%x:%x:%x:%x:%x:%x:%x:%x", a[0] * 256 + a[1], a[2] * 256 + a[3], a[4] * 256 + a[5], a[6] * 256 + a[7], a[8] * 256 + a[9], a[10] * 256 + a[11], a[12] * 256 + a[13], a[14] * 256 + a[15]);
591                                 return 1;
592                         }
593                 }
594                 break;
595 #endif
596         }
597         return 0;
598 }
599
600 int LHNETADDRESS_GetAddressType(const lhnetaddress_t *address)
601 {
602         if (address)
603                 return address->addresstype;
604         else
605                 return LHNETADDRESSTYPE_NONE;
606 }
607
608 const char *LHNETADDRESS_GetInterfaceName(const lhnetaddress_t *vaddress)
609 {
610 #ifdef SUPPORTIPV6
611         lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
612
613         if (address && address->addresstype == LHNETADDRESSTYPE_INET6)
614         {
615 #ifndef _WIN32
616
617                 static char ifname [IF_NAMESIZE];
618                 
619                 if (if_indextoname(address->addr.in6.sin6_scope_id, ifname) == ifname)
620                         return ifname;
621
622 #else
623
624                 // The Win32 API doesn't have if_indextoname() until Windows Vista,
625                 // but luckily it just uses the interface ID as the interface name
626
627                 static char ifname [16];
628
629                 if (dpsnprintf(ifname, sizeof(ifname), "%lu", address->addr.in6.sin6_scope_id) > 0)
630                         return ifname;
631
632 #endif
633         }
634 #endif
635
636         return NULL;
637 }
638
639 int LHNETADDRESS_GetPort(const lhnetaddress_t *address)
640 {
641         if (!address)
642                 return -1;
643         return address->port;
644 }
645
646 int LHNETADDRESS_SetPort(lhnetaddress_t *vaddress, int port)
647 {
648         lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
649         if (!address)
650                 return 0;
651         address->port = port;
652         switch(address->addresstype)
653         {
654         case LHNETADDRESSTYPE_LOOP:
655                 return 1;
656         case LHNETADDRESSTYPE_INET4:
657                 address->addr.in.sin_port = htons((unsigned short)port);
658                 return 1;
659 #ifdef SUPPORTIPV6
660         case LHNETADDRESSTYPE_INET6:
661                 address->addr.in6.sin6_port = htons((unsigned short)port);
662                 return 1;
663 #endif
664         default:
665                 return 0;
666         }
667 }
668
669 int LHNETADDRESS_Compare(const lhnetaddress_t *vaddress1, const lhnetaddress_t *vaddress2)
670 {
671         lhnetaddressnative_t *address1 = (lhnetaddressnative_t *)vaddress1;
672         lhnetaddressnative_t *address2 = (lhnetaddressnative_t *)vaddress2;
673         if (!address1 || !address2)
674                 return 1;
675         if (address1->addresstype != address2->addresstype)
676                 return 1;
677         switch(address1->addresstype)
678         {
679         case LHNETADDRESSTYPE_LOOP:
680                 if (address1->port != address2->port)
681                         return -1;
682                 return 0;
683         case LHNETADDRESSTYPE_INET4:
684                 if (address1->addr.in.sin_family != address2->addr.in.sin_family)
685                         return 1;
686                 if (memcmp(&address1->addr.in.sin_addr, &address2->addr.in.sin_addr, sizeof(address1->addr.in.sin_addr)))
687                         return 1;
688                 if (address1->port != address2->port)
689                         return -1;
690                 return 0;
691 #ifdef SUPPORTIPV6
692         case LHNETADDRESSTYPE_INET6:
693                 if (address1->addr.in6.sin6_family != address2->addr.in6.sin6_family)
694                         return 1;
695                 if (memcmp(&address1->addr.in6.sin6_addr, &address2->addr.in6.sin6_addr, sizeof(address1->addr.in6.sin6_addr)))
696                         return 1;
697                 if (address1->port != address2->port)
698                         return -1;
699                 return 0;
700 #endif
701         default:
702                 return 1;
703         }
704 }
705
706 typedef struct lhnetpacket_s
707 {
708         void *data;
709         int length;
710         int sourceport;
711         int destinationport;
712         time_t timeout;
713 #ifndef STANDALONETEST
714         double sentdoubletime;
715 #endif
716         struct lhnetpacket_s *next, *prev;
717 }
718 lhnetpacket_t;
719
720 static int lhnet_active;
721 static lhnetsocket_t lhnet_socketlist;
722 static lhnetpacket_t lhnet_packetlist;
723 #ifdef WIN32
724 static int lhnet_didWSAStartup = 0;
725 static WSADATA lhnet_winsockdata;
726 #endif
727
728 void LHNET_Init(void)
729 {
730         if (lhnet_active)
731                 return;
732         lhnet_socketlist.next = lhnet_socketlist.prev = &lhnet_socketlist;
733         lhnet_packetlist.next = lhnet_packetlist.prev = &lhnet_packetlist;
734         lhnet_active = 1;
735 #ifdef WIN32
736         lhnet_didWSAStartup = !WSAStartup(MAKEWORD(1, 1), &lhnet_winsockdata);
737         if (!lhnet_didWSAStartup)
738                 Con_Print("LHNET_Init: WSAStartup failed, networking disabled\n");
739 #endif
740 }
741
742 void LHNET_Shutdown(void)
743 {
744         lhnetpacket_t *p;
745         if (!lhnet_active)
746                 return;
747         while (lhnet_socketlist.next != &lhnet_socketlist)
748                 LHNET_CloseSocket(lhnet_socketlist.next);
749         while (lhnet_packetlist.next != &lhnet_packetlist)
750         {
751                 p = lhnet_packetlist.next;
752                 p->prev->next = p->next;
753                 p->next->prev = p->prev;
754                 Z_Free(p);
755         }
756 #ifdef WIN32
757         if (lhnet_didWSAStartup)
758         {
759                 lhnet_didWSAStartup = 0;
760                 WSACleanup();
761         }
762 #endif
763         lhnet_active = 0;
764 }
765
766 static const char *LHNETPRIVATE_StrError(void)
767 {
768 #ifdef WIN32
769         int i = WSAGetLastError();
770         switch (i)
771         {
772                 case WSAEINTR:           return "WSAEINTR";
773                 case WSAEBADF:           return "WSAEBADF";
774                 case WSAEACCES:          return "WSAEACCES";
775                 case WSAEFAULT:          return "WSAEFAULT";
776                 case WSAEINVAL:          return "WSAEINVAL";
777                 case WSAEMFILE:          return "WSAEMFILE";
778                 case WSAEWOULDBLOCK:     return "WSAEWOULDBLOCK";
779                 case WSAEINPROGRESS:     return "WSAEINPROGRESS";
780                 case WSAEALREADY:        return "WSAEALREADY";
781                 case WSAENOTSOCK:        return "WSAENOTSOCK";
782                 case WSAEDESTADDRREQ:    return "WSAEDESTADDRREQ";
783                 case WSAEMSGSIZE:        return "WSAEMSGSIZE";
784                 case WSAEPROTOTYPE:      return "WSAEPROTOTYPE";
785                 case WSAENOPROTOOPT:     return "WSAENOPROTOOPT";
786                 case WSAEPROTONOSUPPORT: return "WSAEPROTONOSUPPORT";
787                 case WSAESOCKTNOSUPPORT: return "WSAESOCKTNOSUPPORT";
788                 case WSAEOPNOTSUPP:      return "WSAEOPNOTSUPP";
789                 case WSAEPFNOSUPPORT:    return "WSAEPFNOSUPPORT";
790                 case WSAEAFNOSUPPORT:    return "WSAEAFNOSUPPORT";
791                 case WSAEADDRINUSE:      return "WSAEADDRINUSE";
792                 case WSAEADDRNOTAVAIL:   return "WSAEADDRNOTAVAIL";
793                 case WSAENETDOWN:        return "WSAENETDOWN";
794                 case WSAENETUNREACH:     return "WSAENETUNREACH";
795                 case WSAENETRESET:       return "WSAENETRESET";
796                 case WSAECONNABORTED:    return "WSAECONNABORTED";
797                 case WSAECONNRESET:      return "WSAECONNRESET";
798                 case WSAENOBUFS:         return "WSAENOBUFS";
799                 case WSAEISCONN:         return "WSAEISCONN";
800                 case WSAENOTCONN:        return "WSAENOTCONN";
801                 case WSAESHUTDOWN:       return "WSAESHUTDOWN";
802                 case WSAETOOMANYREFS:    return "WSAETOOMANYREFS";
803                 case WSAETIMEDOUT:       return "WSAETIMEDOUT";
804                 case WSAECONNREFUSED:    return "WSAECONNREFUSED";
805                 case WSAELOOP:           return "WSAELOOP";
806                 case WSAENAMETOOLONG:    return "WSAENAMETOOLONG";
807                 case WSAEHOSTDOWN:       return "WSAEHOSTDOWN";
808                 case WSAEHOSTUNREACH:    return "WSAEHOSTUNREACH";
809                 case WSAENOTEMPTY:       return "WSAENOTEMPTY";
810                 case WSAEPROCLIM:        return "WSAEPROCLIM";
811                 case WSAEUSERS:          return "WSAEUSERS";
812                 case WSAEDQUOT:          return "WSAEDQUOT";
813                 case WSAESTALE:          return "WSAESTALE";
814                 case WSAEREMOTE:         return "WSAEREMOTE";
815                 case WSAEDISCON:         return "WSAEDISCON";
816                 case 0:                  return "no error";
817                 default:                 return "unknown WSAE error";
818         }
819 #else
820         return strerror(errno);
821 #endif
822 }
823
824 void LHNET_SleepUntilPacket_Microseconds(int microseconds)
825 {
826 #ifdef FD_SET
827         fd_set fdreadset;
828         struct timeval tv;
829         int lastfd;
830         lhnetsocket_t *s;
831         FD_ZERO(&fdreadset);
832         lastfd = 0;
833         for (s = lhnet_socketlist.next;s != &lhnet_socketlist;s = s->next)
834         {
835                 if (s->address.addresstype == LHNETADDRESSTYPE_INET4 || s->address.addresstype == LHNETADDRESSTYPE_INET6)
836                 {
837                         if (lastfd < s->inetsocket)
838                                 lastfd = s->inetsocket;
839                         FD_SET((unsigned int)s->inetsocket, &fdreadset);
840                 }
841         }
842         tv.tv_sec = microseconds / 1000000;
843         tv.tv_usec = microseconds % 1000000;
844         select(lastfd + 1, &fdreadset, NULL, NULL, &tv);
845 #else
846         Sys_Sleep(microseconds);
847 #endif
848 }
849
850 lhnetsocket_t *LHNET_OpenSocket_Connectionless(lhnetaddress_t *address)
851 {
852         lhnetsocket_t *lhnetsocket, *s;
853         if (!address)
854                 return NULL;
855         lhnetsocket = (lhnetsocket_t *)Z_Malloc(sizeof(*lhnetsocket));
856         if (lhnetsocket)
857         {
858                 memset(lhnetsocket, 0, sizeof(*lhnetsocket));
859                 lhnetsocket->address = *address;
860                 switch(lhnetsocket->address.addresstype)
861                 {
862                 case LHNETADDRESSTYPE_LOOP:
863                         if (lhnetsocket->address.port == 0)
864                         {
865                                 // allocate a port dynamically
866                                 // this search will always terminate because there is never
867                                 // an allocated socket with port 0, so if the number wraps it
868                                 // will find the port is unused, and then refuse to use port
869                                 // 0, causing an intentional failure condition
870                                 lhnetsocket->address.port = 1024;
871                                 for (;;)
872                                 {
873                                         for (s = lhnet_socketlist.next;s != &lhnet_socketlist;s = s->next)
874                                                 if (s->address.addresstype == lhnetsocket->address.addresstype && s->address.port == lhnetsocket->address.port)
875                                                         break;
876                                         if (s == &lhnet_socketlist)
877                                                 break;
878                                         lhnetsocket->address.port++;
879                                 }
880                         }
881                         // check if the port is available
882                         for (s = lhnet_socketlist.next;s != &lhnet_socketlist;s = s->next)
883                                 if (s->address.addresstype == lhnetsocket->address.addresstype && s->address.port == lhnetsocket->address.port)
884                                         break;
885                         if (s == &lhnet_socketlist && lhnetsocket->address.port != 0)
886                         {
887                                 lhnetsocket->next = &lhnet_socketlist;
888                                 lhnetsocket->prev = lhnetsocket->next->prev;
889                                 lhnetsocket->next->prev = lhnetsocket;
890                                 lhnetsocket->prev->next = lhnetsocket;
891                                 return lhnetsocket;
892                         }
893                         break;
894                 case LHNETADDRESSTYPE_INET4:
895 #ifdef SUPPORTIPV6
896                 case LHNETADDRESSTYPE_INET6:
897 #endif
898 #ifdef WIN32
899                         if (lhnet_didWSAStartup)
900                         {
901 #endif
902 #ifdef SUPPORTIPV6
903                                 if ((lhnetsocket->inetsocket = socket(address->addresstype == LHNETADDRESSTYPE_INET6 ? PF_INET6 : PF_INET, SOCK_DGRAM, IPPROTO_UDP)) != -1)
904 #else
905                                 if ((lhnetsocket->inetsocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) != -1)
906 #endif
907                                 {
908 #ifdef WIN32
909                                         u_long _false = 0;
910 #endif
911 #ifdef MSG_DONTWAIT
912                                         if (1)
913 #else
914 #ifdef WIN32
915                                         u_long _true = 1;
916 #else
917                                         char _true = 1;
918 #endif
919                                         if (ioctlsocket(lhnetsocket->inetsocket, FIONBIO, &_true) != -1)
920 #endif
921                                         {
922 #ifdef IPV6_V6ONLY
923                                                 // We need to set this flag to tell the OS that we only listen on IPv6. If we don't
924                                                 // most OSes will create a dual-protocol socket that also listens on IPv4. In this case
925                                                 // if an IPv4 socket is already bound to the port we want, our bind() call will fail.
926                                                 int ipv6_only = 1;
927                                                 if (address->addresstype != LHNETADDRESSTYPE_INET6
928                                                         || setsockopt (lhnetsocket->inetsocket, IPPROTO_IPV6, IPV6_V6ONLY,
929                                                                                    (const char *)&ipv6_only, sizeof(ipv6_only)) == 0
930 #ifdef WIN32
931                                                         // The Win32 API only supports IPV6_V6ONLY since Windows Vista, but fortunately
932                                                         // the default value is what we want on Win32 anyway (IPV6_V6ONLY = true)
933                                                         || SOCKETERRNO == WSAENOPROTOOPT
934 #endif
935                                                         )
936 #endif
937                                                 {
938                                                         lhnetaddressnative_t *localaddress = (lhnetaddressnative_t *)&lhnetsocket->address;
939                                                         SOCKLEN_T namelen;
940                                                         int bindresult;
941 #ifdef SUPPORTIPV6
942                                                         if (address->addresstype == LHNETADDRESSTYPE_INET6)
943                                                         {
944                                                                 namelen = sizeof(localaddress->addr.in6);
945                                                                 bindresult = bind(lhnetsocket->inetsocket, &localaddress->addr.sock, namelen);
946                                                                 if (bindresult != -1)
947                                                                         getsockname(lhnetsocket->inetsocket, &localaddress->addr.sock, &namelen);
948                                                         }
949                                                         else
950 #endif
951                                                         {
952                                                                 namelen = sizeof(localaddress->addr.in);
953                                                                 bindresult = bind(lhnetsocket->inetsocket, &localaddress->addr.sock, namelen);
954                                                                 if (bindresult != -1)
955                                                                         getsockname(lhnetsocket->inetsocket, &localaddress->addr.sock, &namelen);
956                                                         }
957                                                         if (bindresult != -1)
958                                                         {
959                                                                 int i = 1;
960                                                                 // enable broadcast on this socket
961                                                                 setsockopt(lhnetsocket->inetsocket, SOL_SOCKET, SO_BROADCAST, (char *)&i, sizeof(i));
962                                                                 lhnetsocket->next = &lhnet_socketlist;
963                                                                 lhnetsocket->prev = lhnetsocket->next->prev;
964                                                                 lhnetsocket->next->prev = lhnetsocket;
965                                                                 lhnetsocket->prev->next = lhnetsocket;
966 #ifdef WIN32
967                                                                 if (ioctlsocket(lhnetsocket->inetsocket, SIO_UDP_CONNRESET, &_false) == -1)
968                                                                         Con_DPrintf("LHNET_OpenSocket_Connectionless: ioctlsocket SIO_UDP_CONNRESET returned error: %s\n", LHNETPRIVATE_StrError());
969 #endif
970                                                                 return lhnetsocket;
971                                                         }
972                                                         else
973                                                                 Con_Printf("LHNET_OpenSocket_Connectionless: bind returned error: %s\n", LHNETPRIVATE_StrError());
974                                                 }
975 #ifdef IPV6_V6ONLY
976                                                 else
977                                                         Con_Printf("LHNET_OpenSocket_Connectionless: setsockopt(IPV6_V6ONLY) returned error: %s\n", LHNETPRIVATE_StrError());
978 #endif
979                                         }
980                                         else
981                                                 Con_Printf("LHNET_OpenSocket_Connectionless: ioctlsocket returned error: %s\n", LHNETPRIVATE_StrError());
982                                         closesocket(lhnetsocket->inetsocket);
983                                 }
984                                 else
985                                         Con_Printf("LHNET_OpenSocket_Connectionless: socket returned error: %s\n", LHNETPRIVATE_StrError());
986 #ifdef WIN32
987                         }
988                         else
989                                 Con_Print("LHNET_OpenSocket_Connectionless: can't open a socket (WSAStartup failed during LHNET_Init)\n");
990 #endif
991                         break;
992                 default:
993                         break;
994                 }
995                 Z_Free(lhnetsocket);
996         }
997         return NULL;
998 }
999
1000 void LHNET_CloseSocket(lhnetsocket_t *lhnetsocket)
1001 {
1002         if (lhnetsocket)
1003         {
1004                 // unlink from socket list
1005                 if (lhnetsocket->next == NULL)
1006                         return; // invalid!
1007                 lhnetsocket->next->prev = lhnetsocket->prev;
1008                 lhnetsocket->prev->next = lhnetsocket->next;
1009                 lhnetsocket->next = NULL;
1010                 lhnetsocket->prev = NULL;
1011
1012                 // no special close code for loopback, just inet
1013                 if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4 || lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
1014                 {
1015                         closesocket(lhnetsocket->inetsocket);
1016                 }
1017                 Z_Free(lhnetsocket);
1018         }
1019 }
1020
1021 lhnetaddress_t *LHNET_AddressFromSocket(lhnetsocket_t *sock)
1022 {
1023         if (sock)
1024                 return &sock->address;
1025         else
1026                 return NULL;
1027 }
1028
1029 int LHNET_Read(lhnetsocket_t *lhnetsocket, void *content, int maxcontentlength, lhnetaddress_t *vaddress)
1030 {
1031         lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
1032         int value = 0;
1033         if (!lhnetsocket || !address || !content || maxcontentlength < 1)
1034                 return -1;
1035         if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_LOOP)
1036         {
1037                 time_t currenttime;
1038                 lhnetpacket_t *p, *pnext;
1039                 // scan for any old packets to timeout while searching for a packet
1040                 // that is waiting to be delivered to this socket
1041                 currenttime = time(NULL);
1042                 for (p = lhnet_packetlist.next;p != &lhnet_packetlist;p = pnext)
1043                 {
1044                         pnext = p->next;
1045                         if (p->timeout < currenttime)
1046                         {
1047                                 // unlink and free
1048                                 p->next->prev = p->prev;
1049                                 p->prev->next = p->next;
1050                                 Z_Free(p);
1051                                 continue;
1052                         }
1053 #ifndef STANDALONETEST
1054                         if (cl_netlocalping.value && (realtime - cl_netlocalping.value * (1.0 / 2000.0)) < p->sentdoubletime)
1055                                 continue;
1056 #endif
1057                         if (value == 0 && p->destinationport == lhnetsocket->address.port)
1058                         {
1059                                 if (p->length <= maxcontentlength)
1060                                 {
1061                                         lhnetaddressnative_t *localaddress = (lhnetaddressnative_t *)&lhnetsocket->address;
1062                                         *address = *localaddress;
1063                                         address->port = p->sourceport;
1064                                         memcpy(content, p->data, p->length);
1065                                         value = p->length;
1066                                 }
1067                                 else
1068                                         value = -1;
1069                                 // unlink and free
1070                                 p->next->prev = p->prev;
1071                                 p->prev->next = p->next;
1072                                 Z_Free(p);
1073                         }
1074                 }
1075         }
1076         else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4)
1077         {
1078                 SOCKLEN_T inetaddresslength;
1079                 address->addresstype = LHNETADDRESSTYPE_NONE;
1080                 inetaddresslength = sizeof(address->addr.in);
1081                 value = recvfrom(lhnetsocket->inetsocket, (char *)content, maxcontentlength, LHNET_RECVFROM_FLAGS, &address->addr.sock, &inetaddresslength);
1082                 if (value > 0)
1083                 {
1084                         address->addresstype = LHNETADDRESSTYPE_INET4;
1085                         address->port = ntohs(address->addr.in.sin_port);
1086                         return value;
1087                 }
1088                 else if (value < 0)
1089                 {
1090                         int e = SOCKETERRNO;
1091                         if (e == EWOULDBLOCK)
1092                                 return 0;
1093                         switch (e)
1094                         {
1095                                 case ECONNREFUSED:
1096                                         Con_Print("Connection refused\n");
1097                                         return 0;
1098                         }
1099                         Con_Printf("LHNET_Read: recvfrom returned error: %s\n", LHNETPRIVATE_StrError());
1100                 }
1101         }
1102 #ifdef SUPPORTIPV6
1103         else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
1104         {
1105                 SOCKLEN_T inetaddresslength;
1106                 address->addresstype = LHNETADDRESSTYPE_NONE;
1107                 inetaddresslength = sizeof(address->addr.in6);
1108                 value = recvfrom(lhnetsocket->inetsocket, (char *)content, maxcontentlength, 0, &address->addr.sock, &inetaddresslength);
1109                 if (value > 0)
1110                 {
1111                         address->addresstype = LHNETADDRESSTYPE_INET6;
1112                         address->port = ntohs(address->addr.in6.sin6_port);
1113                         return value;
1114                 }
1115                 else if (value == -1)
1116                 {
1117                         int e = SOCKETERRNO;
1118                         if (e == EWOULDBLOCK)
1119                                 return 0;
1120                         switch (e)
1121                         {
1122                                 case ECONNREFUSED:
1123                                         Con_Print("Connection refused\n");
1124                                         return 0;
1125                         }
1126                         Con_Printf("LHNET_Read: recvfrom returned error: %s\n", LHNETPRIVATE_StrError());
1127                 }
1128         }
1129 #endif
1130         return value;
1131 }
1132
1133 int LHNET_Write(lhnetsocket_t *lhnetsocket, const void *content, int contentlength, const lhnetaddress_t *vaddress)
1134 {
1135         lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
1136         int value = -1;
1137         if (!lhnetsocket || !address || !content || contentlength < 1)
1138                 return -1;
1139         if (lhnetsocket->address.addresstype != address->addresstype)
1140                 return -1;
1141         if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_LOOP)
1142         {
1143                 lhnetpacket_t *p;
1144                 p = (lhnetpacket_t *)Z_Malloc(sizeof(*p) + contentlength);
1145                 p->data = (void *)(p + 1);
1146                 memcpy(p->data, content, contentlength);
1147                 p->length = contentlength;
1148                 p->sourceport = lhnetsocket->address.port;
1149                 p->destinationport = address->port;
1150                 p->timeout = time(NULL) + 10;
1151                 p->next = &lhnet_packetlist;
1152                 p->prev = p->next->prev;
1153                 p->next->prev = p;
1154                 p->prev->next = p;
1155 #ifndef STANDALONETEST
1156                 p->sentdoubletime = realtime;
1157 #endif
1158                 value = contentlength;
1159         }
1160         else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4)
1161         {
1162                 value = sendto(lhnetsocket->inetsocket, (char *)content, contentlength, LHNET_SENDTO_FLAGS, (struct sockaddr *)&address->addr.in, sizeof(struct sockaddr_in));
1163                 if (value == -1)
1164                 {
1165                         if (SOCKETERRNO == EWOULDBLOCK)
1166                                 return 0;
1167                         Con_Printf("LHNET_Write: sendto returned error: %s\n", LHNETPRIVATE_StrError());
1168                 }
1169         }
1170 #ifdef SUPPORTIPV6
1171         else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
1172         {
1173                 value = sendto(lhnetsocket->inetsocket, (char *)content, contentlength, 0, (struct sockaddr *)&address->addr.in6, sizeof(struct sockaddr_in6));
1174                 if (value == -1)
1175                 {
1176                         if (SOCKETERRNO == EWOULDBLOCK)
1177                                 return 0;
1178                         Con_Printf("LHNET_Write: sendto returned error: %s\n", LHNETPRIVATE_StrError());
1179                 }
1180         }
1181 #endif
1182         return value;
1183 }
1184
1185 #ifdef STANDALONETEST
1186 int main(int argc, char **argv)
1187 {
1188 #if 1
1189         char *buffer = "test", buffer2[1024];
1190         int blen = strlen(buffer);
1191         int b2len = 1024;
1192         lhnetsocket_t *sock1;
1193         lhnetsocket_t *sock2;
1194         lhnetaddress_t myaddy1;
1195         lhnetaddress_t myaddy2;
1196         lhnetaddress_t myaddy3;
1197         lhnetaddress_t localhostaddy1;
1198         lhnetaddress_t localhostaddy2;
1199         int test1;
1200         int test2;
1201
1202         printf("calling LHNET_Init\n");
1203         LHNET_Init();
1204
1205         printf("calling LHNET_FromPort twice to create two local addresses\n");
1206         LHNETADDRESS_FromPort(&myaddy1, LHNETADDRESSTYPE_INET4, 4000);
1207         LHNETADDRESS_FromPort(&myaddy2, LHNETADDRESSTYPE_INET4, 4001);
1208         LHNETADDRESS_FromString(&localhostaddy1, "127.0.0.1", 4000);
1209         LHNETADDRESS_FromString(&localhostaddy2, "127.0.0.1", 4001);
1210
1211         printf("calling LHNET_OpenSocket_Connectionless twice to create two local sockets\n");
1212         sock1 = LHNET_OpenSocket_Connectionless(&myaddy1);
1213         sock2 = LHNET_OpenSocket_Connectionless(&myaddy2);
1214
1215         printf("calling LHNET_Write to send a packet from the first socket to the second socket\n");
1216         test1 = LHNET_Write(sock1, buffer, blen, &localhostaddy2);
1217         printf("sleeping briefly\n");
1218 #ifdef WIN32
1219         Sleep (100);
1220 #else
1221         usleep (100000);
1222 #endif
1223         printf("calling LHNET_Read on the second socket to read the packet sent from the first socket\n");
1224         test2 = LHNET_Read(sock2, buffer2, b2len - 1, &myaddy3);
1225         if (test2 > 0)
1226                 Con_Printf("socket to socket test succeeded\n");
1227         else
1228                 Con_Printf("socket to socket test failed\n");
1229
1230 #ifdef WIN32
1231         printf("press any key to exit\n");
1232         getchar();
1233 #endif
1234
1235         printf("calling LHNET_Shutdown\n");
1236         LHNET_Shutdown();
1237         printf("exiting\n");
1238         return 0;
1239 #else
1240         lhnetsocket_t *sock[16], *sendsock;
1241         int i;
1242         int numsockets;
1243         int count;
1244         int length;
1245         int port;
1246         time_t oldtime;
1247         time_t newtime;
1248         char *sendmessage;
1249         int sendmessagelength;
1250         lhnetaddress_t destaddress;
1251         lhnetaddress_t receiveaddress;
1252         lhnetaddress_t sockaddress[16];
1253         char buffer[1536], addressstring[128], addressstring2[128];
1254         if ((argc == 2 || argc == 5) && (port = atoi(argv[1])) >= 1 && port < 65535)
1255         {
1256                 printf("calling LHNET_Init()\n");
1257                 LHNET_Init();
1258
1259                 numsockets = 0;
1260                 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_LOOP, port);
1261                 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_INET4, port);
1262                 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_INET6, port+1);
1263
1264                 sendsock = NULL;
1265                 sendmessage = NULL;
1266                 sendmessagelength = 0;
1267
1268                 for (i = 0;i < numsockets;i++)
1269                 {
1270                         LHNETADDRESS_ToString(&sockaddress[i], addressstring, sizeof(addressstring), 1);
1271                         printf("calling LHNET_OpenSocket_Connectionless(<%s>)\n", addressstring);
1272                         if ((sock[i] = LHNET_OpenSocket_Connectionless(&sockaddress[i])))
1273                         {
1274                                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
1275                                 printf("opened socket successfully (address \"%s\")\n", addressstring2);
1276                         }
1277                         else
1278                         {
1279                                 printf("failed to open socket\n");
1280                                 if (i == 0)
1281                                 {
1282                                         LHNET_Shutdown();
1283                                         return -1;
1284                                 }
1285                         }
1286                 }
1287                 count = 0;
1288                 if (argc == 5)
1289                 {
1290                         count = atoi(argv[2]);
1291                         if (LHNETADDRESS_FromString(&destaddress, argv[3], -1))
1292                         {
1293                                 sendmessage = argv[4];
1294                                 sendmessagelength = strlen(sendmessage);
1295                                 sendsock = NULL;
1296                                 for (i = 0;i < numsockets;i++)
1297                                         if (sock[i] && LHNETADDRESS_GetAddressType(&destaddress) == LHNETADDRESS_GetAddressType(&sockaddress[i]))
1298                                                 sendsock = sock[i];
1299                                 if (sendsock == NULL)
1300                                 {
1301                                         printf("Could not find an open socket matching the addresstype (%i) of destination address, switching to listen only mode\n", LHNETADDRESS_GetAddressType(&destaddress));
1302                                         argc = 2;
1303                                 }
1304                         }
1305                         else
1306                         {
1307                                 printf("LHNETADDRESS_FromString did not like the address \"%s\", switching to listen only mode\n", argv[3]);
1308                                 argc = 2;
1309                         }
1310                 }
1311                 printf("started, now listening for \"exit\" on the opened sockets\n");
1312                 oldtime = time(NULL);
1313                 for(;;)
1314                 {
1315 #ifdef WIN32
1316                         Sleep(1);
1317 #else
1318                         usleep(1);
1319 #endif
1320                         for (i = 0;i < numsockets;i++)
1321                         {
1322                                 if (sock[i])
1323                                 {
1324                                         length = LHNET_Read(sock[i], buffer, sizeof(buffer), &receiveaddress);
1325                                         if (length < 0)
1326                                                 printf("localsock read error: length < 0");
1327                                         else if (length > 0 && length < (int)sizeof(buffer))
1328                                         {
1329                                                 buffer[length] = 0;
1330                                                 LHNETADDRESS_ToString(&receiveaddress, addressstring, sizeof(addressstring), 1);
1331                                                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
1332                                                 printf("received message \"%s\" from \"%s\" on socket \"%s\"\n", buffer, addressstring, addressstring2);
1333                                                 if (!strcmp(buffer, "exit"))
1334                                                         break;
1335                                         }
1336                                 }
1337                         }
1338                         if (i < numsockets)
1339                                 break;
1340                         if (argc == 5 && count > 0)
1341                         {
1342                                 newtime = time(NULL);
1343                                 if (newtime != oldtime)
1344                                 {
1345                                         LHNETADDRESS_ToString(&destaddress, addressstring, sizeof(addressstring), 1);
1346                                         LHNETADDRESS_ToString(LHNET_AddressFromSocket(sendsock), addressstring2, sizeof(addressstring2), 1);
1347                                         printf("calling LHNET_Write(<%s>, \"%s\", %i, <%s>)\n", addressstring2, sendmessage, sendmessagelength, addressstring);
1348                                         length = LHNET_Write(sendsock, sendmessage, sendmessagelength, &destaddress);
1349                                         if (length == sendmessagelength)
1350                                                 printf("sent successfully\n");
1351                                         else
1352                                                 printf("LH_Write failed, returned %i (length of message was %i)\n", length, strlen(argv[4]));
1353                                         oldtime = newtime;
1354                                         count--;
1355                                         if (count <= 0)
1356                                                 printf("Done sending, still listening for \"exit\"\n");
1357                                 }
1358                         }
1359                 }
1360                 for (i = 0;i < numsockets;i++)
1361                 {
1362                         if (sock[i])
1363                         {
1364                                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
1365                                 printf("calling LHNET_CloseSocket(<%s>)\n", addressstring2);
1366                                 LHNET_CloseSocket(sock[i]);
1367                         }
1368                 }
1369                 printf("calling LHNET_Shutdown()\n");
1370                 LHNET_Shutdown();
1371                 return 0;
1372         }
1373         printf("Testing code for lhnet.c\nusage: lhnettest <localportnumber> [<sendnumberoftimes> <sendaddress:port> <sendmessage>]\n");
1374         return -1;
1375 #endif
1376 }
1377 #endif
1378