3 * $Id: bres.c,v 1.4 2000/08/15 17:35:02 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.4 2000/08/15 17:35:02 mdw
34 * (gethost, and others): Since @gethost@ actually uses @malloc@ rather
35 * than @xmalloc@, it's wrong to use @xfree@ on the result. Fixed the code
36 * to use the right freeing function on the right data.
38 * Revision 1.3 2000/06/17 10:38:35 mdw
39 * Track changes to selbuf interface.
41 * Revision 1.2 1999/10/30 11:28:39 mdw
42 * Fix include error, pointed out by Chris Rutter.
44 * Revision 1.1 1999/10/04 21:40:42 mdw
45 * Added background resolver from `fw'.
49 /*----- Header files ------------------------------------------------------*/
57 #include <sys/types.h>
62 #include <sys/socket.h>
63 #include <netinet/in.h>
64 #include <arpa/inet.h>
72 /*----- Magic numbers -----------------------------------------------------*/
74 #define BRES_MAX 15 /* Maximum number of resolvers */
75 #define BRES_IDLE 60 /* Lifetime of an idle resolver */
77 /*----- Static variables --------------------------------------------------*/
79 #ifndef BRES_STANDALONE
81 static bres_server servers
[BRES_MAX
]; /* Statically allocated servers */
83 #define FREE ((bres_server *)&freelist)
84 static struct { bres_server
*next
, *prev
; } freelist
= { FREE
, FREE
};
86 #define QUEUE ((bres_client *)&queue)
87 static struct { bres_client
*next
, *prev
; } queue
= { QUEUE
, QUEUE
};
89 static sel_state
*sel
;
91 static const char *server
= 0;
95 /*----- Background resolver protocol --------------------------------------*/
97 /* --- Requests and responses --- *
99 * There are two types of requests: name and addr, corresponding to the
100 * standard @gethostbyname@ and @gethostbyaddr@ calls. There are two types
101 * of responses too: a positive response consists of an encoded equivalent of
102 * a @struct hostent@ structure containing the requested information; a
103 * negative response consists of an @h_errno@ value explaining the problem.
106 #define BRES_BYNAME 0 /* Request: resolve given name */
107 #define BRES_BYADDR 1 /* Request: resolve given address */
109 #define BRES_HOSTENT 0 /* Response: resolved ok */
110 #define BRES_ERROR 1 /* Response: resolution failed */
112 /* --- Encodings --- *
114 * A string is encoded as a @size_t@ length followed by the actual data. The
115 * null terminator is not transmitted.
117 * Addresses for resolution are transmitted as raw @struct in_addr@
120 * A @hostent@ structure is transmitted as a header containing fixed-size
121 * information, followed by the official name, an array of aliases, and an
122 * array of addresses. The number of items in the arrays is specified in the
125 * The implementation assumes that a complete request or reply is always
126 * sent. Undesirable blocking will occur if this is not the case. Both ends
127 * are assumed to trust each other. A protocol failure results in the child
128 * in question being terminated.
131 typedef struct hostskel
{
138 /* --- @doread@, @dowrite@ --- *
140 * Arguments: @int fd@ = file descriptor
141 * @void *buf@ = buffer for data
142 * @size_t sz@ = size of data
144 * Returns: Zero if successful, nonzero otherwise.
146 * Use: Reads or writes a chunk of data. @EINTR@ errors are retried;
147 * incomplete reads and writes are continued from where they
148 * left off. End-of-file is considered an I/O error.
151 static int doread(int fd
, void *buf
, size_t sz
)
155 int r
= read(fd
, p
, sz
);
170 static int dowrite(int fd
, const void *buf
, size_t sz
)
174 int r
= write(fd
, p
, sz
);
189 /* --- @getstring@ --- *
191 * Arguments: @int fd@ = file descriptor to read
193 * Returns: String in heap-allocated block, or a null pointer.
195 * Use: Decodes a string.
198 static char *getstring(int fd
)
203 if (doread(fd
, &sz
, sizeof(sz
)) || (p
= malloc(sz
+ 1)) == 0)
205 if (doread(fd
, p
, sz
)) {
213 /* --- @putstring@ --- *
215 * Arguments: @int fd@ = file descriptor to write on
216 * @const char *p@ = pointer to string to write
218 * Returns: Zero if successful.
220 * Use: Encodes a string.
223 static int putstring(int fd
, const char *p
)
225 size_t sz
= strlen(p
);
226 if (dowrite(fd
, &sz
, sizeof(sz
)) || dowrite(fd
, p
, sz
))
231 /* --- @gethost@ --- *
233 * Arguments: @int fd@ = file descriptor to read
235 * Returns: Pointer to heap-allocated @struct hostent@, or null.
237 * Use: Decodes a host structure. The resulting structure is all in
238 * one big heap block.
241 #ifndef BRES_STANDALONE
243 static struct hostent
*gethost(int fd
)
250 /* --- Read the skeleton structure --- */
252 if (doread(fd
, &hsk
, sizeof(hsk
)))
255 /* --- Read the hostname and alias strings --- *
257 * Count the length of the strings as we go.
262 sizeof(struct hostent
) +
263 hsk
.naddr
* hsk
.addrsz
+
264 (hsk
.naddr
+ hsk
.nalias
+ 2) * sizeof(char *);
266 /* --- Read the primary host name --- */
268 if ((name
= getstring(fd
)) == 0)
270 sz
+= strlen(name
) + 1;
272 /* --- Read in the alias names --- */
276 if ((alias
= malloc(hsk
.nalias
* sizeof(char *))) == 0)
278 for (i
= 0; i
< hsk
.nalias
; i
++)
280 for (i
= 0; i
< hsk
.nalias
; i
++) {
281 if ((alias
[i
] = getstring(fd
)) == 0)
283 sz
+= strlen(alias
[i
]) + 1;
287 /* --- Allocate the output structure --- */
289 if ((h
= malloc(sz
)) == 0)
293 /* --- Fill in the base structure --- */
295 h
->h_addrtype
= hsk
.addrtype
;
296 h
->h_length
= hsk
.addrsz
;
298 /* --- Start putting everything else in --- */
301 char **p
= (char **)(h
+ 1);
302 char *a
= (char *)(p
+ hsk
.nalias
+ hsk
.naddr
+ 2);
305 /* --- Start with the address table --- */
308 if (doread(fd
, a
, hsk
.naddr
* hsk
.addrsz
))
310 for (i
= 0; i
< hsk
.naddr
; i
++) {
313 memcpy(&in
, a
, sizeof(in
));
317 /* --- Finally copy the strings over --- */
319 #define PUT(_p) do { \
320 size_t _len = strlen(_p) + 1; \
321 memcpy(a, (_p), _len); \
329 for (i
= 0; i
< hsk
.nalias
; i
++) {
342 /* --- Tidy up after various types of failure --- */
347 for (i
= 0; i
< hsk
.nalias
&& alias
[i
]; i
++)
359 /* --- @puthost@ --- *
361 * Arguments: @int fd@ = file descriptor
362 * @struct hostent *h@ = pointer to host structure
364 * Returns: Zero if successful.
366 * Use: Encodes a host structure.
369 static int puthost(int fd
, struct hostent
*h
)
374 /* --- Fill in and send the skeleton structure --- */
376 for (i
= 0; h
->h_aliases
[i
]; i
++)
379 for (i
= 0; h
->h_addr_list
[i
]; i
++)
382 hsk
.addrtype
= h
->h_addrtype
;
383 hsk
.addrsz
= h
->h_length
;
384 if (dowrite(fd
, &hsk
, sizeof(hsk
)))
387 /* --- Send the name and alias strings --- */
389 if (putstring(fd
, h
->h_name
))
391 for (i
= 0; h
->h_aliases
[i
]; i
++) {
392 if (putstring(fd
, h
->h_aliases
[i
]))
396 /* --- Send the address data --- */
398 for (i
= 0; h
->h_addr_list
[i
]; i
++) {
399 if (dowrite(fd
, h
->h_addr_list
[i
], hsk
.addrsz
))
403 /* --- OK, done --- */
408 /*----- Resolver server ---------------------------------------------------*/
412 * Arguments: @int rfd@ = output file descriptor for resolved hostnames
413 * @int cfd@ = input file descriptor for raw addresses
417 * Use: Asynchronous name resolving process.
420 static void child(int rfd
, int cfd
)
422 /* --- Close other file descriptors --- */
426 int maxfd
= sysconf(_SC_OPEN_MAX
);
429 maxfd
= 256; /* Fingers crossed... */
430 for (i
= 0; i
< maxfd
; i
++) {
431 if (i
!= rfd
&& i
!= cfd
&& i
!= 1)
436 /* --- Main request/response loop --- */
442 /* --- Read the request --- */
444 if (doread(cfd
, &req
, sizeof(req
)))
447 /* --- Process it into a host structure --- */
451 /* --- Normal forward lookup --- */
454 char *name
= getstring(cfd
);
457 h
= gethostbyname(name
);
461 /* --- Reverse lookup --- */
466 if (doread(cfd
, &addr
, sizeof(addr
)))
468 if ((h
= gethostbyaddr((char *)&addr
, sizeof(addr
), AF_INET
)) == 0)
471 /* --- Do a forward lookup to confirm --- */
474 size_t sz
= strlen(h
->h_name
) + 1;
475 if ((p
= malloc(sz
)) == 0)
477 memcpy(p
, h
->h_name
, sz
);
480 h
= gethostbyname(p
);
487 for (pp
= h
->h_addr_list
; *pp
; pp
++) {
489 memcpy(&a
, *pp
, sizeof(a
));
490 if (a
.s_addr
== addr
.s_addr
) {
498 h_errno
= NO_RECOVERY
;
503 /* --- Unknown request -- may have lost sync --- */
509 /* --- Transmit the response --- */
513 if (dowrite(rfd
, &resp
, sizeof(resp
)) || puthost(rfd
, h
))
517 if (dowrite(rfd
, &resp
, sizeof(resp
)) ||
518 dowrite(rfd
, &h_errno
, sizeof(h_errno
)))
529 * Arguments: @int argc@ = number of command line arguments
530 * @char *argv[]@ = array of arguments
532 * Returns: Runs until killed or an error occurs.
534 * Use: A name resolver server process for mLib programs which need
535 * this sort of thing.
538 #ifdef BRES_STANDALONE
540 int main(int argc
, char *argv
[])
542 if (isatty(STDIN_FILENO
)) {
543 char *p
= strrchr(argv
[0], '/');
549 "%s: don't run this program unless you know what you're doing.\n",
553 child(STDOUT_FILENO
, STDIN_FILENO
);
559 /*----- Main code ---------------------------------------------------------*/
561 #ifndef BRES_STANDALONE
565 * Arguments: @bres_server *rs@ = pointer to server block
569 * Use: Kills a server process, reaps the losing child and makes
570 * things generally clean again.
573 static void zap(bres_server
*rs
)
575 /* --- Close the pipes, kill the child, and reap it --- */
580 kill(rs
->kid
, SIGTERM
);
581 waitpid(rs
->kid
, 0, 0);
585 /* --- Move the server to the back of the list --- */
587 rs
->next
->prev
= rs
->prev
;
588 rs
->prev
->next
= rs
->next
;
590 rs
->prev
= FREE
->prev
;
591 FREE
->prev
->next
= rs
;
595 /* --- @bres_abort@ --- *
597 * Arguments: @bres_client *rc@ = pointer to client block
601 * Use: Removes a queued job.
604 void bres_abort(bres_client
*rc
)
606 if (rc
->q
== BRES_BYNAME
)
609 sel_rmfile(&rc
->rs
->f
);
613 rc
->next
->prev
= rc
->prev
;
614 rc
->prev
->next
= rc
->next
;
620 * Arguments: @struct timeval *tv@ = pointer to the current time
621 * @void *vp@ = pointer to a server block
625 * Use: Kills off a child which has been idle for too long.
628 static void idle(struct timeval
*tv
, void *vp
)
630 bres_server
*rs
= vp
;
634 /* --- @answer@ --- *
636 * Arguments: @int fd@ = file descriptor which is ready
637 * @unsigned mode@ = what it's doing now
638 * @void *vp@ = pointer to server block
642 * Use: Retrieves an answer from a name resolver process.
645 static void attach(bres_client */
*rc*/
);
647 static void answer(int fd
, unsigned mode
, void *vp
)
649 bres_server
*rs
= vp
;
650 bres_client
*rc
= rs
->rc
;
651 struct hostent
*h
= 0;
655 /* --- Report the result to my client --- */
659 if (doread(fd
, &resp
, sizeof(resp
)) == 0) {
662 doread(fd
, &h_errno
, sizeof(h_errno
));
673 if (rc
->q
== BRES_BYNAME
)
683 /* --- Wrap up the various structures --- */
687 rs
->next
= FREE
->next
;
689 FREE
->next
->prev
= rs
;
692 /* --- Tie a timer onto the server block --- */
697 gettimeofday(&tv
, 0);
698 tv
.tv_sec
+= BRES_IDLE
;
699 sel_addtimer(sel
, &rs
->t
, &tv
, idle
, rs
);
702 /* --- If there are any clients waiting, attach one --- */
704 if (QUEUE
->next
!= QUEUE
) {
706 QUEUE
->next
= rc
->next
;
707 rc
->next
->prev
= QUEUE
;
714 * Arguments: @bres_server *rs@ = pointer to a server block
716 * Returns: Zero if OK, nonzero if something failed.
718 * Use: Starts up a child resolver process.
721 static int start(bres_server
*rs
)
726 /* --- Make the pipes --- */
733 /* --- Start up the child process --- */
735 if ((kid
= fork()) < 0)
742 dup2(cfd
[0], STDIN_FILENO
);
743 dup2(rfd
[1], STDOUT_FILENO
);
746 execlp(server
, server
, (char *)0);
747 child(STDOUT_FILENO
, STDIN_FILENO
);
749 child(rfd
[1], cfd
[0]);
753 /* --- Fix up everything in the server block --- */
758 sel_initfile(sel
, &rs
->f
, rfd
[0], SEL_READ
, answer
, rs
);
762 /* --- Fix up after errors --- */
774 /* --- @attach@ --- *
776 * Arguments: @bres_client *rc@ = pointer to a client block
780 * Use: Attaches a client to a spare server (which is assumed to
784 static void attach(bres_client
*rc
)
789 /* --- Fix up the server ready for the job --- *
791 * If the server has a process, remove its timer. Otherwise, fork off a
792 * new resolver process. This is also where I go if I find that the child
793 * resolver process has lost while I wasn't looking. Only one attempt at
794 * forking is performed.
802 if (lose
|| start(rs
))
807 /* --- Submit the job to the resolver --- */
810 struct sigaction sa
, osa
;
813 /* --- Ignore @SIGPIPE@ for now --- *
815 * This way I can trap @EPIPE@ and reap a losing child, if there was one.
818 sa
.sa_handler
= SIG_IGN
;
820 sigemptyset(&sa
.sa_mask
);
821 sigaction(SIGPIPE
, &sa
, &osa
);
823 /* --- Write the new job to the child --- */
826 if (dowrite(rs
->fd
, &rc
->q
, sizeof(rc
->q
)))
828 else switch (rc
->q
) {
830 if (dowrite(rs
->fd
, &rc
->u
.addr
, sizeof(rc
->u
.addr
)))
834 if (putstring(rs
->fd
, rc
->u
.name
))
838 sigaction(SIGPIPE
, &osa
, 0);
840 /* --- Sort out various errors --- *
842 * This was once more complicated, handling @EPIPE@ separately from other
843 * errors. Now everything's handled the same way.
852 /* --- Fiddle with lists so that everything's OK --- */
855 rs
->next
->prev
= FREE
;
856 FREE
->next
= rs
->next
;
857 rs
->next
= rs
->prev
= rs
;
864 if (rc
->q
== BRES_BYNAME
)
868 /* --- @resolve@ --- *
870 * Arguments: @bres_client *rc@ = pointer to filled-in client block
874 * Use: Dispatcher for incoming resolution jobs.
877 static void resolve(bres_client
*rc
)
879 /* --- If there's a free server, plug it in --- */
882 if (FREE
->next
== FREE
) {
884 rc
->prev
= QUEUE
->prev
;
885 QUEUE
->prev
->next
= rc
;
891 /* --- @bres_byaddr@ --- *
893 * Arguments: @bres_client *rc@ = pointer to client block
894 * @struct in_addr addr@ = address to resolve
895 * @void (*func)(struct hostent *h, void *p)@ = handler function
896 * @void *p@ = argument for handler function
900 * Use: Adds an address lookup job to the queue. The job will be
901 * processed when there's a spare resolver process to deal with
905 void bres_byaddr(bres_client
*rc
, struct in_addr addr
,
906 void (*func
)(struct hostent */
*h*/
, void */
*p*/
),
916 /* --- @bres_byname@ --- *
918 * Arguments: @bres_client *rc@ = pointer to client block
919 * @const char *name@ = name to resolve
920 * @void (*func)(struct hostent *h, void *p)@ = handler function
921 * @void *p@ = argument for handler function
925 * Use: Adds a name lookup job to the queue. The job will be
926 * processed when there's a spare resolver process to deal with
930 void bres_byname(bres_client
*rc
, const char *name
,
931 void (*func
)(struct hostent */
*h*/
, void */
*p*/
),
935 rc
->u
.name
= xstrdup(name
);
941 /* --- @bres_exec@ --- *
943 * Arguments: @const char *file@ = file containing server code or null
947 * Use: Makes `bres' use a standalone server rather than copies of
948 * the current process. This can reduce memory consumption for
949 * large processes, at the expense of startup time (which
950 * shouldn't be too bad anyway, because of the resolver design).
951 * If the filename is null, a default set up at install time is
952 * used. It's probably a good idea to leave it alone.
955 void bres_exec(const char *file
)
960 server
= BRES_SERVER
;
963 /* --- @bres_init@ --- *
965 * Arguments: @sel_state *s@ = pointer to select multiplexor
969 * Use: Initializes the background resolver for use.
972 void bres_init(sel_state
*s
)
977 for (i
= 0; i
< BRES_MAX
; i
++) {
978 servers
[i
].next
= FREE
;
979 servers
[i
].prev
= FREE
->prev
;
982 FREE
->prev
->next
= &servers
[i
];
983 FREE
->prev
= &servers
[i
];
989 /*----- That's all, folks -------------------------------------------------*/