use separate sigaction buffers for old and new data
[musl.git] / src / network / gethostbyname2_r.c
blob0dc6dc00d62ccb7e7174d4ab9cf869818a797eb8
1 #define _GNU_SOURCE
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>
10 int gethostbyname2_r(const char *name, int af,
11 struct hostent *h, char *buf, size_t buflen,
12 struct hostent **res, int *err)
14 struct addrinfo hint = {
15 .ai_family = af==AF_INET6 ? af : AF_INET,
16 .ai_flags = AI_CANONNAME
18 struct addrinfo *ai, *p;
19 int i;
20 size_t need;
21 const char *canon;
23 af = hint.ai_family;
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;
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;
50 h->h_addrtype = af;
51 h->h_length = af==AF_INET6 ? 16 : 4;
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;
60 if (need > buflen) {
61 freeaddrinfo(ai);
62 return ERANGE;
65 h->h_aliases = (void *)buf;
66 buf += 3*sizeof(char *);
67 h->h_addr_list = (void *)buf;
68 buf += (i+1)*sizeof(char *);
70 h->h_name = h->h_aliases[0] = buf;
71 strcpy(h->h_name, canon);
72 buf += strlen(h->h_name)+1;
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;
80 h->h_aliases[2] = 0;
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);
89 h->h_addr_list[i] = 0;
91 *res = h;
92 freeaddrinfo(ai);
93 return 0;