Imported Upstream version 0.8
[platform/upstream/libasyncns.git] / libasyncns / asyncns.c
1 /***
2   This file is part of libasyncns.
3
4   Copyright 2005-2008 Lennart Poettering
5
6   libasyncns is free software; you can redistribute it and/or modify
7   it under the terms of the GNU Lesser General Public License as
8   published by the Free Software Foundation, either version 2.1 of the
9   License, or (at your option) any later version.
10
11   libasyncns is distributed in the hope that it will be useful, but
12   WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14   Lesser General Public License for more details.
15
16   You should have received a copy of the GNU Lesser General Public
17   License along with libasyncns. If not, see
18   <http://www.gnu.org/licenses/>.
19 ***/
20
21 #ifdef HAVE_CONFIG_H
22 #include <config.h>
23 #endif
24
25 /* #undef HAVE_PTHREAD */
26
27 #include <assert.h>
28 #include <fcntl.h>
29 #include <signal.h>
30 #include <unistd.h>
31 #include <sys/select.h>
32 #include <stdio.h>
33 #include <string.h>
34 #include <stdlib.h>
35 #include <errno.h>
36 #include <sys/wait.h>
37 #include <sys/types.h>
38 #include <pwd.h>
39 #include <netinet/in.h>
40 #include <arpa/nameser.h>
41 #include <resolv.h>
42 #include <dirent.h>
43 #include <sys/time.h>
44 #include <sys/resource.h>
45 #include <stdint.h>
46
47 #ifdef HAVE_SYS_PRCTL_H
48 #include <sys/prctl.h>
49 #endif
50
51 #if HAVE_PTHREAD
52 #include <pthread.h>
53 #endif
54
55 #include "asyncns.h"
56
57 #ifndef MSG_NOSIGNAL
58 #define MSG_NOSIGNAL 0
59 #endif
60
61 #define MAX_WORKERS 16
62 #define MAX_QUERIES 256
63 #define BUFSIZE (10240)
64
65 typedef enum {
66     REQUEST_ADDRINFO,
67     RESPONSE_ADDRINFO,
68     REQUEST_NAMEINFO,
69     RESPONSE_NAMEINFO,
70     REQUEST_RES_QUERY,
71     REQUEST_RES_SEARCH,
72     RESPONSE_RES,
73     REQUEST_TERMINATE,
74     RESPONSE_DIED
75 } query_type_t;
76
77 enum {
78     REQUEST_RECV_FD = 0,
79     REQUEST_SEND_FD = 1,
80     RESPONSE_RECV_FD = 2,
81     RESPONSE_SEND_FD = 3,
82     MESSAGE_FD_MAX = 4
83 };
84
85 struct asyncns {
86     int fds[4];
87
88 #ifndef HAVE_PTHREAD
89     pid_t workers[MAX_WORKERS];
90 #else
91     pthread_t workers[MAX_WORKERS];
92 #endif
93     unsigned valid_workers;
94
95     unsigned current_id, current_index;
96     asyncns_query_t* queries[MAX_QUERIES];
97
98     asyncns_query_t *done_head, *done_tail;
99
100     int n_queries;
101     int dead;
102 };
103
104 struct asyncns_query {
105     asyncns_t *asyncns;
106     int done;
107     unsigned id;
108     query_type_t type;
109     asyncns_query_t *done_next, *done_prev;
110     int ret;
111     int _errno;
112     int _h_errno;
113     struct addrinfo *addrinfo;
114     char *serv, *host;
115     void *userdata;
116 };
117
118 typedef struct rheader {
119     query_type_t type;
120     unsigned id;
121     size_t length;
122 } rheader_t;
123
124 typedef struct addrinfo_request {
125     struct rheader header;
126     int hints_is_null;
127     int ai_flags;
128     int ai_family;
129     int ai_socktype;
130     int ai_protocol;
131     size_t node_len, service_len;
132 } addrinfo_request_t;
133
134 typedef struct addrinfo_response {
135     struct rheader header;
136     int ret;
137     int _errno;
138     int _h_errno;
139     /* followed by addrinfo_serialization[] */
140 } addrinfo_response_t;
141
142 typedef struct addrinfo_serialization {
143     int ai_flags;
144     int ai_family;
145     int ai_socktype;
146     int ai_protocol;
147     size_t ai_addrlen;
148     size_t canonname_len;
149     /* Followed by ai_addr amd ai_canonname with variable lengths */
150 } addrinfo_serialization_t;
151
152 typedef struct nameinfo_request {
153     struct rheader header;
154     int flags;
155     socklen_t sockaddr_len;
156     int gethost, getserv;
157 } nameinfo_request_t;
158
159 typedef struct nameinfo_response {
160     struct rheader header;
161     size_t hostlen, servlen;
162     int ret;
163     int _errno;
164     int _h_errno;
165 } nameinfo_response_t;
166
167 typedef struct res_request {
168     struct rheader header;
169     int class;
170     int type;
171     size_t dname_len;
172 } res_request_t;
173
174 typedef struct res_response {
175     struct rheader header;
176     int ret;
177     int _errno;
178     int _h_errno;
179 } res_response_t;
180
181 typedef union packet {
182     rheader_t rheader;
183     addrinfo_request_t addrinfo_request;
184     addrinfo_response_t addrinfo_response;
185     nameinfo_request_t nameinfo_request;
186     nameinfo_response_t nameinfo_response;
187     res_request_t res_request;
188     res_response_t res_response;
189 } packet_t;
190
191 #ifndef HAVE_STRNDUP
192
193 static char *strndup(const char *s, size_t l) {
194     size_t a;
195     char *n;
196
197     a = strlen(s);
198     if (a > l)
199         a = l;
200
201     if (!(n = malloc(a+1)))
202         return NULL;
203
204     memcpy(n, s, a);
205     n[a] = 0;
206
207     return n;
208 }
209
210 #endif
211
212 #ifndef HAVE_PTHREAD
213
214 static int close_allv(const int except_fds[]) {
215     struct rlimit rl;
216     int fd, maxfd;
217
218 #ifdef __linux__
219
220     DIR *d;
221
222     assert(except_fds);
223
224     if ((d = opendir("/proc/self/fd"))) {
225
226         struct dirent *de;
227
228         while ((de = readdir(d))) {
229             int found;
230             long l;
231             char *e = NULL;
232             int i;
233
234             if (de->d_name[0] == '.')
235                 continue;
236
237             errno = 0;
238             l = strtol(de->d_name, &e, 10);
239             if (errno != 0 || !e || *e) {
240                 closedir(d);
241                 errno = EINVAL;
242                 return -1;
243             }
244
245             fd = (int) l;
246
247             if ((long) fd != l) {
248                 closedir(d);
249                 errno = EINVAL;
250                 return -1;
251             }
252
253             if (fd < 3)
254                 continue;
255
256             if (fd == dirfd(d))
257                 continue;
258
259             found = 0;
260             for (i = 0; except_fds[i] >= 0; i++)
261                 if (except_fds[i] == fd) {
262                     found = 1;
263                     break;
264                 }
265
266             if (found)
267                 continue;
268
269             if (close(fd) < 0) {
270                 int saved_errno;
271
272                 saved_errno = errno;
273                 closedir(d);
274                 errno = saved_errno;
275
276                 return -1;
277             }
278         }
279
280         closedir(d);
281         return 0;
282     }
283
284 #endif
285
286     if (getrlimit(RLIMIT_NOFILE, &rl) > 0)
287         maxfd = (int) rl.rlim_max;
288     else
289         maxfd = sysconf(_SC_OPEN_MAX);
290
291     for (fd = 3; fd < maxfd; fd++) {
292         int i, found;
293
294         found = 0;
295         for (i = 0; except_fds[i] >= 0; i++)
296             if (except_fds[i] == fd) {
297                 found = 1;
298                 continue;
299             }
300
301         if (found)
302             continue;
303
304         if (close(fd) < 0 && errno != EBADF)
305             return -1;
306     }
307
308     return 0;
309 }
310
311 static int reset_sigsv(const int except[]) {
312     int sig;
313     assert(except);
314
315     for (sig = 1; sig < NSIG; sig++) {
316         int reset = 1;
317
318         switch (sig) {
319             case SIGKILL:
320             case SIGSTOP:
321                 reset = 0;
322                 break;
323
324             default: {
325                 int i;
326
327                 for (i = 0; except[i] > 0; i++) {
328                     if (sig == except[i]) {
329                         reset = 0;
330                         break;
331                     }
332                 }
333             }
334         }
335
336         if (reset) {
337             struct sigaction sa;
338
339             memset(&sa, 0, sizeof(sa));
340             sa.sa_handler = SIG_DFL;
341
342             /* On Linux the first two RT signals are reserved by
343              * glibc, and sigaction() will return EINVAL for them. */
344             if ((sigaction(sig, &sa, NULL) < 0))
345                 if (errno != EINVAL)
346                     return -1;
347         }
348     }
349
350     return 0;
351 }
352
353 static int ignore_sigsv(const int ignore[]) {
354     int i;
355     assert(ignore);
356
357     for (i = 0; ignore[i] > 0; i++) {
358         struct sigaction sa;
359
360         memset(&sa, 0, sizeof(sa));
361         sa.sa_handler = SIG_IGN;
362
363         if ((sigaction(ignore[i], &sa, NULL) < 0))
364             return -1;
365     }
366
367     return 0;
368 }
369
370 #endif
371
372 static int fd_nonblock(int fd) {
373     int i;
374     assert(fd >= 0);
375
376     if ((i = fcntl(fd, F_GETFL, 0)) < 0)
377         return -1;
378
379     if (i & O_NONBLOCK)
380         return 0;
381
382     return fcntl(fd, F_SETFL, i | O_NONBLOCK);
383 }
384
385 static int fd_cloexec(int fd) {
386     int v;
387     assert(fd >= 0);
388
389     if ((v = fcntl(fd, F_GETFD, 0)) < 0)
390         return -1;
391
392     if (v & FD_CLOEXEC)
393         return 0;
394
395     return fcntl(fd, F_SETFD, v | FD_CLOEXEC);
396 }
397
398 static int send_died(int out_fd) {
399     rheader_t rh;
400     assert(out_fd > 0);
401
402     memset(&rh, 0, sizeof(rh));
403     rh.type = RESPONSE_DIED;
404     rh.id = 0;
405     rh.length = sizeof(rh);
406
407     return send(out_fd, &rh, rh.length, MSG_NOSIGNAL);
408 }
409
410 static void *serialize_addrinfo(void *p, const struct addrinfo *ai, size_t *length, size_t maxlength) {
411     addrinfo_serialization_t s;
412     size_t cnl, l;
413     assert(p);
414     assert(ai);
415     assert(length);
416     assert(*length <= maxlength);
417
418     cnl = (ai->ai_canonname ? strlen(ai->ai_canonname)+1 : 0);
419     l = sizeof(addrinfo_serialization_t) + ai->ai_addrlen + cnl;
420
421     if (*length + l > maxlength)
422         return NULL;
423
424     s.ai_flags = ai->ai_flags;
425     s.ai_family = ai->ai_family;
426     s.ai_socktype = ai->ai_socktype;
427     s.ai_protocol = ai->ai_protocol;
428     s.ai_addrlen = ai->ai_addrlen;
429     s.canonname_len = cnl;
430
431     memcpy((uint8_t*) p, &s, sizeof(addrinfo_serialization_t));
432     memcpy((uint8_t*) p + sizeof(addrinfo_serialization_t), ai->ai_addr, ai->ai_addrlen);
433
434     if (ai->ai_canonname)
435         strcpy((char*) p + sizeof(addrinfo_serialization_t) + ai->ai_addrlen, ai->ai_canonname);
436
437     *length += l;
438     return (uint8_t*) p + l;
439 }
440
441 static int send_addrinfo_reply(int out_fd, unsigned id, int ret, struct addrinfo *ai, int _errno, int _h_errno) {
442     addrinfo_response_t data[BUFSIZE/sizeof(addrinfo_response_t) + 1];
443     addrinfo_response_t *resp = data;
444     assert(out_fd >= 0);
445
446     memset(data, 0, sizeof(data));
447     resp->header.type = RESPONSE_ADDRINFO;
448     resp->header.id = id;
449     resp->header.length = sizeof(addrinfo_response_t);
450     resp->ret = ret;
451     resp->_errno = _errno;
452     resp->_h_errno = _h_errno;
453
454     if (ret == 0 && ai) {
455         void *p = data + 1;
456         struct addrinfo *k;
457
458         for (k = ai; k; k = k->ai_next) {
459
460             if (!(p = serialize_addrinfo(p, k, &resp->header.length, (char*) data + BUFSIZE - (char*) p))) {
461                 resp->ret = EAI_MEMORY;
462                 break;
463             }
464         }
465     }
466
467     if (ai)
468         freeaddrinfo(ai);
469
470     return send(out_fd, resp, resp->header.length, MSG_NOSIGNAL);
471 }
472
473 static int send_nameinfo_reply(int out_fd, unsigned id, int ret, const char *host, const char *serv, int _errno, int _h_errno) {
474     nameinfo_response_t data[BUFSIZE/sizeof(nameinfo_response_t) + 1];
475     size_t hl, sl;
476     nameinfo_response_t *resp = data;
477
478     assert(out_fd >= 0);
479
480     sl = serv ? strlen(serv)+1 : 0;
481     hl = host ? strlen(host)+1 : 0;
482
483     memset(data, 0, sizeof(data));
484     resp->header.type = RESPONSE_NAMEINFO;
485     resp->header.id = id;
486     resp->header.length = sizeof(nameinfo_response_t) + hl + sl;
487     resp->ret = ret;
488     resp->_errno = _errno;
489     resp->_h_errno = _h_errno;
490     resp->hostlen = hl;
491     resp->servlen = sl;
492
493     assert(sizeof(data) >= resp->header.length);
494
495     if (host)
496         memcpy((uint8_t *)data + sizeof(nameinfo_response_t), host, hl);
497
498     if (serv)
499         memcpy((uint8_t *)data + sizeof(nameinfo_response_t) + hl, serv, sl);
500
501     return send(out_fd, resp, resp->header.length, MSG_NOSIGNAL);
502 }
503
504 static int send_res_reply(int out_fd, unsigned id, const unsigned char *answer, int ret, int _errno, int _h_errno) {
505     res_response_t data[BUFSIZE/sizeof(res_response_t) + 1];
506     res_response_t *resp = data;
507
508     assert(out_fd >= 0);
509
510     memset(data, 0, sizeof(data));
511     resp->header.type = RESPONSE_RES;
512     resp->header.id = id;
513     resp->header.length = sizeof(res_response_t) + (ret < 0 ? 0 : ret);
514     resp->ret = ret;
515     resp->_errno = _errno;
516     resp->_h_errno = _h_errno;
517
518     assert(sizeof(data) >= resp->header.length);
519
520     if (ret > 0)
521         memcpy((uint8_t *)data + sizeof(res_response_t), answer, ret);
522
523     return send(out_fd, resp, resp->header.length, MSG_NOSIGNAL);
524 }
525
526 static int handle_request(int out_fd, const packet_t *packet, size_t length) {
527     const rheader_t *req;
528     assert(out_fd >= 0);
529
530     req = &packet->rheader;
531     assert(req);
532     assert(length >= sizeof(rheader_t));
533     assert(length == req->length);
534
535     switch (req->type) {
536
537         case REQUEST_ADDRINFO: {
538             struct addrinfo ai, *result = NULL;
539             const addrinfo_request_t *ai_req = &packet->addrinfo_request;
540             const char *node, *service;
541             int ret;
542
543             assert(length >= sizeof(addrinfo_request_t));
544             assert(length == sizeof(addrinfo_request_t) + ai_req->node_len + ai_req->service_len);
545
546             memset(&ai, 0, sizeof(ai));
547             ai.ai_flags = ai_req->ai_flags;
548             ai.ai_family = ai_req->ai_family;
549             ai.ai_socktype = ai_req->ai_socktype;
550             ai.ai_protocol = ai_req->ai_protocol;
551
552             node = ai_req->node_len ? (const char*) ai_req + sizeof(addrinfo_request_t) : NULL;
553             service = ai_req->service_len ? (const char*) ai_req + sizeof(addrinfo_request_t) + ai_req->node_len : NULL;
554
555             ret = getaddrinfo(node, service,
556                               ai_req->hints_is_null ? NULL : &ai,
557                               &result);
558
559             /* send_addrinfo_reply() frees result */
560             return send_addrinfo_reply(out_fd, req->id, ret, result, errno, h_errno);
561         }
562
563         case REQUEST_NAMEINFO: {
564             int ret;
565             const nameinfo_request_t *ni_req = &packet->nameinfo_request;
566             char hostbuf[NI_MAXHOST], servbuf[NI_MAXSERV];
567             struct sockaddr_storage sa;
568
569             assert(length >= sizeof(nameinfo_request_t));
570             assert(length == sizeof(nameinfo_request_t) + ni_req->sockaddr_len);
571
572             memcpy(&sa, (const uint8_t *) ni_req + sizeof(nameinfo_request_t), ni_req->sockaddr_len);
573
574             ret = getnameinfo((struct sockaddr *)&sa, ni_req->sockaddr_len,
575                               ni_req->gethost ? hostbuf : NULL, ni_req->gethost ? sizeof(hostbuf) : 0,
576                               ni_req->getserv ? servbuf : NULL, ni_req->getserv ? sizeof(servbuf) : 0,
577                               ni_req->flags);
578
579             return send_nameinfo_reply(out_fd, req->id, ret,
580                                        ret == 0 && ni_req->gethost ? hostbuf : NULL,
581                                        ret == 0 && ni_req->getserv ? servbuf : NULL,
582                                        errno, h_errno);
583         }
584
585         case REQUEST_RES_QUERY:
586         case REQUEST_RES_SEARCH: {
587             int ret;
588             HEADER answer[BUFSIZE/sizeof(HEADER) + 1];
589             const res_request_t *res_req = &packet->res_request;
590             const char *dname;
591
592             assert(length >= sizeof(res_request_t));
593             assert(length == sizeof(res_request_t) + res_req->dname_len);
594
595             dname = (const char *) req + sizeof(res_request_t);
596
597             if (req->type == REQUEST_RES_QUERY)
598                 ret = res_query(dname, res_req->class, res_req->type, (unsigned char *) answer, BUFSIZE);
599             else
600                 ret = res_search(dname, res_req->class, res_req->type, (unsigned char *) answer, BUFSIZE);
601
602             return send_res_reply(out_fd, req->id, (unsigned char *) answer, ret, errno, h_errno);
603         }
604
605         case REQUEST_TERMINATE:
606             /* Quit */
607             return -1;
608
609         default:
610             ;
611     }
612
613     return 0;
614 }
615
616 #ifndef HAVE_PTHREAD
617
618 static int process_worker(int in_fd, int out_fd) {
619     int have_death_sig = 0;
620     int good_fds[3];
621     int ret = 1;
622
623     const int ignore_sigs[] = {
624         SIGINT,
625         SIGHUP,
626         SIGPIPE,
627         SIGUSR1,
628         SIGUSR2,
629         -1
630     };
631
632     assert(in_fd > 2);
633     assert(out_fd > 2);
634
635     close(0);
636     close(1);
637     close(2);
638
639     if (open("/dev/null", O_RDONLY) != 0)
640         goto fail;
641
642     if (open("/dev/null", O_WRONLY) != 1)
643         goto fail;
644
645     if (open("/dev/null", O_WRONLY) != 2)
646         goto fail;
647
648     if (chdir("/") < 0)
649         goto fail;
650
651     if (geteuid() == 0) {
652         struct passwd *pw;
653         int r;
654
655         if ((pw = getpwnam("nobody"))) {
656 #ifdef HAVE_SETRESUID
657             r = setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid);
658 #elif HAVE_SETREUID
659             r = setreuid(pw->pw_uid, pw->pw_uid);
660 #else
661             if ((r = setuid(pw->pw_uid)) >= 0)
662                 r = seteuid(pw->pw_uid);
663 #endif
664             if (r < 0)
665                 goto fail;
666         }
667     }
668
669     if (reset_sigsv(ignore_sigs) < 0)
670         goto fail;
671
672     if (ignore_sigsv(ignore_sigs) < 0)
673         goto fail;
674
675     good_fds[0] = in_fd; good_fds[1] = out_fd; good_fds[2] = -1;
676     if (close_allv(good_fds) < 0)
677         goto fail;
678
679 #ifdef PR_SET_PDEATHSIG
680     if (prctl(PR_SET_PDEATHSIG, SIGTERM) >= 0)
681         have_death_sig = 1;
682 #endif
683
684     if (!have_death_sig)
685         fd_nonblock(in_fd);
686
687     while (getppid() > 1) { /* if the parent PID is 1 our parent process died. */
688         packet_t buf[BUFSIZE/sizeof(packet_t) + 1];
689         ssize_t length;
690
691         if (!have_death_sig) {
692             fd_set fds;
693             struct timeval tv = { 0, 500000 };
694
695             FD_ZERO(&fds);
696             FD_SET(in_fd, &fds);
697
698             if (select(in_fd+1, &fds, NULL, NULL, &tv) < 0)
699                 break;
700
701             if (getppid() == 1)
702                 break;
703         }
704
705         if ((length = recv(in_fd, buf, sizeof(buf), 0)) <= 0) {
706
707             if (length < 0 &&
708                 (errno == EAGAIN || errno == EINTR))
709                 continue;
710
711             break;
712         }
713
714         if (handle_request(out_fd, buf, (size_t) length) < 0)
715             break;
716     }
717
718     ret = 0;
719
720 fail:
721     send_died(out_fd);
722
723     return ret;
724 }
725
726 #else
727
728 static void* thread_worker(void *p) {
729     asyncns_t *asyncns = p;
730     sigset_t fullset;
731
732     /* No signals in this thread please */
733     sigfillset(&fullset);
734     pthread_sigmask(SIG_BLOCK, &fullset, NULL);
735
736     while (!asyncns->dead) {
737         packet_t buf[BUFSIZE/sizeof(packet_t) + 1];
738         ssize_t length;
739
740         if ((length = recv(asyncns->fds[REQUEST_RECV_FD], buf, sizeof(buf), 0)) <= 0) {
741
742             if (length < 0 &&
743                 (errno == EAGAIN || errno == EINTR))
744                 continue;
745
746             break;
747         }
748
749         if (asyncns->dead)
750             break;
751
752         if (handle_request(asyncns->fds[RESPONSE_SEND_FD], buf, (size_t) length) < 0)
753             break;
754     }
755
756     send_died(asyncns->fds[RESPONSE_SEND_FD]);
757
758     return NULL;
759 }
760
761 #endif
762
763 asyncns_t* asyncns_new(unsigned n_proc) {
764     asyncns_t *asyncns = NULL;
765     int i;
766     assert(n_proc >= 1);
767
768     if (n_proc > MAX_WORKERS)
769         n_proc = MAX_WORKERS;
770
771     if (!(asyncns = malloc(sizeof(asyncns_t)))) {
772         errno = ENOMEM;
773         goto fail;
774     }
775
776     asyncns->dead = 0;
777     asyncns->valid_workers = 0;
778
779     for (i = 0; i < MESSAGE_FD_MAX; i++)
780         asyncns->fds[i] = -1;
781
782     memset(asyncns->queries, 0, sizeof(asyncns->queries));
783
784     if (socketpair(PF_UNIX, SOCK_DGRAM, 0, asyncns->fds) < 0 ||
785         socketpair(PF_UNIX, SOCK_DGRAM, 0, asyncns->fds+2) < 0)
786         goto fail;
787
788     for (i = 0; i < MESSAGE_FD_MAX; i++)
789         fd_cloexec(asyncns->fds[i]);
790
791     for (asyncns->valid_workers = 0; asyncns->valid_workers < n_proc; asyncns->valid_workers++) {
792
793 #ifndef HAVE_PTHREAD
794         if ((asyncns->workers[asyncns->valid_workers] = fork()) < 0)
795             goto fail;
796         else if (asyncns->workers[asyncns->valid_workers] == 0) {
797             int ret;
798
799             close(asyncns->fds[REQUEST_SEND_FD]);
800             close(asyncns->fds[RESPONSE_RECV_FD]);
801             ret = process_worker(asyncns->fds[REQUEST_RECV_FD], asyncns->fds[RESPONSE_SEND_FD]);
802             close(asyncns->fds[REQUEST_RECV_FD]);
803             close(asyncns->fds[RESPONSE_SEND_FD]);
804             _exit(ret);
805         }
806 #else
807         int r;
808
809         if ((r = pthread_create(&asyncns->workers[asyncns->valid_workers], NULL, thread_worker, asyncns)) != 0) {
810             errno = r;
811             goto fail;
812         }
813 #endif
814     }
815
816 #ifndef HAVE_PTHREAD
817     close(asyncns->fds[REQUEST_RECV_FD]);
818     close(asyncns->fds[RESPONSE_SEND_FD]);
819     asyncns->fds[REQUEST_RECV_FD] = asyncns->fds[RESPONSE_SEND_FD] = -1;
820 #endif
821
822     asyncns->current_index = asyncns->current_id = 0;
823     asyncns->done_head = asyncns->done_tail = NULL;
824     asyncns->n_queries = 0;
825
826     fd_nonblock(asyncns->fds[RESPONSE_RECV_FD]);
827
828     return asyncns;
829
830 fail:
831     if (asyncns)
832         asyncns_free(asyncns);
833
834     return NULL;
835 }
836
837 void asyncns_free(asyncns_t *asyncns) {
838     int i;
839     int saved_errno = errno;
840     unsigned p;
841
842     assert(asyncns);
843
844     asyncns->dead = 1;
845
846     if (asyncns->fds[REQUEST_SEND_FD] >= 0) {
847         rheader_t req;
848
849         memset(&req, 0, sizeof(req));
850         req.type = REQUEST_TERMINATE;
851         req.length = sizeof(req);
852         req.id = 0;
853
854         /* Send one termination packet for each worker */
855         for (p = 0; p < asyncns->valid_workers; p++)
856             send(asyncns->fds[REQUEST_SEND_FD], &req, req.length, MSG_NOSIGNAL);
857     }
858
859     /* Now terminate them and wait until they are gone. */
860     for (p = 0; p < asyncns->valid_workers; p++) {
861 #ifndef HAVE_PTHREAD
862         kill(asyncns->workers[p], SIGTERM);
863         for (;;) {
864             if (waitpid(asyncns->workers[p], NULL, 0) >= 0 || errno != EINTR)
865                 break;
866         }
867 #else
868         for (;;) {
869             if (pthread_join(asyncns->workers[p], NULL) != EINTR)
870                 break;
871         }
872 #endif
873     }
874
875     /* Close all communication channels */
876     for (i = 0; i < MESSAGE_FD_MAX; i++)
877         if (asyncns->fds[i] >= 0)
878             close(asyncns->fds[i]);
879
880     for (p = 0; p < MAX_QUERIES; p++)
881         if (asyncns->queries[p])
882             asyncns_cancel(asyncns, asyncns->queries[p]);
883
884     free(asyncns);
885
886     errno = saved_errno;
887 }
888
889 int asyncns_fd(asyncns_t *asyncns) {
890     assert(asyncns);
891
892     return asyncns->fds[RESPONSE_RECV_FD];
893 }
894
895 static asyncns_query_t *lookup_query(asyncns_t *asyncns, unsigned id) {
896     asyncns_query_t *q;
897     assert(asyncns);
898
899     if ((q = asyncns->queries[id % MAX_QUERIES]))
900         if (q->id == id)
901             return q;
902
903     return NULL;
904 }
905
906 static void complete_query(asyncns_t *asyncns, asyncns_query_t *q) {
907     assert(asyncns);
908     assert(q);
909     assert(!q->done);
910
911     q->done = 1;
912
913     if ((q->done_prev = asyncns->done_tail))
914         asyncns->done_tail->done_next = q;
915     else
916         asyncns->done_head = q;
917
918     asyncns->done_tail = q;
919     q->done_next = NULL;
920 }
921
922 static const void *unserialize_addrinfo(const void *p, struct addrinfo **ret_ai, size_t *length) {
923     addrinfo_serialization_t s;
924     size_t l;
925     struct addrinfo *ai;
926     assert(p);
927     assert(ret_ai);
928     assert(length);
929
930     if (*length < sizeof(addrinfo_serialization_t))
931         return NULL;
932
933     memcpy(&s, p, sizeof(s));
934
935     l = sizeof(addrinfo_serialization_t) + s.ai_addrlen + s.canonname_len;
936     if (*length < l)
937         return NULL;
938
939     if (!(ai = malloc(sizeof(struct addrinfo))))
940         goto fail;
941
942     ai->ai_addr = NULL;
943     ai->ai_canonname = NULL;
944     ai->ai_next = NULL;
945
946     if (s.ai_addrlen && !(ai->ai_addr = malloc(s.ai_addrlen)))
947         goto fail;
948
949     if (s.canonname_len && !(ai->ai_canonname = malloc(s.canonname_len)))
950         goto fail;
951
952     ai->ai_flags = s.ai_flags;
953     ai->ai_family = s.ai_family;
954     ai->ai_socktype = s.ai_socktype;
955     ai->ai_protocol = s.ai_protocol;
956     ai->ai_addrlen = s.ai_addrlen;
957
958     if (ai->ai_addr)
959         memcpy(ai->ai_addr, (const uint8_t*) p + sizeof(addrinfo_serialization_t), s.ai_addrlen);
960
961     if (ai->ai_canonname)
962         memcpy(ai->ai_canonname, (const uint8_t*) p + sizeof(addrinfo_serialization_t) + s.ai_addrlen, s.canonname_len);
963
964     *length -= l;
965     *ret_ai = ai;
966
967     return (const uint8_t*) p + l;
968
969
970 fail:
971     if (ai)
972         asyncns_freeaddrinfo(ai);
973
974     return NULL;
975 }
976
977 static int handle_response(asyncns_t *asyncns, const packet_t *packet, size_t length) {
978     const rheader_t *resp;
979     asyncns_query_t *q;
980
981     assert(asyncns);
982
983     resp = &packet->rheader;
984     assert(resp);
985     assert(length >= sizeof(rheader_t));
986     assert(length == resp->length);
987
988     if (resp->type == RESPONSE_DIED) {
989         asyncns->dead = 1;
990         return 0;
991     }
992
993     if (!(q = lookup_query(asyncns, resp->id)))
994         return 0;
995
996     switch (resp->type) {
997         case RESPONSE_ADDRINFO: {
998             const addrinfo_response_t *ai_resp = &packet->addrinfo_response;
999             const void *p;
1000             size_t l;
1001             struct addrinfo *prev = NULL;
1002
1003             assert(length >= sizeof(addrinfo_response_t));
1004             assert(q->type == REQUEST_ADDRINFO);
1005
1006             q->ret = ai_resp->ret;
1007             q->_errno = ai_resp->_errno;
1008             q->_h_errno = ai_resp->_h_errno;
1009             l = length - sizeof(addrinfo_response_t);
1010             p = (const uint8_t*) resp + sizeof(addrinfo_response_t);
1011
1012             while (l > 0 && p) {
1013                 struct addrinfo *ai = NULL;
1014                 p = unserialize_addrinfo(p, &ai, &l);
1015
1016                 if (!p || !ai) {
1017                     q->ret = EAI_MEMORY;
1018                     break;
1019                 }
1020
1021                 if (prev)
1022                     prev->ai_next = ai;
1023                 else
1024                     q->addrinfo = ai;
1025
1026                 prev = ai;
1027             }
1028
1029             complete_query(asyncns, q);
1030             break;
1031         }
1032
1033         case RESPONSE_NAMEINFO: {
1034             const nameinfo_response_t *ni_resp = &packet->nameinfo_response;
1035
1036             assert(length >= sizeof(nameinfo_response_t));
1037             assert(q->type == REQUEST_NAMEINFO);
1038
1039             q->ret = ni_resp->ret;
1040             q->_errno = ni_resp->_errno;
1041             q->_h_errno = ni_resp->_h_errno;
1042
1043             if (ni_resp->hostlen)
1044                 if (!(q->host = strndup((const char*) ni_resp + sizeof(nameinfo_response_t), ni_resp->hostlen-1)))
1045                     q->ret = EAI_MEMORY;
1046
1047             if (ni_resp->servlen)
1048                 if (!(q->serv = strndup((const char*) ni_resp + sizeof(nameinfo_response_t) + ni_resp->hostlen, ni_resp->servlen-1)))
1049                     q->ret = EAI_MEMORY;
1050
1051             complete_query(asyncns, q);
1052             break;
1053         }
1054
1055         case RESPONSE_RES: {
1056             const res_response_t *res_resp = &packet->res_response;
1057
1058             assert(length >= sizeof(res_response_t));
1059             assert(q->type == REQUEST_RES_QUERY || q->type == REQUEST_RES_SEARCH);
1060
1061             q->ret = res_resp->ret;
1062             q->_errno = res_resp->_errno;
1063             q->_h_errno = res_resp->_h_errno;
1064
1065             if (res_resp->ret >= 0)  {
1066                 if (!(q->serv = malloc(res_resp->ret))) {
1067                     q->ret = -1;
1068                     q->_errno = ENOMEM;
1069                 } else
1070                     memcpy(q->serv, (const char *)resp + sizeof(res_response_t), res_resp->ret);
1071             }
1072
1073             complete_query(asyncns, q);
1074             break;
1075         }
1076
1077         default:
1078             ;
1079     }
1080
1081     return 0;
1082 }
1083
1084 int asyncns_wait(asyncns_t *asyncns, int block) {
1085     int handled = 0;
1086     assert(asyncns);
1087
1088     for (;;) {
1089         packet_t buf[BUFSIZE/sizeof(packet_t) + 1];
1090         ssize_t l;
1091
1092         if (asyncns->dead) {
1093             errno = ECHILD;
1094             return -1;
1095         }
1096
1097         if (((l = recv(asyncns->fds[RESPONSE_RECV_FD], buf, sizeof(buf), 0)) < 0)) {
1098             fd_set fds;
1099
1100             if (errno != EAGAIN)
1101                 return -1;
1102
1103             if (!block || handled)
1104                 return 0;
1105
1106             FD_ZERO(&fds);
1107             FD_SET(asyncns->fds[RESPONSE_RECV_FD], &fds);
1108
1109             if (select(asyncns->fds[RESPONSE_RECV_FD]+1, &fds, NULL, NULL, NULL) < 0)
1110                 return -1;
1111
1112             continue;
1113         }
1114
1115         if (handle_response(asyncns, buf, (size_t) l) < 0)
1116             return -1;
1117
1118         handled = 1;
1119     }
1120 }
1121
1122 static asyncns_query_t *alloc_query(asyncns_t *asyncns) {
1123     asyncns_query_t *q;
1124     assert(asyncns);
1125
1126     if (asyncns->n_queries >= MAX_QUERIES) {
1127         errno = ENOMEM;
1128         return NULL;
1129     }
1130
1131     while (asyncns->queries[asyncns->current_index]) {
1132
1133         asyncns->current_index++;
1134         asyncns->current_id++;
1135
1136         while (asyncns->current_index >= MAX_QUERIES)
1137             asyncns->current_index -= MAX_QUERIES;
1138     }
1139
1140     if (!(q = asyncns->queries[asyncns->current_index] = malloc(sizeof(asyncns_query_t)))) {
1141         errno = ENOMEM;
1142         return NULL;
1143     }
1144
1145     asyncns->n_queries++;
1146
1147     q->asyncns = asyncns;
1148     q->done = 0;
1149     q->id = asyncns->current_id;
1150     q->done_next = q->done_prev = NULL;
1151     q->ret = 0;
1152     q->_errno = 0;
1153     q->_h_errno = 0;
1154     q->addrinfo = NULL;
1155     q->userdata = NULL;
1156     q->host = q->serv = NULL;
1157
1158     return q;
1159 }
1160
1161 asyncns_query_t* asyncns_getaddrinfo(asyncns_t *asyncns, const char *node, const char *service, const struct addrinfo *hints) {
1162     addrinfo_request_t data[BUFSIZE/sizeof(addrinfo_request_t) + 1];
1163     addrinfo_request_t *req = data;
1164     asyncns_query_t *q;
1165     assert(asyncns);
1166     assert(node || service);
1167
1168     if (asyncns->dead) {
1169         errno = ECHILD;
1170         return NULL;
1171     }
1172
1173     if (!(q = alloc_query(asyncns)))
1174         return NULL;
1175
1176     memset(req, 0, sizeof(addrinfo_request_t));
1177
1178     req->node_len = node ? strlen(node)+1 : 0;
1179     req->service_len = service ? strlen(service)+1 : 0;
1180
1181     req->header.id = q->id;
1182     req->header.type = q->type = REQUEST_ADDRINFO;
1183     req->header.length = sizeof(addrinfo_request_t) + req->node_len + req->service_len;
1184
1185     if (req->header.length > BUFSIZE) {
1186         errno = ENOMEM;
1187         goto fail;
1188     }
1189
1190     if (!(req->hints_is_null = !hints)) {
1191         req->ai_flags = hints->ai_flags;
1192         req->ai_family = hints->ai_family;
1193         req->ai_socktype = hints->ai_socktype;
1194         req->ai_protocol = hints->ai_protocol;
1195     }
1196
1197     if (node)
1198         strcpy((char*) req + sizeof(addrinfo_request_t), node);
1199
1200     if (service)
1201         strcpy((char*) req + sizeof(addrinfo_request_t) + req->node_len, service);
1202
1203     if (send(asyncns->fds[REQUEST_SEND_FD], req, req->header.length, MSG_NOSIGNAL) < 0)
1204         goto fail;
1205
1206     return q;
1207
1208 fail:
1209     if (q)
1210         asyncns_cancel(asyncns, q);
1211
1212     return NULL;
1213 }
1214
1215 int asyncns_getaddrinfo_done(asyncns_t *asyncns, asyncns_query_t* q, struct addrinfo **ret_res) {
1216     int ret;
1217     assert(asyncns);
1218     assert(q);
1219     assert(q->asyncns == asyncns);
1220     assert(q->type == REQUEST_ADDRINFO);
1221
1222     if (asyncns->dead) {
1223         errno = ECHILD;
1224         return EAI_SYSTEM;
1225     }
1226
1227     if (!q->done)
1228         return EAI_AGAIN;
1229
1230     *ret_res = q->addrinfo;
1231     q->addrinfo = NULL;
1232
1233     ret = q->ret;
1234
1235     if (ret == EAI_SYSTEM)
1236         errno = q->_errno;
1237
1238     if (ret != 0)
1239         h_errno = q->_h_errno;
1240
1241     asyncns_cancel(asyncns, q);
1242
1243     return ret;
1244 }
1245
1246 asyncns_query_t* asyncns_getnameinfo(asyncns_t *asyncns, const struct sockaddr *sa, socklen_t salen, int flags, int gethost, int getserv) {
1247     nameinfo_request_t data[BUFSIZE/sizeof(nameinfo_request_t) + 1];
1248     nameinfo_request_t *req = data;
1249     asyncns_query_t *q;
1250
1251     assert(asyncns);
1252     assert(sa);
1253     assert(salen > 0);
1254
1255     if (asyncns->dead) {
1256         errno = ECHILD;
1257         return NULL;
1258     }
1259
1260     if (!(q = alloc_query(asyncns)))
1261         return NULL;
1262
1263     memset(req, 0, sizeof(nameinfo_request_t));
1264
1265     req->header.id = q->id;
1266     req->header.type = q->type = REQUEST_NAMEINFO;
1267     req->header.length = sizeof(nameinfo_request_t) + salen;
1268
1269     if (req->header.length > BUFSIZE) {
1270         errno = ENOMEM;
1271         goto fail;
1272     }
1273
1274     req->flags = flags;
1275     req->sockaddr_len = salen;
1276     req->gethost = gethost;
1277     req->getserv = getserv;
1278
1279     memcpy((uint8_t*) req + sizeof(nameinfo_request_t), sa, salen);
1280
1281     if (send(asyncns->fds[REQUEST_SEND_FD], req, req->header.length, MSG_NOSIGNAL) < 0)
1282         goto fail;
1283
1284     return q;
1285
1286 fail:
1287     if (q)
1288         asyncns_cancel(asyncns, q);
1289
1290     return NULL;
1291 }
1292
1293 int asyncns_getnameinfo_done(asyncns_t *asyncns, asyncns_query_t* q, char *ret_host, size_t hostlen, char *ret_serv, size_t servlen) {
1294     int ret;
1295     assert(asyncns);
1296     assert(q);
1297     assert(q->asyncns == asyncns);
1298     assert(q->type == REQUEST_NAMEINFO);
1299     assert(!ret_host || hostlen);
1300     assert(!ret_serv || servlen);
1301
1302     if (asyncns->dead) {
1303         errno = ECHILD;
1304         return EAI_SYSTEM;
1305     }
1306
1307     if (!q->done)
1308         return EAI_AGAIN;
1309
1310     if (ret_host && q->host) {
1311         strncpy(ret_host, q->host, hostlen);
1312         ret_host[hostlen-1] = 0;
1313     }
1314
1315     if (ret_serv && q->serv) {
1316         strncpy(ret_serv, q->serv, servlen);
1317         ret_serv[servlen-1] = 0;
1318     }
1319
1320     ret = q->ret;
1321
1322     if (ret == EAI_SYSTEM)
1323         errno = q->_errno;
1324
1325     if (ret != 0)
1326         h_errno = q->_h_errno;
1327
1328     asyncns_cancel(asyncns, q);
1329
1330     return ret;
1331 }
1332
1333 static asyncns_query_t * asyncns_res(asyncns_t *asyncns, query_type_t qtype, const char *dname, int class, int type) {
1334     res_request_t data[BUFSIZE/sizeof(res_request_t) + 1];
1335     res_request_t *req = data;
1336     asyncns_query_t *q;
1337
1338     assert(asyncns);
1339     assert(dname);
1340
1341     if (asyncns->dead) {
1342         errno = ECHILD;
1343         return NULL;
1344     }
1345
1346     if (!(q = alloc_query(asyncns)))
1347         return NULL;
1348
1349     memset(req, 0, sizeof(res_request_t));
1350
1351     req->dname_len = strlen(dname) + 1;
1352
1353     req->header.id = q->id;
1354     req->header.type = q->type = qtype;
1355     req->header.length = sizeof(res_request_t) + req->dname_len;
1356
1357     if (req->header.length > BUFSIZE) {
1358         errno = ENOMEM;
1359         goto fail;
1360     }
1361
1362     req->class = class;
1363     req->type = type;
1364
1365     strcpy((char*) req + sizeof(res_request_t), dname);
1366
1367     if (send(asyncns->fds[REQUEST_SEND_FD], req, req->header.length, MSG_NOSIGNAL) < 0)
1368         goto fail;
1369
1370     return q;
1371
1372 fail:
1373     if (q)
1374         asyncns_cancel(asyncns, q);
1375
1376     return NULL;
1377 }
1378
1379 asyncns_query_t* asyncns_res_query(asyncns_t *asyncns, const char *dname, int class, int type) {
1380     return asyncns_res(asyncns, REQUEST_RES_QUERY, dname, class, type);
1381 }
1382
1383 asyncns_query_t* asyncns_res_search(asyncns_t *asyncns, const char *dname, int class, int type) {
1384     return asyncns_res(asyncns, REQUEST_RES_SEARCH, dname, class, type);
1385 }
1386
1387 int asyncns_res_done(asyncns_t *asyncns, asyncns_query_t* q, unsigned char **answer) {
1388     int ret;
1389     assert(asyncns);
1390     assert(q);
1391     assert(q->asyncns == asyncns);
1392     assert(q->type == REQUEST_RES_QUERY || q->type == REQUEST_RES_SEARCH);
1393     assert(answer);
1394
1395     if (asyncns->dead) {
1396         errno = ECHILD;
1397         return -ECHILD;
1398     }
1399
1400     if (!q->done) {
1401         errno = EAGAIN;
1402         return -EAGAIN;
1403     }
1404
1405     *answer = (unsigned char *)q->serv;
1406     q->serv = NULL;
1407
1408     ret = q->ret;
1409
1410     if (ret < 0) {
1411         errno = q->_errno;
1412         h_errno = q->_h_errno;
1413     }
1414
1415     asyncns_cancel(asyncns, q);
1416
1417     return ret < 0 ? -errno : ret;
1418 }
1419
1420 asyncns_query_t* asyncns_getnext(asyncns_t *asyncns) {
1421     assert(asyncns);
1422     return asyncns->done_head;
1423 }
1424
1425 int asyncns_getnqueries(asyncns_t *asyncns) {
1426     assert(asyncns);
1427     return asyncns->n_queries;
1428 }
1429
1430 void asyncns_cancel(asyncns_t *asyncns, asyncns_query_t* q) {
1431     int i;
1432     int saved_errno = errno;
1433
1434     assert(asyncns);
1435     assert(q);
1436     assert(q->asyncns == asyncns);
1437     assert(asyncns->n_queries > 0);
1438
1439     if (q->done) {
1440
1441         if (q->done_prev)
1442             q->done_prev->done_next = q->done_next;
1443         else
1444             asyncns->done_head = q->done_next;
1445
1446         if (q->done_next)
1447             q->done_next->done_prev = q->done_prev;
1448         else
1449             asyncns->done_tail = q->done_prev;
1450     }
1451
1452     i = q->id % MAX_QUERIES;
1453     assert(asyncns->queries[i] == q);
1454     asyncns->queries[i] = NULL;
1455
1456     asyncns_freeaddrinfo(q->addrinfo);
1457     free(q->host);
1458     free(q->serv);
1459
1460     asyncns->n_queries--;
1461     free(q);
1462
1463     errno = saved_errno;
1464 }
1465
1466 void asyncns_freeaddrinfo(struct addrinfo *ai) {
1467     int saved_errno = errno;
1468
1469     while (ai) {
1470         struct addrinfo *next = ai->ai_next;
1471
1472         free(ai->ai_addr);
1473         free(ai->ai_canonname);
1474         free(ai);
1475
1476         ai = next;
1477     }
1478
1479     errno = saved_errno;
1480 }
1481
1482 void asyncns_freeanswer(unsigned char *answer) {
1483     int saved_errno = errno;
1484
1485     if (!answer)
1486         return;
1487
1488     /* Please note that this function is new in libasyncns 0.4. In
1489      * older versions you were supposed to free the answer directly
1490      * with free(). Hence, if this function is changed to do more than
1491      * just a simple free() this must be considered ABI/API breakage! */
1492
1493     free(answer);
1494
1495     errno = saved_errno;
1496 }
1497
1498 int asyncns_isdone(asyncns_t *asyncns, asyncns_query_t*q) {
1499     assert(asyncns);
1500     assert(q);
1501     assert(q->asyncns == asyncns);
1502
1503     return q->done;
1504 }
1505
1506 void asyncns_setuserdata(asyncns_t *asyncns, asyncns_query_t *q, void *userdata) {
1507     assert(q);
1508     assert(asyncns);
1509     assert(q->asyncns = asyncns);
1510
1511     q->userdata = userdata;
1512 }
1513
1514 void* asyncns_getuserdata(asyncns_t *asyncns, asyncns_query_t *q) {
1515     assert(q);
1516     assert(asyncns);
1517     assert(q->asyncns = asyncns);
1518
1519     return q->userdata;
1520 }