implement dn_skipname (legacy resolver function)
[musl] / src / network / gethostbyname2_r.c
1 #define _GNU_SOURCE
2
3 #include <sys/socket.h>
4 #include <netdb.h>
5 #include <string.h>
6 #include <netinet/in.h>
7 #include <errno.h>
8 #include <inttypes.h>
9
10 int gethostbyname2_r(const char *name, int af,
11         struct hostent *h, char *buf, size_t buflen,
12         struct hostent **res, int *err)
13 {
14         struct addrinfo hint = {
15                 .ai_family = af==AF_INET6 ? af : AF_INET,
16                 .ai_flags = AI_CANONNAME
17         };
18         struct addrinfo *ai, *p;
19         int i;
20         size_t need;
21         const char *canon;
22
23         af = hint.ai_family;
24
25         /* Align buffer */
26         i = (uintptr_t)buf & sizeof(char *)-1;
27         if (i) {
28                 if (buflen < sizeof(char *)-i) return ERANGE;
29                 buf += sizeof(char *)-i;
30                 buflen -= sizeof(char *)-i;
31         }
32
33         switch (getaddrinfo(name, 0, &hint, &ai)) {
34         case EAI_NONAME:
35                 *err = HOST_NOT_FOUND;
36                 return errno;
37         case EAI_AGAIN:
38                 *err = TRY_AGAIN;
39                 return errno;
40         default:
41         case EAI_MEMORY:
42         case EAI_SYSTEM:
43         case EAI_FAIL:
44                 *err = NO_RECOVERY;
45                 return errno;
46         case 0:
47                 break;
48         }
49
50         h->h_addrtype = af;
51         h->h_length = af==AF_INET6 ? 16 : 4;
52
53         canon = ai->ai_canonname ? ai->ai_canonname : name;
54         need = 4*sizeof(char *);
55         for (i=0, p=ai; p; i++, p=p->ai_next)
56                 need += sizeof(char *) + h->h_length;
57         need += strlen(name)+1;
58         need += strlen(canon)+1;
59
60         if (need > buflen) {
61                 freeaddrinfo(ai);
62                 return ERANGE;
63         }
64
65         h->h_aliases = (void *)buf;
66         buf += 3*sizeof(char *);
67         h->h_addr_list = (void *)buf;
68         buf += (i+1)*sizeof(char *);
69
70         h->h_name = h->h_aliases[0] = buf;
71         strcpy(h->h_name, canon);
72         buf += strlen(h->h_name)+1;
73
74         if (strcmp(h->h_name, name)) {
75                 h->h_aliases[1] = buf;
76                 strcpy(h->h_aliases[1], name);
77                 buf += strlen(h->h_aliases[1])+1;
78         } else h->h_aliases[1] = 0;
79
80         h->h_aliases[2] = 0;
81
82         for (i=0, p=ai; p; i++, p=p->ai_next) {
83                 h->h_addr_list[i] = (void *)buf;
84                 buf += h->h_length;
85                 memcpy(h->h_addr_list[i],
86                         &((struct sockaddr_in *)p->ai_addr)->sin_addr,
87                         h->h_length);
88         }
89         h->h_addr_list[i] = 0;
90
91         *res = h;
92         freeaddrinfo(ai);
93         return 0;
94 }