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