tinc: Add clean sources of 1.1pre10.
[tomato.git] / release / src / router / tinc / src / fake-getaddrinfo.c
blobcb821b5f5785fa67ea22fb40192abbc40e704b59
1 /*
2 * fake library for ssh
4 * This file includes getaddrinfo(), freeaddrinfo() and gai_strerror().
5 * These funtions are defined in rfc2133.
7 * But these functions are not implemented correctly. The minimum subset
8 * is implemented for ssh use only. For exapmle, this routine assumes
9 * that ai_family is AF_INET. Don't use it for another purpose.
12 #include "system.h"
14 #include "ipv4.h"
15 #include "ipv6.h"
16 #include "fake-getaddrinfo.h"
17 #include "xalloc.h"
20 #if !HAVE_DECL_GAI_STRERROR
21 char *gai_strerror(int ecode) {
22 switch (ecode) {
23 case EAI_NODATA:
24 return "No address associated with hostname";
25 case EAI_MEMORY:
26 return "Memory allocation failure";
27 case EAI_FAMILY:
28 return "Address family not supported";
29 default:
30 return "Unknown error";
33 #endif /* !HAVE_GAI_STRERROR */
35 #if !HAVE_DECL_FREEADDRINFO
36 void freeaddrinfo(struct addrinfo *ai) {
37 struct addrinfo *next;
39 while(ai) {
40 next = ai->ai_next;
41 free(ai);
42 ai = next;
45 #endif /* !HAVE_FREEADDRINFO */
47 #if !HAVE_DECL_GETADDRINFO
48 static struct addrinfo *malloc_ai(uint16_t port, uint32_t addr) {
49 struct addrinfo *ai;
51 ai = xzalloc(sizeof(struct addrinfo) + sizeof(struct sockaddr_in));
53 ai->ai_addr = (struct sockaddr *)(ai + 1);
54 ai->ai_addrlen = sizeof(struct sockaddr_in);
55 ai->ai_addr->sa_family = ai->ai_family = AF_INET;
57 ((struct sockaddr_in *)(ai)->ai_addr)->sin_port = port;
58 ((struct sockaddr_in *)(ai)->ai_addr)->sin_addr.s_addr = addr;
60 return ai;
63 int getaddrinfo(const char *hostname, const char *servname, const struct addrinfo *hints, struct addrinfo **res) {
64 struct addrinfo *prev = NULL;
65 struct hostent *hp;
66 struct in_addr in = {0};
67 int i;
68 uint16_t port = 0;
70 if(hints && hints->ai_family != AF_INET && hints->ai_family != AF_UNSPEC)
71 return EAI_FAMILY;
73 if (servname)
74 port = htons(atoi(servname));
76 if (hints && hints->ai_flags & AI_PASSIVE) {
77 *res = malloc_ai(port, htonl(0x00000000));
78 return 0;
81 if (!hostname) {
82 *res = malloc_ai(port, htonl(0x7f000001));
83 return 0;
86 hp = gethostbyname(hostname);
88 if(!hp || !hp->h_addr_list || !hp->h_addr_list[0])
89 return EAI_NODATA;
91 for (i = 0; hp->h_addr_list[i]; i++) {
92 *res = malloc_ai(port, ((struct in_addr *)hp->h_addr_list[i])->s_addr);
94 if(prev)
95 prev->ai_next = *res;
97 prev = *res;
100 return 0;
102 #endif /* !HAVE_GETADDRINFO */