3 * $Id: bres.c,v 1.2 1999/10/30 11:28:39 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.2 1999/10/30 11:28:39 mdw
34 * Fix include error, pointed out by Chris Rutter.
36 * Revision 1.1 1999/10/04 21:40:42 mdw
37 * Added background resolver from `fw'.
41 /*----- Header files ------------------------------------------------------*/
49 #include <sys/types.h>
54 #include <sys/socket.h>
55 #include <netinet/in.h>
56 #include <arpa/inet.h>
64 /*----- Magic numbers -----------------------------------------------------*/
66 #define BRES_MAX 15 /* Maximum number of resolvers */
67 #define BRES_IDLE 60 /* Lifetime of an idle resolver */
69 /*----- Static variables --------------------------------------------------*/
71 #ifndef BRES_STANDALONE
73 static bres_server servers[BRES_MAX]; /* Statically allocated servers */
75 #define FREE ((bres_server *)&freelist)
76 static struct { bres_server *next, *prev; } freelist = { FREE, FREE };
78 #define QUEUE ((bres_client *)&queue)
79 static struct { bres_client *next, *prev; } queue = { QUEUE, QUEUE };
81 static sel_state *sel;
83 static const char *server = 0;
87 /*----- Background resolver protocol --------------------------------------*/
89 /* --- Requests and responses --- *
91 * There are two types of requests: name and addr, corresponding to the
92 * standard @gethostbyname@ and @gethostbyaddr@ calls. There are two types
93 * of responses too: a positive response consists of an encoded equivalent of
94 * a @struct hostent@ structure containing the requested information; a
95 * negative response consists of an @h_errno@ value explaining the problem.
98 #define BRES_BYNAME 0 /* Request: resolve given name */
99 #define BRES_BYADDR 1 /* Request: resolve given address */
101 #define BRES_HOSTENT 0 /* Response: resolved ok */
102 #define BRES_ERROR 1 /* Response: resolution failed */
104 /* --- Encodings --- *
106 * A string is encoded as a @size_t@ length followed by the actual data. The
107 * null terminator is not transmitted.
109 * Addresses for resolution are transmitted as raw @struct in_addr@
112 * A @hostent@ structure is transmitted as a header containing fixed-size
113 * information, followed by the official name, an array of aliases, and an
114 * array of addresses. The number of items in the arrays is specified in the
117 * The implementation assumes that a complete request or reply is always
118 * sent. Undesirable blocking will occur if this is not the case. Both ends
119 * are assumed to trust each other. A protocol failure results in the child
120 * in question being terminated.
123 typedef struct hostskel {
130 /* --- @doread@, @dowrite@ --- *
132 * Arguments: @int fd@ = file descriptor
133 * @void *buf@ = buffer for data
134 * @size_t sz@ = size of data
136 * Returns: Zero if successful, nonzero otherwise.
138 * Use: Reads or writes a chunk of data. @EINTR@ errors are retried;
139 * incomplete reads and writes are continued from where they
140 * left off. End-of-file is considered an I/O error.
143 static int doread(int fd, void *buf, size_t sz)
147 int r = read(fd, p, sz);
162 static int dowrite(int fd, const void *buf, size_t sz)
166 int r = write(fd, p, sz);
181 /* --- @getstring@ --- *
183 * Arguments: @int fd@ = file descriptor to read
185 * Returns: String in heap-allocated block, or a null pointer.
187 * Use: Decodes a string.
190 static char *getstring(int fd)
195 if (doread(fd, &sz, sizeof(sz)) || (p = malloc(sz + 1)) == 0)
197 if (doread(fd, p, sz)) {
205 /* --- @putstring@ --- *
207 * Arguments: @int fd@ = file descriptor to write on
208 * @const char *p@ = pointer to string to write
210 * Returns: Zero if successful.
212 * Use: Encodes a string.
215 static int putstring(int fd, const char *p)
217 size_t sz = strlen(p);
218 if (dowrite(fd, &sz, sizeof(sz)) || dowrite(fd, p, sz))
223 /* --- @gethost@ --- *
225 * Arguments: @int fd@ = file descriptor to read
227 * Returns: Pointer to heap-allocated @struct hostent@, or null.
229 * Use: Decodes a host structure. The resulting structure is all in
230 * one big heap block.
233 #ifndef BRES_STANDALONE
235 static struct hostent *gethost(int fd)
242 /* --- Read the skeleton structure --- */
244 if (doread(fd, &hsk, sizeof(hsk)))
247 /* --- Read the hostname and alias strings --- *
249 * Count the length of the strings as we go.
254 sizeof(struct hostent) +
255 hsk.naddr * hsk.addrsz +
256 (hsk.naddr + hsk.nalias + 2) * sizeof(char *);
258 /* --- Read the primary host name --- */
260 if ((name = getstring(fd)) == 0)
262 sz += strlen(name) + 1;
264 /* --- Read in the alias names --- */
268 if ((alias = malloc(hsk.nalias * sizeof(char *))) == 0)
270 for (i = 0; i < hsk.nalias; i++)
272 for (i = 0; i < hsk.nalias; i++) {
273 if ((alias[i] = getstring(fd)) == 0)
275 sz += strlen(alias[i]) + 1;
279 /* --- Allocate the output structure --- */
281 if ((h = malloc(sz)) == 0)
285 /* --- Fill in the base structure --- */
287 h->h_addrtype = hsk.addrtype;
288 h->h_length = hsk.addrsz;
290 /* --- Start putting everything else in --- */
293 char **p = (char **)(h + 1);
294 char *a = (char *)(p + hsk.nalias + hsk.naddr + 2);
297 /* --- Start with the address table --- */
300 if (doread(fd, a, hsk.naddr * hsk.addrsz))
302 for (i = 0; i < hsk.naddr; i++) {
305 memcpy(&in, a, sizeof(in));
309 /* --- Finally copy the strings over --- */
311 #define PUT(_p) do { \
312 size_t _len = strlen(_p) + 1; \
313 memcpy(a, (_p), _len); \
321 for (i = 0; i < hsk.nalias; i++) {
334 /* --- Tidy up after various types of failure --- */
339 for (i = 0; i < hsk.nalias && alias[i]; i++)
351 /* --- @puthost@ --- *
353 * Arguments: @int fd@ = file descriptor
354 * @struct hostent *h@ = pointer to host structure
356 * Returns: Zero if successful.
358 * Use: Encodes a host structure.
361 static int puthost(int fd, struct hostent *h)
366 /* --- Fill in and send the skeleton structure --- */
368 for (i = 0; h->h_aliases[i]; i++)
371 for (i = 0; h->h_addr_list[i]; i++)
374 hsk.addrtype = h->h_addrtype;
375 hsk.addrsz = h->h_length;
376 if (dowrite(fd, &hsk, sizeof(hsk)))
379 /* --- Send the name and alias strings --- */
381 if (putstring(fd, h->h_name))
383 for (i = 0; h->h_aliases[i]; i++) {
384 if (putstring(fd, h->h_aliases[i]))
388 /* --- Send the address data --- */
390 for (i = 0; h->h_addr_list[i]; i++) {
391 if (dowrite(fd, h->h_addr_list[i], hsk.addrsz))
395 /* --- OK, done --- */
400 /*----- Resolver server ---------------------------------------------------*/
404 * Arguments: @int rfd@ = output file descriptor for resolved hostnames
405 * @int cfd@ = input file descriptor for raw addresses
409 * Use: Asynchronous name resolving process.
412 static void child(int rfd, int cfd)
414 /* --- Close other file descriptors --- */
418 int maxfd = sysconf(_SC_OPEN_MAX);
421 maxfd = 256; /* Fingers crossed... */
422 for (i = 0; i < maxfd; i++) {
423 if (i != rfd && i != cfd && i != 1)
428 /* --- Main request/response loop --- */
434 /* --- Read the request --- */
436 if (doread(cfd, &req, sizeof(req)))
439 /* --- Process it into a host structure --- */
443 /* --- Normal forward lookup --- */
446 char *name = getstring(cfd);
449 h = gethostbyname(name);
453 /* --- Forward lookup --- */
458 if (doread(cfd, &addr, sizeof(addr)))
460 if ((h = gethostbyaddr((char *)&addr, sizeof(addr), AF_INET)) == 0)
463 /* --- Do a forward lookup to confirm --- */
466 size_t sz = strlen(h->h_name) + 1;
467 if ((p = malloc(sz)) == 0)
469 memcpy(p, h->h_name, sz);
472 h = gethostbyname(p);
479 for (pp = h->h_addr_list; *pp; pp++) {
481 memcpy(&a, *pp, sizeof(a));
482 if (a.s_addr == addr.s_addr) {
490 h_errno = NO_RECOVERY;
495 /* --- Unknown request -- may have lost sync --- */
501 /* --- Transmit the response --- */
505 if (dowrite(rfd, &resp, sizeof(resp)) || puthost(rfd, h))
509 if (dowrite(rfd, &resp, sizeof(resp)) ||
510 dowrite(rfd, &h_errno, sizeof(h_errno)))
521 * Arguments: @int argc@ = number of command line arguments
522 * @char *argv[]@ = array of arguments
524 * Returns: Runs until killed or an error occurs.
526 * Use: A name resolver server process for mLib programs which need
527 * this sort of thing.
530 #ifdef BRES_STANDALONE
532 int main(int argc, char *argv[])
534 if (isatty(STDIN_FILENO)) {
535 char *p = strrchr(argv[0], '/');
541 "%s: don't run this program unless you know what you're doing.\n",
545 child(STDOUT_FILENO, STDIN_FILENO);
551 /*----- Main code ---------------------------------------------------------*/
553 #ifndef BRES_STANDALONE
557 * Arguments: @bres_server *rs@ = pointer to server block
561 * Use: Kills a server process, reaps the losing child and makes
562 * things generally clean again.
565 static void zap(bres_server *rs)
567 /* --- Close the pipes, kill the child, and reap it --- */
572 kill(rs->kid, SIGTERM);
573 waitpid(rs->kid, 0, 0);
577 /* --- Move the server to the back of the list --- */
579 rs->next->prev = rs->prev;
580 rs->prev->next = rs->next;
582 rs->prev = FREE->prev;
583 FREE->prev->next = rs;
587 /* --- @bres_abort@ --- *
589 * Arguments: @bres_client *rc@ = pointer to client block
593 * Use: Removes a queued job.
596 void bres_abort(bres_client *rc)
598 if (rc->q == BRES_BYNAME)
601 sel_rmfile(&rc->rs->f);
605 rc->next->prev = rc->prev;
606 rc->prev->next = rc->next;
612 * Arguments: @struct timeval *tv@ = pointer to the current time
613 * @void *vp@ = pointer to a server block
617 * Use: Kills off a child which has been idle for too long.
620 static void idle(struct timeval *tv, void *vp)
622 bres_server *rs = vp;
626 /* --- @answer@ --- *
628 * Arguments: @int fd@ = file descriptor which is ready
629 * @unsigned mode@ = what it's doing now
630 * @void *vp@ = pointer to server block
634 * Use: Retrieves an answer from a name resolver process.
637 static void attach(bres_client */*rc*/);
639 static void answer(int fd, unsigned mode, void *vp)
641 bres_server *rs = vp;
642 bres_client *rc = rs->rc;
643 struct hostent *h = 0;
647 /* --- Report the result to my client --- */
651 if (doread(fd, &resp, sizeof(resp)) == 0) {
654 doread(fd, &h_errno, sizeof(h_errno));
665 if (rc->q == BRES_BYNAME)
675 /* --- Wrap up the various structures --- */
679 rs->next = FREE->next;
681 FREE->next->prev = rs;
684 /* --- Tie a timer onto the server block --- */
689 gettimeofday(&tv, 0);
690 tv.tv_sec += BRES_IDLE;
691 sel_addtimer(sel, &rs->t, &tv, idle, rs);
694 /* --- If there are any clients waiting, attach one --- */
696 if (QUEUE->next != QUEUE) {
698 QUEUE->next = rc->next;
699 rc->next->prev = QUEUE;
706 * Arguments: @bres_server *rs@ = pointer to a server block
708 * Returns: Zero if OK, nonzero if something failed.
710 * Use: Starts up a child resolver process.
713 static int start(bres_server *rs)
718 /* --- Make the pipes --- */
725 /* --- Start up the child process --- */
727 if ((kid = fork()) < 0)
734 dup2(cfd[0], STDIN_FILENO);
735 dup2(rfd[1], STDOUT_FILENO);
738 execlp(server, server, (char *)0);
739 child(STDOUT_FILENO, STDIN_FILENO);
741 child(rfd[1], cfd[0]);
745 /* --- Fix up everything in the server block --- */
750 sel_initfile(sel, &rs->f, rfd[0], SEL_READ, answer, rs);
754 /* --- Fix up after errors --- */
766 /* --- @attach@ --- *
768 * Arguments: @bres_client *rc@ = pointer to a client block
772 * Use: Attaches a client to a spare server (which is assumed to
776 static void attach(bres_client *rc)
781 /* --- Fix up the server ready for the job --- *
783 * If the server has a process, remove its timer. Otherwise, fork off a
784 * new resolver process. This is also where I go if I find that the child
785 * resolver process has lost while I wasn't looking. Only one attempt at
786 * forking is performed.
794 if (lose || start(rs))
799 /* --- Submit the job to the resolver --- */
802 struct sigaction sa, osa;
805 /* --- Ignore @SIGPIPE@ for now --- *
807 * This way I can trap @EPIPE@ and reap a losing child, if there was one.
810 sa.sa_handler = SIG_IGN;
812 sigemptyset(&sa.sa_mask);
813 sigaction(SIGPIPE, &sa, &osa);
815 /* --- Write the new job to the child --- */
818 if (dowrite(rs->fd, &rc->q, sizeof(rc->q)))
820 else switch (rc->q) {
822 if (dowrite(rs->fd, &rc->u.addr, sizeof(rc->u.addr)))
826 if (putstring(rs->fd, rc->u.name))
830 sigaction(SIGPIPE, &osa, 0);
832 /* --- Sort out various errors --- *
834 * This was once more complicated, handling @EPIPE@ separately from other
835 * errors. Now everything's handled the same way.
844 /* --- Fiddle with lists so that everything's OK --- */
847 rs->next->prev = FREE;
848 FREE->next = rs->next;
849 rs->next = rs->prev = rs;
856 if (rc->q == BRES_BYNAME)
860 /* --- @resolve@ --- *
862 * Arguments: @bres_client *rc@ = pointer to filled-in client block
866 * Use: Dispatcher for incoming resolution jobs.
869 static void resolve(bres_client *rc)
871 /* --- If there's a free server, plug it in --- */
874 if (FREE->next == FREE) {
876 rc->prev = QUEUE->prev;
877 QUEUE->prev->next = rc;
883 /* --- @bres_byaddr@ --- *
885 * Arguments: @bres_client *rc@ = pointer to client block
886 * @struct in_addr addr@ = address to resolve
887 * @void (*func)(struct hostent *h, void *p)@ = handler function
888 * @void *p@ = argument for handler function
892 * Use: Adds an address lookup job to the queue. The job will be
893 * processed when there's a spare resolver process to deal with
897 void bres_byaddr(bres_client *rc, struct in_addr addr,
898 void (*func)(struct hostent */*h*/, void */*p*/),
908 /* --- @bres_byname@ --- *
910 * Arguments: @bres_client *rc@ = pointer to client block
911 * @const char *name@ = name to resolve
912 * @void (*func)(struct hostent *h, void *p)@ = handler function
913 * @void *p@ = argument for handler function
917 * Use: Adds a name lookup job to the queue. The job will be
918 * processed when there's a spare resolver process to deal with
922 void bres_byname(bres_client *rc, const char *name,
923 void (*func)(struct hostent */*h*/, void */*p*/),
927 rc->u.name = xstrdup(name);
933 /* --- @bres_exec@ --- *
935 * Arguments: @const char *file@ = file containing server code or null
939 * Use: Makes `bres' use a standalone server rather than copies of
940 * the current process. This can reduce memory consumption for
941 * large processes, at the expense of startup time (which
942 * shouldn't be too bad anyway, because of the resolver design).
943 * If the filename is null, a default set up at install time is
944 * used. It's probably a good idea to leave it alone.
947 void bres_exec(const char *file)
952 server = BRES_SERVER;
955 /* --- @bres_init@ --- *
957 * Arguments: @sel_state *s@ = pointer to select multiplexor
961 * Use: Initializes the background resolver for use.
964 void bres_init(sel_state *s)
969 for (i = 0; i < BRES_MAX; i++) {
970 servers[i].next = FREE;
971 servers[i].prev = FREE->prev;
974 FREE->prev->next = &servers[i];
975 FREE->prev = &servers[i];
981 /*----- That's all, folks -------------------------------------------------*/