3 * $Id: bres.c,v 1.3 2000/06/17 10:38:35 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.3 2000/06/17 10:38:35 mdw
34 * Track changes to selbuf interface.
36 * Revision 1.2 1999/10/30 11:28:39 mdw
37 * Fix include error, pointed out by Chris Rutter.
39 * Revision 1.1 1999/10/04 21:40:42 mdw
40 * Added background resolver from `fw'.
44 /*----- Header files ------------------------------------------------------*/
52 #include <sys/types.h>
57 #include <sys/socket.h>
58 #include <netinet/in.h>
59 #include <arpa/inet.h>
67 /*----- Magic numbers -----------------------------------------------------*/
69 #define BRES_MAX 15 /* Maximum number of resolvers */
70 #define BRES_IDLE 60 /* Lifetime of an idle resolver */
72 /*----- Static variables --------------------------------------------------*/
74 #ifndef BRES_STANDALONE
76 static bres_server servers[BRES_MAX]; /* Statically allocated servers */
78 #define FREE ((bres_server *)&freelist)
79 static struct { bres_server *next, *prev; } freelist = { FREE, FREE };
81 #define QUEUE ((bres_client *)&queue)
82 static struct { bres_client *next, *prev; } queue = { QUEUE, QUEUE };
84 static sel_state *sel;
86 static const char *server = 0;
90 /*----- Background resolver protocol --------------------------------------*/
92 /* --- Requests and responses --- *
94 * There are two types of requests: name and addr, corresponding to the
95 * standard @gethostbyname@ and @gethostbyaddr@ calls. There are two types
96 * of responses too: a positive response consists of an encoded equivalent of
97 * a @struct hostent@ structure containing the requested information; a
98 * negative response consists of an @h_errno@ value explaining the problem.
101 #define BRES_BYNAME 0 /* Request: resolve given name */
102 #define BRES_BYADDR 1 /* Request: resolve given address */
104 #define BRES_HOSTENT 0 /* Response: resolved ok */
105 #define BRES_ERROR 1 /* Response: resolution failed */
107 /* --- Encodings --- *
109 * A string is encoded as a @size_t@ length followed by the actual data. The
110 * null terminator is not transmitted.
112 * Addresses for resolution are transmitted as raw @struct in_addr@
115 * A @hostent@ structure is transmitted as a header containing fixed-size
116 * information, followed by the official name, an array of aliases, and an
117 * array of addresses. The number of items in the arrays is specified in the
120 * The implementation assumes that a complete request or reply is always
121 * sent. Undesirable blocking will occur if this is not the case. Both ends
122 * are assumed to trust each other. A protocol failure results in the child
123 * in question being terminated.
126 typedef struct hostskel {
133 /* --- @doread@, @dowrite@ --- *
135 * Arguments: @int fd@ = file descriptor
136 * @void *buf@ = buffer for data
137 * @size_t sz@ = size of data
139 * Returns: Zero if successful, nonzero otherwise.
141 * Use: Reads or writes a chunk of data. @EINTR@ errors are retried;
142 * incomplete reads and writes are continued from where they
143 * left off. End-of-file is considered an I/O error.
146 static int doread(int fd, void *buf, size_t sz)
150 int r = read(fd, p, sz);
165 static int dowrite(int fd, const void *buf, size_t sz)
169 int r = write(fd, p, sz);
184 /* --- @getstring@ --- *
186 * Arguments: @int fd@ = file descriptor to read
188 * Returns: String in heap-allocated block, or a null pointer.
190 * Use: Decodes a string.
193 static char *getstring(int fd)
198 if (doread(fd, &sz, sizeof(sz)) || (p = malloc(sz + 1)) == 0)
200 if (doread(fd, p, sz)) {
208 /* --- @putstring@ --- *
210 * Arguments: @int fd@ = file descriptor to write on
211 * @const char *p@ = pointer to string to write
213 * Returns: Zero if successful.
215 * Use: Encodes a string.
218 static int putstring(int fd, const char *p)
220 size_t sz = strlen(p);
221 if (dowrite(fd, &sz, sizeof(sz)) || dowrite(fd, p, sz))
226 /* --- @gethost@ --- *
228 * Arguments: @int fd@ = file descriptor to read
230 * Returns: Pointer to heap-allocated @struct hostent@, or null.
232 * Use: Decodes a host structure. The resulting structure is all in
233 * one big heap block.
236 #ifndef BRES_STANDALONE
238 static struct hostent *gethost(int fd)
245 /* --- Read the skeleton structure --- */
247 if (doread(fd, &hsk, sizeof(hsk)))
250 /* --- Read the hostname and alias strings --- *
252 * Count the length of the strings as we go.
257 sizeof(struct hostent) +
258 hsk.naddr * hsk.addrsz +
259 (hsk.naddr + hsk.nalias + 2) * sizeof(char *);
261 /* --- Read the primary host name --- */
263 if ((name = getstring(fd)) == 0)
265 sz += strlen(name) + 1;
267 /* --- Read in the alias names --- */
271 if ((alias = malloc(hsk.nalias * sizeof(char *))) == 0)
273 for (i = 0; i < hsk.nalias; i++)
275 for (i = 0; i < hsk.nalias; i++) {
276 if ((alias[i] = getstring(fd)) == 0)
278 sz += strlen(alias[i]) + 1;
282 /* --- Allocate the output structure --- */
284 if ((h = malloc(sz)) == 0)
288 /* --- Fill in the base structure --- */
290 h->h_addrtype = hsk.addrtype;
291 h->h_length = hsk.addrsz;
293 /* --- Start putting everything else in --- */
296 char **p = (char **)(h + 1);
297 char *a = (char *)(p + hsk.nalias + hsk.naddr + 2);
300 /* --- Start with the address table --- */
303 if (doread(fd, a, hsk.naddr * hsk.addrsz))
305 for (i = 0; i < hsk.naddr; i++) {
308 memcpy(&in, a, sizeof(in));
312 /* --- Finally copy the strings over --- */
314 #define PUT(_p) do { \
315 size_t _len = strlen(_p) + 1; \
316 memcpy(a, (_p), _len); \
324 for (i = 0; i < hsk.nalias; i++) {
337 /* --- Tidy up after various types of failure --- */
342 for (i = 0; i < hsk.nalias && alias[i]; i++)
354 /* --- @puthost@ --- *
356 * Arguments: @int fd@ = file descriptor
357 * @struct hostent *h@ = pointer to host structure
359 * Returns: Zero if successful.
361 * Use: Encodes a host structure.
364 static int puthost(int fd, struct hostent *h)
369 /* --- Fill in and send the skeleton structure --- */
371 for (i = 0; h->h_aliases[i]; i++)
374 for (i = 0; h->h_addr_list[i]; i++)
377 hsk.addrtype = h->h_addrtype;
378 hsk.addrsz = h->h_length;
379 if (dowrite(fd, &hsk, sizeof(hsk)))
382 /* --- Send the name and alias strings --- */
384 if (putstring(fd, h->h_name))
386 for (i = 0; h->h_aliases[i]; i++) {
387 if (putstring(fd, h->h_aliases[i]))
391 /* --- Send the address data --- */
393 for (i = 0; h->h_addr_list[i]; i++) {
394 if (dowrite(fd, h->h_addr_list[i], hsk.addrsz))
398 /* --- OK, done --- */
403 /*----- Resolver server ---------------------------------------------------*/
407 * Arguments: @int rfd@ = output file descriptor for resolved hostnames
408 * @int cfd@ = input file descriptor for raw addresses
412 * Use: Asynchronous name resolving process.
415 static void child(int rfd, int cfd)
417 /* --- Close other file descriptors --- */
421 int maxfd = sysconf(_SC_OPEN_MAX);
424 maxfd = 256; /* Fingers crossed... */
425 for (i = 0; i < maxfd; i++) {
426 if (i != rfd && i != cfd && i != 1)
431 /* --- Main request/response loop --- */
437 /* --- Read the request --- */
439 if (doread(cfd, &req, sizeof(req)))
442 /* --- Process it into a host structure --- */
446 /* --- Normal forward lookup --- */
449 char *name = getstring(cfd);
452 h = gethostbyname(name);
456 /* --- Forward lookup --- */
461 if (doread(cfd, &addr, sizeof(addr)))
463 if ((h = gethostbyaddr((char *)&addr, sizeof(addr), AF_INET)) == 0)
466 /* --- Do a forward lookup to confirm --- */
469 size_t sz = strlen(h->h_name) + 1;
470 if ((p = malloc(sz)) == 0)
472 memcpy(p, h->h_name, sz);
475 h = gethostbyname(p);
482 for (pp = h->h_addr_list; *pp; pp++) {
484 memcpy(&a, *pp, sizeof(a));
485 if (a.s_addr == addr.s_addr) {
493 h_errno = NO_RECOVERY;
498 /* --- Unknown request -- may have lost sync --- */
504 /* --- Transmit the response --- */
508 if (dowrite(rfd, &resp, sizeof(resp)) || puthost(rfd, h))
512 if (dowrite(rfd, &resp, sizeof(resp)) ||
513 dowrite(rfd, &h_errno, sizeof(h_errno)))
524 * Arguments: @int argc@ = number of command line arguments
525 * @char *argv[]@ = array of arguments
527 * Returns: Runs until killed or an error occurs.
529 * Use: A name resolver server process for mLib programs which need
530 * this sort of thing.
533 #ifdef BRES_STANDALONE
535 int main(int argc, char *argv[])
537 if (isatty(STDIN_FILENO)) {
538 char *p = strrchr(argv[0], '/');
544 "%s: don't run this program unless you know what you're doing.\n",
548 child(STDOUT_FILENO, STDIN_FILENO);
554 /*----- Main code ---------------------------------------------------------*/
556 #ifndef BRES_STANDALONE
560 * Arguments: @bres_server *rs@ = pointer to server block
564 * Use: Kills a server process, reaps the losing child and makes
565 * things generally clean again.
568 static void zap(bres_server *rs)
570 /* --- Close the pipes, kill the child, and reap it --- */
575 kill(rs->kid, SIGTERM);
576 waitpid(rs->kid, 0, 0);
580 /* --- Move the server to the back of the list --- */
582 rs->next->prev = rs->prev;
583 rs->prev->next = rs->next;
585 rs->prev = FREE->prev;
586 FREE->prev->next = rs;
590 /* --- @bres_abort@ --- *
592 * Arguments: @bres_client *rc@ = pointer to client block
596 * Use: Removes a queued job.
599 void bres_abort(bres_client *rc)
601 if (rc->q == BRES_BYNAME)
604 sel_rmfile(&rc->rs->f);
608 rc->next->prev = rc->prev;
609 rc->prev->next = rc->next;
615 * Arguments: @struct timeval *tv@ = pointer to the current time
616 * @void *vp@ = pointer to a server block
620 * Use: Kills off a child which has been idle for too long.
623 static void idle(struct timeval *tv, void *vp)
625 bres_server *rs = vp;
629 /* --- @answer@ --- *
631 * Arguments: @int fd@ = file descriptor which is ready
632 * @unsigned mode@ = what it's doing now
633 * @void *vp@ = pointer to server block
637 * Use: Retrieves an answer from a name resolver process.
640 static void attach(bres_client */*rc*/);
642 static void answer(int fd, unsigned mode, void *vp)
644 bres_server *rs = vp;
645 bres_client *rc = rs->rc;
646 struct hostent *h = 0;
650 /* --- Report the result to my client --- */
654 if (doread(fd, &resp, sizeof(resp)) == 0) {
657 doread(fd, &h_errno, sizeof(h_errno));
668 if (rc->q == BRES_BYNAME)
678 /* --- Wrap up the various structures --- */
682 rs->next = FREE->next;
684 FREE->next->prev = rs;
687 /* --- Tie a timer onto the server block --- */
692 gettimeofday(&tv, 0);
693 tv.tv_sec += BRES_IDLE;
694 sel_addtimer(sel, &rs->t, &tv, idle, rs);
697 /* --- If there are any clients waiting, attach one --- */
699 if (QUEUE->next != QUEUE) {
701 QUEUE->next = rc->next;
702 rc->next->prev = QUEUE;
709 * Arguments: @bres_server *rs@ = pointer to a server block
711 * Returns: Zero if OK, nonzero if something failed.
713 * Use: Starts up a child resolver process.
716 static int start(bres_server *rs)
721 /* --- Make the pipes --- */
728 /* --- Start up the child process --- */
730 if ((kid = fork()) < 0)
737 dup2(cfd[0], STDIN_FILENO);
738 dup2(rfd[1], STDOUT_FILENO);
741 execlp(server, server, (char *)0);
742 child(STDOUT_FILENO, STDIN_FILENO);
744 child(rfd[1], cfd[0]);
748 /* --- Fix up everything in the server block --- */
753 sel_initfile(sel, &rs->f, rfd[0], SEL_READ, answer, rs);
757 /* --- Fix up after errors --- */
769 /* --- @attach@ --- *
771 * Arguments: @bres_client *rc@ = pointer to a client block
775 * Use: Attaches a client to a spare server (which is assumed to
779 static void attach(bres_client *rc)
784 /* --- Fix up the server ready for the job --- *
786 * If the server has a process, remove its timer. Otherwise, fork off a
787 * new resolver process. This is also where I go if I find that the child
788 * resolver process has lost while I wasn't looking. Only one attempt at
789 * forking is performed.
797 if (lose || start(rs))
802 /* --- Submit the job to the resolver --- */
805 struct sigaction sa, osa;
808 /* --- Ignore @SIGPIPE@ for now --- *
810 * This way I can trap @EPIPE@ and reap a losing child, if there was one.
813 sa.sa_handler = SIG_IGN;
815 sigemptyset(&sa.sa_mask);
816 sigaction(SIGPIPE, &sa, &osa);
818 /* --- Write the new job to the child --- */
821 if (dowrite(rs->fd, &rc->q, sizeof(rc->q)))
823 else switch (rc->q) {
825 if (dowrite(rs->fd, &rc->u.addr, sizeof(rc->u.addr)))
829 if (putstring(rs->fd, rc->u.name))
833 sigaction(SIGPIPE, &osa, 0);
835 /* --- Sort out various errors --- *
837 * This was once more complicated, handling @EPIPE@ separately from other
838 * errors. Now everything's handled the same way.
847 /* --- Fiddle with lists so that everything's OK --- */
850 rs->next->prev = FREE;
851 FREE->next = rs->next;
852 rs->next = rs->prev = rs;
859 if (rc->q == BRES_BYNAME)
863 /* --- @resolve@ --- *
865 * Arguments: @bres_client *rc@ = pointer to filled-in client block
869 * Use: Dispatcher for incoming resolution jobs.
872 static void resolve(bres_client *rc)
874 /* --- If there's a free server, plug it in --- */
877 if (FREE->next == FREE) {
879 rc->prev = QUEUE->prev;
880 QUEUE->prev->next = rc;
886 /* --- @bres_byaddr@ --- *
888 * Arguments: @bres_client *rc@ = pointer to client block
889 * @struct in_addr addr@ = address to resolve
890 * @void (*func)(struct hostent *h, void *p)@ = handler function
891 * @void *p@ = argument for handler function
895 * Use: Adds an address lookup job to the queue. The job will be
896 * processed when there's a spare resolver process to deal with
900 void bres_byaddr(bres_client *rc, struct in_addr addr,
901 void (*func)(struct hostent */*h*/, void */*p*/),
911 /* --- @bres_byname@ --- *
913 * Arguments: @bres_client *rc@ = pointer to client block
914 * @const char *name@ = name to resolve
915 * @void (*func)(struct hostent *h, void *p)@ = handler function
916 * @void *p@ = argument for handler function
920 * Use: Adds a name lookup job to the queue. The job will be
921 * processed when there's a spare resolver process to deal with
925 void bres_byname(bres_client *rc, const char *name,
926 void (*func)(struct hostent */*h*/, void */*p*/),
930 rc->u.name = xstrdup(name);
936 /* --- @bres_exec@ --- *
938 * Arguments: @const char *file@ = file containing server code or null
942 * Use: Makes `bres' use a standalone server rather than copies of
943 * the current process. This can reduce memory consumption for
944 * large processes, at the expense of startup time (which
945 * shouldn't be too bad anyway, because of the resolver design).
946 * If the filename is null, a default set up at install time is
947 * used. It's probably a good idea to leave it alone.
950 void bres_exec(const char *file)
955 server = BRES_SERVER;
958 /* --- @bres_init@ --- *
960 * Arguments: @sel_state *s@ = pointer to select multiplexor
964 * Use: Initializes the background resolver for use.
967 void bres_init(sel_state *s)
972 for (i = 0; i < BRES_MAX; i++) {
973 servers[i].next = FREE;
974 servers[i].prev = FREE->prev;
977 FREE->prev->next = &servers[i];
978 FREE->prev = &servers[i];
984 /*----- That's all, folks -------------------------------------------------*/