3 * $Id: bres.c,v 1.1 1999/10/04 21:40:42 mdw Exp $
5 * Background reverse name resolution
7 * (c) 1999 Straylight/Edgeware
10 /*----- Licensing notice --------------------------------------------------*
12 * This file is part of the mLib utilities library.
14 * mLib is free software; you can redistribute it and/or modify
15 * it under the terms of the GNU Library General Public License as
16 * published by the Free Software Foundation; either version 2 of the
17 * License, or (at your option) any later version.
19 * mLib is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU Library General Public License for more details.
24 * You should have received a copy of the GNU Library General Public
25 * License along with mLib; if not, write to the Free
26 * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
30 /*----- Revision history --------------------------------------------------*
33 * Revision 1.1 1999/10/04 21:40:42 mdw
34 * Added background resolver from `fw'.
38 /*----- Header files ------------------------------------------------------*/
46 #include <sys/types.h>
51 #include <sys/socket.h>
52 #include <netinet/in.h>
53 #include <arpa/inet.h>
56 #include <mLib/alloc.h>
57 #include <mLib/report.h>
62 /*----- Magic numbers -----------------------------------------------------*/
64 #define BRES_MAX 15 /* Maximum number of resolvers */
65 #define BRES_IDLE 60 /* Lifetime of an idle resolver */
67 /*----- Static variables --------------------------------------------------*/
69 #ifndef BRES_STANDALONE
71 static bres_server servers[BRES_MAX]; /* Statically allocated servers */
73 #define FREE ((bres_server *)&freelist)
74 static struct { bres_server *next, *prev; } freelist = { FREE, FREE };
76 #define QUEUE ((bres_client *)&queue)
77 static struct { bres_client *next, *prev; } queue = { QUEUE, QUEUE };
79 static sel_state *sel;
81 static const char *server = 0;
85 /*----- Background resolver protocol --------------------------------------*/
87 /* --- Requests and responses --- *
89 * There are two types of requests: name and addr, corresponding to the
90 * standard @gethostbyname@ and @gethostbyaddr@ calls. There are two types
91 * of responses too: a positive response consists of an encoded equivalent of
92 * a @struct hostent@ structure containing the requested information; a
93 * negative response consists of an @h_errno@ value explaining the problem.
96 #define BRES_BYNAME 0 /* Request: resolve given name */
97 #define BRES_BYADDR 1 /* Request: resolve given address */
99 #define BRES_HOSTENT 0 /* Response: resolved ok */
100 #define BRES_ERROR 1 /* Response: resolution failed */
102 /* --- Encodings --- *
104 * A string is encoded as a @size_t@ length followed by the actual data. The
105 * null terminator is not transmitted.
107 * Addresses for resolution are transmitted as raw @struct in_addr@
110 * A @hostent@ structure is transmitted as a header containing fixed-size
111 * information, followed by the official name, an array of aliases, and an
112 * array of addresses. The number of items in the arrays is specified in the
115 * The implementation assumes that a complete request or reply is always
116 * sent. Undesirable blocking will occur if this is not the case. Both ends
117 * are assumed to trust each other. A protocol failure results in the child
118 * in question being terminated.
121 typedef struct hostskel {
128 /* --- @doread@, @dowrite@ --- *
130 * Arguments: @int fd@ = file descriptor
131 * @void *buf@ = buffer for data
132 * @size_t sz@ = size of data
134 * Returns: Zero if successful, nonzero otherwise.
136 * Use: Reads or writes a chunk of data. @EINTR@ errors are retried;
137 * incomplete reads and writes are continued from where they
138 * left off. End-of-file is considered an I/O error.
141 static int doread(int fd, void *buf, size_t sz)
145 int r = read(fd, p, sz);
160 static int dowrite(int fd, const void *buf, size_t sz)
164 int r = write(fd, p, sz);
179 /* --- @getstring@ --- *
181 * Arguments: @int fd@ = file descriptor to read
183 * Returns: String in heap-allocated block, or a null pointer.
185 * Use: Decodes a string.
188 static char *getstring(int fd)
193 if (doread(fd, &sz, sizeof(sz)) || (p = malloc(sz + 1)) == 0)
195 if (doread(fd, p, sz)) {
203 /* --- @putstring@ --- *
205 * Arguments: @int fd@ = file descriptor to write on
206 * @const char *p@ = pointer to string to write
208 * Returns: Zero if successful.
210 * Use: Encodes a string.
213 static int putstring(int fd, const char *p)
215 size_t sz = strlen(p);
216 if (dowrite(fd, &sz, sizeof(sz)) || dowrite(fd, p, sz))
221 /* --- @gethost@ --- *
223 * Arguments: @int fd@ = file descriptor to read
225 * Returns: Pointer to heap-allocated @struct hostent@, or null.
227 * Use: Decodes a host structure. The resulting structure is all in
228 * one big heap block.
231 #ifndef BRES_STANDALONE
233 static struct hostent *gethost(int fd)
240 /* --- Read the skeleton structure --- */
242 if (doread(fd, &hsk, sizeof(hsk)))
245 /* --- Read the hostname and alias strings --- *
247 * Count the length of the strings as we go.
252 sizeof(struct hostent) +
253 hsk.naddr * hsk.addrsz +
254 (hsk.naddr + hsk.nalias + 2) * sizeof(char *);
256 /* --- Read the primary host name --- */
258 if ((name = getstring(fd)) == 0)
260 sz += strlen(name) + 1;
262 /* --- Read in the alias names --- */
266 if ((alias = malloc(hsk.nalias * sizeof(char *))) == 0)
268 for (i = 0; i < hsk.nalias; i++)
270 for (i = 0; i < hsk.nalias; i++) {
271 if ((alias[i] = getstring(fd)) == 0)
273 sz += strlen(alias[i]) + 1;
277 /* --- Allocate the output structure --- */
279 if ((h = malloc(sz)) == 0)
283 /* --- Fill in the base structure --- */
285 h->h_addrtype = hsk.addrtype;
286 h->h_length = hsk.addrsz;
288 /* --- Start putting everything else in --- */
291 char **p = (char **)(h + 1);
292 char *a = (char *)(p + hsk.nalias + hsk.naddr + 2);
295 /* --- Start with the address table --- */
298 if (doread(fd, a, hsk.naddr * hsk.addrsz))
300 for (i = 0; i < hsk.naddr; i++) {
303 memcpy(&in, a, sizeof(in));
307 /* --- Finally copy the strings over --- */
309 #define PUT(_p) do { \
310 size_t _len = strlen(_p) + 1; \
311 memcpy(a, (_p), _len); \
319 for (i = 0; i < hsk.nalias; i++) {
332 /* --- Tidy up after various types of failure --- */
337 for (i = 0; i < hsk.nalias && alias[i]; i++)
349 /* --- @puthost@ --- *
351 * Arguments: @int fd@ = file descriptor
352 * @struct hostent *h@ = pointer to host structure
354 * Returns: Zero if successful.
356 * Use: Encodes a host structure.
359 static int puthost(int fd, struct hostent *h)
364 /* --- Fill in and send the skeleton structure --- */
366 for (i = 0; h->h_aliases[i]; i++)
369 for (i = 0; h->h_addr_list[i]; i++)
372 hsk.addrtype = h->h_addrtype;
373 hsk.addrsz = h->h_length;
374 if (dowrite(fd, &hsk, sizeof(hsk)))
377 /* --- Send the name and alias strings --- */
379 if (putstring(fd, h->h_name))
381 for (i = 0; h->h_aliases[i]; i++) {
382 if (putstring(fd, h->h_aliases[i]))
386 /* --- Send the address data --- */
388 for (i = 0; h->h_addr_list[i]; i++) {
389 if (dowrite(fd, h->h_addr_list[i], hsk.addrsz))
393 /* --- OK, done --- */
398 /*----- Resolver server ---------------------------------------------------*/
402 * Arguments: @int rfd@ = output file descriptor for resolved hostnames
403 * @int cfd@ = input file descriptor for raw addresses
407 * Use: Asynchronous name resolving process.
410 static void child(int rfd, int cfd)
412 /* --- Close other file descriptors --- */
416 int maxfd = sysconf(_SC_OPEN_MAX);
419 maxfd = 256; /* Fingers crossed... */
420 for (i = 0; i < maxfd; i++) {
421 if (i != rfd && i != cfd && i != 1)
426 /* --- Main request/response loop --- */
432 /* --- Read the request --- */
434 if (doread(cfd, &req, sizeof(req)))
437 /* --- Process it into a host structure --- */
441 /* --- Normal forward lookup --- */
444 char *name = getstring(cfd);
447 h = gethostbyname(name);
451 /* --- Forward lookup --- */
456 if (doread(cfd, &addr, sizeof(addr)))
458 if ((h = gethostbyaddr((char *)&addr, sizeof(addr), AF_INET)) == 0)
461 /* --- Do a forward lookup to confirm --- */
464 size_t sz = strlen(h->h_name) + 1;
465 if ((p = malloc(sz)) == 0)
467 memcpy(p, h->h_name, sz);
470 h = gethostbyname(p);
477 for (pp = h->h_addr_list; *pp; pp++) {
479 memcpy(&a, *pp, sizeof(a));
480 if (a.s_addr == addr.s_addr) {
488 h_errno = NO_RECOVERY;
493 /* --- Unknown request -- may have lost sync --- */
499 /* --- Transmit the response --- */
503 if (dowrite(rfd, &resp, sizeof(resp)) || puthost(rfd, h))
507 if (dowrite(rfd, &resp, sizeof(resp)) ||
508 dowrite(rfd, &h_errno, sizeof(h_errno)))
519 * Arguments: @int argc@ = number of command line arguments
520 * @char *argv[]@ = array of arguments
522 * Returns: Runs until killed or an error occurs.
524 * Use: A name resolver server process for mLib programs which need
525 * this sort of thing.
528 #ifdef BRES_STANDALONE
530 int main(int argc, char *argv[])
532 if (isatty(STDIN_FILENO)) {
533 char *p = strrchr(argv[0], '/');
539 "%s: don't run this program unless you know what you're doing.\n",
543 child(STDOUT_FILENO, STDIN_FILENO);
549 /*----- Main code ---------------------------------------------------------*/
551 #ifndef BRES_STANDALONE
555 * Arguments: @bres_server *rs@ = pointer to server block
559 * Use: Kills a server process, reaps the losing child and makes
560 * things generally clean again.
563 static void zap(bres_server *rs)
565 /* --- Close the pipes, kill the child, and reap it --- */
570 kill(rs->kid, SIGTERM);
571 waitpid(rs->kid, 0, 0);
575 /* --- Move the server to the back of the list --- */
577 rs->next->prev = rs->prev;
578 rs->prev->next = rs->next;
580 rs->prev = FREE->prev;
581 FREE->prev->next = rs;
585 /* --- @bres_abort@ --- *
587 * Arguments: @bres_client *rc@ = pointer to client block
591 * Use: Removes a queued job.
594 void bres_abort(bres_client *rc)
596 if (rc->q == BRES_BYNAME)
599 sel_rmfile(&rc->rs->f);
603 rc->next->prev = rc->prev;
604 rc->prev->next = rc->next;
610 * Arguments: @struct timeval *tv@ = pointer to the current time
611 * @void *vp@ = pointer to a server block
615 * Use: Kills off a child which has been idle for too long.
618 static void idle(struct timeval *tv, void *vp)
620 bres_server *rs = vp;
624 /* --- @answer@ --- *
626 * Arguments: @int fd@ = file descriptor which is ready
627 * @unsigned mode@ = what it's doing now
628 * @void *vp@ = pointer to server block
632 * Use: Retrieves an answer from a name resolver process.
635 static void attach(bres_client */*rc*/);
637 static void answer(int fd, unsigned mode, void *vp)
639 bres_server *rs = vp;
640 bres_client *rc = rs->rc;
641 struct hostent *h = 0;
645 /* --- Report the result to my client --- */
649 if (doread(fd, &resp, sizeof(resp)) == 0) {
652 doread(fd, &h_errno, sizeof(h_errno));
663 if (rc->q == BRES_BYNAME)
673 /* --- Wrap up the various structures --- */
677 rs->next = FREE->next;
679 FREE->next->prev = rs;
682 /* --- Tie a timer onto the server block --- */
687 gettimeofday(&tv, 0);
688 tv.tv_sec += BRES_IDLE;
689 sel_addtimer(sel, &rs->t, &tv, idle, rs);
692 /* --- If there are any clients waiting, attach one --- */
694 if (QUEUE->next != QUEUE) {
696 QUEUE->next = rc->next;
697 rc->next->prev = QUEUE;
704 * Arguments: @bres_server *rs@ = pointer to a server block
706 * Returns: Zero if OK, nonzero if something failed.
708 * Use: Starts up a child resolver process.
711 static int start(bres_server *rs)
716 /* --- Make the pipes --- */
723 /* --- Start up the child process --- */
725 if ((kid = fork()) < 0)
732 dup2(cfd[0], STDIN_FILENO);
733 dup2(rfd[1], STDOUT_FILENO);
736 execlp(server, server, (char *)0);
737 child(STDOUT_FILENO, STDIN_FILENO);
739 child(rfd[1], cfd[0]);
743 /* --- Fix up everything in the server block --- */
748 sel_initfile(sel, &rs->f, rfd[0], SEL_READ, answer, rs);
752 /* --- Fix up after errors --- */
764 /* --- @attach@ --- *
766 * Arguments: @bres_client *rc@ = pointer to a client block
770 * Use: Attaches a client to a spare server (which is assumed to
774 static void attach(bres_client *rc)
779 /* --- Fix up the server ready for the job --- *
781 * If the server has a process, remove its timer. Otherwise, fork off a
782 * new resolver process. This is also where I go if I find that the child
783 * resolver process has lost while I wasn't looking. Only one attempt at
784 * forking is performed.
792 if (lose || start(rs))
797 /* --- Submit the job to the resolver --- */
800 struct sigaction sa, osa;
803 /* --- Ignore @SIGPIPE@ for now --- *
805 * This way I can trap @EPIPE@ and reap a losing child, if there was one.
808 sa.sa_handler = SIG_IGN;
810 sigemptyset(&sa.sa_mask);
811 sigaction(SIGPIPE, &sa, &osa);
813 /* --- Write the new job to the child --- */
816 if (dowrite(rs->fd, &rc->q, sizeof(rc->q)))
818 else switch (rc->q) {
820 if (dowrite(rs->fd, &rc->u.addr, sizeof(rc->u.addr)))
824 if (putstring(rs->fd, rc->u.name))
828 sigaction(SIGPIPE, &osa, 0);
830 /* --- Sort out various errors --- *
832 * This was once more complicated, handling @EPIPE@ separately from other
833 * errors. Now everything's handled the same way.
842 /* --- Fiddle with lists so that everything's OK --- */
845 rs->next->prev = FREE;
846 FREE->next = rs->next;
847 rs->next = rs->prev = rs;
854 if (rc->q == BRES_BYNAME)
858 /* --- @resolve@ --- *
860 * Arguments: @bres_client *rc@ = pointer to filled-in client block
864 * Use: Dispatcher for incoming resolution jobs.
867 static void resolve(bres_client *rc)
869 /* --- If there's a free server, plug it in --- */
872 if (FREE->next == FREE) {
874 rc->prev = QUEUE->prev;
875 QUEUE->prev->next = rc;
881 /* --- @bres_byaddr@ --- *
883 * Arguments: @bres_client *rc@ = pointer to client block
884 * @struct in_addr addr@ = address to resolve
885 * @void (*func)(struct hostent *h, void *p)@ = handler function
886 * @void *p@ = argument for handler function
890 * Use: Adds an address lookup job to the queue. The job will be
891 * processed when there's a spare resolver process to deal with
895 void bres_byaddr(bres_client *rc, struct in_addr addr,
896 void (*func)(struct hostent */*h*/, void */*p*/),
906 /* --- @bres_byname@ --- *
908 * Arguments: @bres_client *rc@ = pointer to client block
909 * @const char *name@ = name to resolve
910 * @void (*func)(struct hostent *h, void *p)@ = handler function
911 * @void *p@ = argument for handler function
915 * Use: Adds a name lookup job to the queue. The job will be
916 * processed when there's a spare resolver process to deal with
920 void bres_byname(bres_client *rc, const char *name,
921 void (*func)(struct hostent */*h*/, void */*p*/),
925 rc->u.name = xstrdup(name);
931 /* --- @bres_exec@ --- *
933 * Arguments: @const char *file@ = file containing server code or null
937 * Use: Makes `bres' use a standalone server rather than copies of
938 * the current process. This can reduce memory consumption for
939 * large processes, at the expense of startup time (which
940 * shouldn't be too bad anyway, because of the resolver design).
941 * If the filename is null, a default set up at install time is
942 * used. It's probably a good idea to leave it alone.
945 void bres_exec(const char *file)
950 server = BRES_SERVER;
953 /* --- @bres_init@ --- *
955 * Arguments: @sel_state *s@ = pointer to select multiplexor
959 * Use: Initializes the background resolver for use.
962 void bres_init(sel_state *s)
967 for (i = 0; i < BRES_MAX; i++) {
968 servers[i].next = FREE;
969 servers[i].prev = FREE->prev;
972 FREE->prev->next = &servers[i];
973 FREE->prev = &servers[i];
979 /*----- That's all, folks -------------------------------------------------*/