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