4efea3c1902d0cf3d12837d5863b4c57c150a74f
3 * $Id: bres.c,v 1.7 2004/04/08 01:36:11 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 /*----- Header files ------------------------------------------------------*/
40 #include <sys/types.h>
45 #include <sys/socket.h>
46 #include <netinet/in.h>
47 #include <arpa/inet.h>
56 /*----- Magic numbers -----------------------------------------------------*/
58 #define BRES_MAX 15 /* Maximum number of resolvers */
59 #define BRES_IDLE 60 /* Lifetime of an idle resolver */
61 /*----- Static variables --------------------------------------------------*/
63 #ifndef BRES_STANDALONE
65 static bres_server servers
[BRES_MAX
]; /* Statically allocated servers */
67 #define FREE ((bres_server *)&freelist)
68 static struct { bres_server
*next
, *prev
; } freelist
= { FREE
, FREE
};
70 #define QUEUE ((bres_client *)&queue)
71 static struct { bres_client
*next
, *prev
; } queue
= { QUEUE
, QUEUE
};
73 static sel_state
*sel
;
75 static const char *server
= 0;
79 /*----- Background resolver protocol --------------------------------------*/
81 /* --- Requests and responses --- *
83 * There are two types of requests: name and addr, corresponding to the
84 * standard @gethostbyname@ and @gethostbyaddr@ calls. There are two types
85 * of responses too: a positive response consists of an encoded equivalent of
86 * a @struct hostent@ structure containing the requested information; a
87 * negative response consists of an @h_errno@ value explaining the problem.
90 #define BRES_BYNAME 0 /* Request: resolve given name */
91 #define BRES_BYADDR 1 /* Request: resolve given address */
93 #define BRES_HOSTENT 0 /* Response: resolved ok */
94 #define BRES_ERROR 1 /* Response: resolution failed */
96 /* --- Encodings --- *
98 * A string is encoded as a @size_t@ length followed by the actual data. The
99 * null terminator is not transmitted.
101 * Addresses for resolution are transmitted as raw @struct in_addr@
104 * A @hostent@ structure is transmitted as a header containing fixed-size
105 * information, followed by the official name, an array of aliases, and an
106 * array of addresses. The number of items in the arrays is specified in the
109 * The implementation assumes that a complete request or reply is always
110 * sent. Undesirable blocking will occur if this is not the case. Both ends
111 * are assumed to trust each other. A protocol failure results in the child
112 * in question being terminated.
115 typedef struct hostskel
{
122 /* --- @doread@, @dowrite@ --- *
124 * Arguments: @int fd@ = file descriptor
125 * @void *buf@ = buffer for data
126 * @size_t sz@ = size of data
128 * Returns: Zero if successful, nonzero otherwise.
130 * Use: Reads or writes a chunk of data. @EINTR@ errors are retried;
131 * incomplete reads and writes are continued from where they
132 * left off. End-of-file is considered an I/O error.
135 static int doread(int fd
, void *buf
, size_t sz
)
139 int r
= read(fd
, p
, sz
);
154 static int dowrite(int fd
, const void *buf
, size_t sz
)
158 int r
= write(fd
, p
, sz
);
173 /* --- @getstring@ --- *
175 * Arguments: @int fd@ = file descriptor to read
177 * Returns: String in heap-allocated block, or a null pointer.
179 * Use: Decodes a string.
182 static char *getstring(int fd
)
187 if (doread(fd
, &sz
, sizeof(sz
)) || (p
= malloc(sz
+ 1)) == 0)
189 if (doread(fd
, p
, sz
)) {
197 /* --- @putstring@ --- *
199 * Arguments: @int fd@ = file descriptor to write on
200 * @const char *p@ = pointer to string to write
202 * Returns: Zero if successful.
204 * Use: Encodes a string.
207 static int putstring(int fd
, const char *p
)
209 size_t sz
= strlen(p
);
210 if (dowrite(fd
, &sz
, sizeof(sz
)) || dowrite(fd
, p
, sz
))
215 /* --- @gethost@ --- *
217 * Arguments: @int fd@ = file descriptor to read
219 * Returns: Pointer to heap-allocated @struct hostent@, or null.
221 * Use: Decodes a host structure. The resulting structure is all in
222 * one big heap block.
225 #ifndef BRES_STANDALONE
227 static struct hostent
*gethost(int fd
)
234 /* --- Read the skeleton structure --- */
236 if (doread(fd
, &hsk
, sizeof(hsk
)))
239 /* --- Read the hostname and alias strings --- *
241 * Count the length of the strings as we go.
246 sizeof(struct hostent
) +
247 hsk
.naddr
* hsk
.addrsz
+
248 (hsk
.naddr
+ hsk
.nalias
+ 2) * sizeof(char *);
250 /* --- Read the primary host name --- */
252 if ((name
= getstring(fd
)) == 0)
254 sz
+= strlen(name
) + 1;
256 /* --- Read in the alias names --- */
260 if ((alias
= malloc(hsk
.nalias
* sizeof(char *))) == 0)
262 for (i
= 0; i
< hsk
.nalias
; i
++)
264 for (i
= 0; i
< hsk
.nalias
; i
++) {
265 if ((alias
[i
] = getstring(fd
)) == 0)
267 sz
+= strlen(alias
[i
]) + 1;
271 /* --- Allocate the output structure --- */
273 if ((h
= malloc(sz
)) == 0)
277 /* --- Fill in the base structure --- */
279 h
->h_addrtype
= hsk
.addrtype
;
280 h
->h_length
= hsk
.addrsz
;
282 /* --- Start putting everything else in --- */
285 char **p
= (char **)(h
+ 1);
286 char *a
= (char *)(p
+ hsk
.nalias
+ hsk
.naddr
+ 2);
289 /* --- Start with the address table --- */
292 if (doread(fd
, a
, hsk
.naddr
* hsk
.addrsz
))
294 for (i
= 0; i
< hsk
.naddr
; i
++) {
300 /* --- Finally copy the strings over --- */
302 #define PUT(_p) do { \
303 size_t _len = strlen(_p) + 1; \
304 memcpy(a, (_p), _len); \
312 for (i
= 0; i
< hsk
.nalias
; i
++) {
325 /* --- Tidy up after various types of failure --- */
330 for (i
= 0; i
< hsk
.nalias
&& alias
[i
]; i
++)
342 /* --- @puthost@ --- *
344 * Arguments: @int fd@ = file descriptor
345 * @struct hostent *h@ = pointer to host structure
347 * Returns: Zero if successful.
349 * Use: Encodes a host structure.
352 static int puthost(int fd
, struct hostent
*h
)
357 /* --- Fill in and send the skeleton structure --- */
359 for (i
= 0; h
->h_aliases
[i
]; i
++)
362 for (i
= 0; h
->h_addr_list
[i
]; i
++)
365 hsk
.addrtype
= h
->h_addrtype
;
366 hsk
.addrsz
= h
->h_length
;
367 if (dowrite(fd
, &hsk
, sizeof(hsk
)))
370 /* --- Send the name and alias strings --- */
372 if (putstring(fd
, h
->h_name
))
374 for (i
= 0; h
->h_aliases
[i
]; i
++) {
375 if (putstring(fd
, h
->h_aliases
[i
]))
379 /* --- Send the address data --- */
381 for (i
= 0; h
->h_addr_list
[i
]; i
++) {
382 if (dowrite(fd
, h
->h_addr_list
[i
], hsk
.addrsz
))
386 /* --- OK, done --- */
391 /*----- Resolver server ---------------------------------------------------*/
395 * Arguments: @int rfd@ = output file descriptor for resolved hostnames
396 * @int cfd@ = input file descriptor for raw addresses
400 * Use: Asynchronous name resolving process.
403 static void child(int rfd
, int cfd
)
405 /* --- Close other file descriptors --- */
409 #if defined(_SC_OPEN_MAX)
410 int maxfd
= sysconf(_SC_OPEN_MAX
);
411 #elif defined(OPEN_MAX)
412 int maxfd
= OPEN_MAX
;
418 maxfd
= 256; /* Fingers crossed... */
419 for (i
= 0; i
< maxfd
; i
++) {
420 if (i
!= rfd
&& i
!= cfd
&& i
!= 1)
425 signal(SIGTERM
, SIG_DFL
);
426 signal(SIGHUP
, SIG_DFL
);
427 signal(SIGQUIT
, SIG_DFL
);
428 signal(SIGALRM
, SIG_DFL
);
429 signal(SIGINT
, SIG_DFL
);
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 /* --- Reverse 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
)
722 /* --- Make the pipes --- */
729 /* --- Start up the child process --- */
731 if ((kid
= fork()) < 0)
738 md
[0].cur
= cfd
[0]; md
[0].want
= STDIN_FILENO
;
739 md
[1].cur
= rfd
[1]; md
[1].want
= STDOUT_FILENO
;
740 if (mdup(md
, 2) || execlp(server
, server
, (char *)0))
741 child(STDOUT_FILENO
, STDIN_FILENO
);
743 child(rfd
[1], cfd
[0]);
747 /* --- Fix up everything in the server block --- */
752 sel_initfile(sel
, &rs
->f
, rfd
[0], SEL_READ
, answer
, rs
);
756 /* --- Fix up after errors --- */
768 /* --- @attach@ --- *
770 * Arguments: @bres_client *rc@ = pointer to a client block
774 * Use: Attaches a client to a spare server (which is assumed to
778 static void attach(bres_client
*rc
)
783 /* --- Fix up the server ready for the job --- *
785 * If the server has a process, remove its timer. Otherwise, fork off a
786 * new resolver process. This is also where I go if I find that the child
787 * resolver process has lost while I wasn't looking. Only one attempt at
788 * forking is performed.
796 if (lose
|| start(rs
))
801 /* --- Submit the job to the resolver --- */
804 struct sigaction sa
, osa
;
807 /* --- Ignore @SIGPIPE@ for now --- *
809 * This way I can trap @EPIPE@ and reap a losing child, if there was one.
812 sa
.sa_handler
= SIG_IGN
;
814 sigemptyset(&sa
.sa_mask
);
815 sigaction(SIGPIPE
, &sa
, &osa
);
817 /* --- Write the new job to the child --- */
820 if (dowrite(rs
->fd
, &rc
->q
, sizeof(rc
->q
)))
822 else switch (rc
->q
) {
824 if (dowrite(rs
->fd
, &rc
->u
.addr
, sizeof(rc
->u
.addr
)))
828 if (putstring(rs
->fd
, rc
->u
.name
))
832 sigaction(SIGPIPE
, &osa
, 0);
834 /* --- Sort out various errors --- *
836 * This was once more complicated, handling @EPIPE@ separately from other
837 * errors. Now everything's handled the same way.
846 /* --- Fiddle with lists so that everything's OK --- */
849 rs
->next
->prev
= FREE
;
850 FREE
->next
= rs
->next
;
851 rs
->next
= rs
->prev
= rs
;
858 if (rc
->q
== BRES_BYNAME
)
862 /* --- @resolve@ --- *
864 * Arguments: @bres_client *rc@ = pointer to filled-in client block
868 * Use: Dispatcher for incoming resolution jobs.
871 static void resolve(bres_client
*rc
)
873 /* --- If there's a free server, plug it in --- */
876 if (FREE
->next
== FREE
) {
878 rc
->prev
= QUEUE
->prev
;
879 QUEUE
->prev
->next
= rc
;
885 /* --- @bres_byaddr@ --- *
887 * Arguments: @bres_client *rc@ = pointer to client block
888 * @struct in_addr addr@ = address to resolve
889 * @void (*func)(struct hostent *h, void *p)@ = handler function
890 * @void *p@ = argument for handler function
894 * Use: Adds an address lookup job to the queue. The job will be
895 * processed when there's a spare resolver process to deal with
899 void bres_byaddr(bres_client
*rc
, struct in_addr addr
,
900 void (*func
)(struct hostent */
*h*/
, void */
*p*/
),
910 /* --- @bres_byname@ --- *
912 * Arguments: @bres_client *rc@ = pointer to client block
913 * @const char *name@ = name to resolve
914 * @void (*func)(struct hostent *h, void *p)@ = handler function
915 * @void *p@ = argument for handler function
919 * Use: Adds a name lookup job to the queue. The job will be
920 * processed when there's a spare resolver process to deal with
924 void bres_byname(bres_client
*rc
, const char *name
,
925 void (*func
)(struct hostent */
*h*/
, void */
*p*/
),
929 rc
->u
.name
= xstrdup(name
);
935 /* --- @bres_exec@ --- *
937 * Arguments: @const char *file@ = file containing server code or null
941 * Use: Makes `bres' use a standalone server rather than copies of
942 * the current process. This can reduce memory consumption for
943 * large processes, at the expense of startup time (which
944 * shouldn't be too bad anyway, because of the resolver design).
945 * If the filename is null, a default set up at install time is
946 * used. It's probably a good idea to leave it alone.
949 void bres_exec(const char *file
)
954 server
= BRES_SERVER
;
957 /* --- @bres_init@ --- *
959 * Arguments: @sel_state *s@ = pointer to select multiplexor
963 * Use: Initializes the background resolver for use.
966 void bres_init(sel_state
*s
)
971 for (i
= 0; i
< BRES_MAX
; i
++) {
972 servers
[i
].next
= FREE
;
973 servers
[i
].prev
= FREE
->prev
;
976 FREE
->prev
->next
= &servers
[i
];
977 FREE
->prev
= &servers
[i
];
983 /*----- That's all, folks -------------------------------------------------*/