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