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