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>
55 /*----- Magic numbers -----------------------------------------------------*/
57 #define BRES_MAX 15 /* Maximum number of resolvers */
58 #define BRES_IDLE 60 /* Lifetime of an idle resolver */
60 /*----- Static variables --------------------------------------------------*/
62 #ifndef BRES_STANDALONE
64 static bres_server servers
[BRES_MAX
]; /* Statically allocated servers */
66 #define FREE ((bres_server *)&freelist)
67 static struct { bres_server
*next
, *prev
; } freelist
= { FREE
, FREE
};
69 #define QUEUE ((bres_client *)&queue)
70 static struct { bres_client
*next
, *prev
; } queue
= { QUEUE
, QUEUE
};
72 static sel_state
*sel
;
74 static const char *server
= 0;
78 /*----- Background resolver protocol --------------------------------------*/
80 /* --- Requests and responses --- *
82 * There are two types of requests: name and addr, corresponding to the
83 * standard @gethostbyname@ and @gethostbyaddr@ calls. There are two types
84 * of responses too: a positive response consists of an encoded equivalent of
85 * a @struct hostent@ structure containing the requested information; a
86 * negative response consists of an @h_errno@ value explaining the problem.
89 #define BRES_BYNAME 0 /* Request: resolve given name */
90 #define BRES_BYADDR 1 /* Request: resolve given address */
92 #define BRES_HOSTENT 0 /* Response: resolved ok */
93 #define BRES_ERROR 1 /* Response: resolution failed */
95 /* --- Encodings --- *
97 * A string is encoded as a @size_t@ length followed by the actual data. The
98 * null terminator is not transmitted.
100 * Addresses for resolution are transmitted as raw @struct in_addr@
103 * A @hostent@ structure is transmitted as a header containing fixed-size
104 * information, followed by the official name, an array of aliases, and an
105 * array of addresses. The number of items in the arrays is specified in the
108 * The implementation assumes that a complete request or reply is always
109 * sent. Undesirable blocking will occur if this is not the case. Both ends
110 * are assumed to trust each other. A protocol failure results in the child
111 * in question being terminated.
114 typedef struct hostskel
{
121 /* --- @doread@, @dowrite@ --- *
123 * Arguments: @int fd@ = file descriptor
124 * @void *buf@ = buffer for data
125 * @size_t sz@ = size of data
127 * Returns: Zero if successful, nonzero otherwise.
129 * Use: Reads or writes a chunk of data. @EINTR@ errors are retried;
130 * incomplete reads and writes are continued from where they
131 * left off. End-of-file is considered an I/O error.
134 static int doread(int fd
, void *buf
, size_t sz
)
138 int r
= read(fd
, p
, sz
);
153 static int dowrite(int fd
, const void *buf
, size_t sz
)
157 int r
= write(fd
, p
, sz
);
172 /* --- @getstring@ --- *
174 * Arguments: @int fd@ = file descriptor to read
176 * Returns: String in heap-allocated block, or a null pointer.
178 * Use: Decodes a string.
181 static char *getstring(int fd
)
186 if (doread(fd
, &sz
, sizeof(sz
)) || (p
= malloc(sz
+ 1)) == 0)
188 if (doread(fd
, p
, sz
)) {
196 /* --- @putstring@ --- *
198 * Arguments: @int fd@ = file descriptor to write on
199 * @const char *p@ = pointer to string to write
201 * Returns: Zero if successful.
203 * Use: Encodes a string.
206 static int putstring(int fd
, const char *p
)
208 size_t sz
= strlen(p
);
209 if (dowrite(fd
, &sz
, sizeof(sz
)) || dowrite(fd
, p
, sz
))
214 /* --- @gethost@ --- *
216 * Arguments: @int fd@ = file descriptor to read
218 * Returns: Pointer to heap-allocated @struct hostent@, or null.
220 * Use: Decodes a host structure. The resulting structure is all in
221 * one big heap block.
224 #ifndef BRES_STANDALONE
226 static struct hostent
*gethost(int fd
)
233 /* --- Read the skeleton structure --- */
235 if (doread(fd
, &hsk
, sizeof(hsk
)))
238 /* --- Read the hostname and alias strings --- *
240 * Count the length of the strings as we go.
245 sizeof(struct hostent
) +
246 hsk
.naddr
* hsk
.addrsz
+
247 (hsk
.naddr
+ hsk
.nalias
+ 2) * sizeof(char *);
249 /* --- Read the primary host name --- */
251 if ((name
= getstring(fd
)) == 0)
253 sz
+= strlen(name
) + 1;
255 /* --- Read in the alias names --- */
259 if ((alias
= malloc(hsk
.nalias
* sizeof(char *))) == 0)
261 for (i
= 0; i
< hsk
.nalias
; i
++)
263 for (i
= 0; i
< hsk
.nalias
; i
++) {
264 if ((alias
[i
] = getstring(fd
)) == 0)
266 sz
+= strlen(alias
[i
]) + 1;
270 /* --- Allocate the output structure --- */
272 if ((h
= malloc(sz
)) == 0)
276 /* --- Fill in the base structure --- */
278 h
->h_addrtype
= hsk
.addrtype
;
279 h
->h_length
= hsk
.addrsz
;
281 /* --- Start putting everything else in --- */
284 char **p
= (char **)(h
+ 1);
285 char *a
= (char *)(p
+ hsk
.nalias
+ hsk
.naddr
+ 2);
288 /* --- Start with the address table --- */
291 if (doread(fd
, a
, hsk
.naddr
* hsk
.addrsz
))
293 for (i
= 0; i
< hsk
.naddr
; i
++) {
299 /* --- Finally copy the strings over --- */
301 #define PUT(_p) do { \
302 size_t _len = strlen(_p) + 1; \
303 memcpy(a, (_p), _len); \
311 for (i
= 0; i
< hsk
.nalias
; i
++) {
324 /* --- Tidy up after various types of failure --- */
329 for (i
= 0; i
< hsk
.nalias
&& alias
[i
]; i
++)
341 /* --- @puthost@ --- *
343 * Arguments: @int fd@ = file descriptor
344 * @struct hostent *h@ = pointer to host structure
346 * Returns: Zero if successful.
348 * Use: Encodes a host structure.
351 static int puthost(int fd
, struct hostent
*h
)
356 /* --- Fill in and send the skeleton structure --- */
358 for (i
= 0; h
->h_aliases
[i
]; i
++)
361 for (i
= 0; h
->h_addr_list
[i
]; i
++)
364 hsk
.addrtype
= h
->h_addrtype
;
365 hsk
.addrsz
= h
->h_length
;
366 if (dowrite(fd
, &hsk
, sizeof(hsk
)))
369 /* --- Send the name and alias strings --- */
371 if (putstring(fd
, h
->h_name
))
373 for (i
= 0; h
->h_aliases
[i
]; i
++) {
374 if (putstring(fd
, h
->h_aliases
[i
]))
378 /* --- Send the address data --- */
380 for (i
= 0; h
->h_addr_list
[i
]; i
++) {
381 if (dowrite(fd
, h
->h_addr_list
[i
], hsk
.addrsz
))
385 /* --- OK, done --- */
390 /*----- Resolver server ---------------------------------------------------*/
394 * Arguments: @int rfd@ = output file descriptor for resolved hostnames
395 * @int cfd@ = input file descriptor for raw addresses
399 * Use: Asynchronous name resolving process.
402 static void child(int rfd
, int cfd
)
404 /* --- Close other file descriptors --- */
408 #if defined(_SC_OPEN_MAX)
409 int maxfd
= sysconf(_SC_OPEN_MAX
);
410 #elif defined(OPEN_MAX)
411 int maxfd
= OPEN_MAX
;
417 maxfd
= 256; /* Fingers crossed... */
418 for (i
= 0; i
< maxfd
; i
++) {
419 if (i
!= rfd
&& i
!= cfd
&& i
!= 1)
424 signal(SIGTERM
, SIG_DFL
);
425 signal(SIGHUP
, SIG_DFL
);
426 signal(SIGQUIT
, SIG_DFL
);
427 signal(SIGALRM
, SIG_DFL
);
428 signal(SIGINT
, SIG_DFL
);
430 /* --- Main request/response loop --- */
436 /* --- Read the request --- */
438 if (doread(cfd
, &req
, sizeof(req
)))
441 /* --- Process it into a host structure --- */
445 /* --- Normal forward lookup --- */
448 char *name
= getstring(cfd
);
451 h
= gethostbyname(name
);
455 /* --- Reverse lookup --- */
460 if (doread(cfd
, &addr
, sizeof(addr
)))
462 if ((h
= gethostbyaddr((char *)&addr
, sizeof(addr
), AF_INET
)) == 0)
465 /* --- Do a forward lookup to confirm --- */
468 size_t sz
= strlen(h
->h_name
) + 1;
469 if ((p
= malloc(sz
)) == 0)
471 memcpy(p
, h
->h_name
, sz
);
474 h
= gethostbyname(p
);
481 for (pp
= h
->h_addr_list
; *pp
; pp
++) {
483 memcpy(&a
, *pp
, sizeof(a
));
484 if (a
.s_addr
== addr
.s_addr
) {
492 h_errno
= NO_RECOVERY
;
497 /* --- Unknown request -- may have lost sync --- */
503 /* --- Transmit the response --- */
507 if (dowrite(rfd
, &resp
, sizeof(resp
)) || puthost(rfd
, h
))
511 if (dowrite(rfd
, &resp
, sizeof(resp
)) ||
512 dowrite(rfd
, &h_errno
, sizeof(h_errno
)))
523 * Arguments: @int argc@ = number of command line arguments
524 * @char *argv[]@ = array of arguments
526 * Returns: Runs until killed or an error occurs.
528 * Use: A name resolver server process for mLib programs which need
529 * this sort of thing.
532 #ifdef BRES_STANDALONE
534 int main(int argc
, char *argv
[])
536 if (isatty(STDIN_FILENO
)) {
537 char *p
= strrchr(argv
[0], '/');
543 "%s: don't run this program unless you know what you're doing.\n",
547 child(STDOUT_FILENO
, STDIN_FILENO
);
553 /*----- Main code ---------------------------------------------------------*/
555 #ifndef BRES_STANDALONE
559 * Arguments: @bres_server *rs@ = pointer to server block
563 * Use: Kills a server process, reaps the losing child and makes
564 * things generally clean again.
567 static void zap(bres_server
*rs
)
569 /* --- Close the pipes, kill the child, and reap it --- */
574 kill(rs
->kid
, SIGTERM
);
575 waitpid(rs
->kid
, 0, 0);
579 /* --- Move the server to the back of the list --- */
581 rs
->next
->prev
= rs
->prev
;
582 rs
->prev
->next
= rs
->next
;
584 rs
->prev
= FREE
->prev
;
585 FREE
->prev
->next
= rs
;
589 /* --- @bres_abort@ --- *
591 * Arguments: @bres_client *rc@ = pointer to client block
595 * Use: Removes a queued job.
598 void bres_abort(bres_client
*rc
)
600 if (rc
->q
== BRES_BYNAME
)
603 sel_rmfile(&rc
->rs
->f
);
607 rc
->next
->prev
= rc
->prev
;
608 rc
->prev
->next
= rc
->next
;
614 * Arguments: @struct timeval *tv@ = pointer to the current time
615 * @void *vp@ = pointer to a server block
619 * Use: Kills off a child which has been idle for too long.
622 static void idle(struct timeval
*tv
, void *vp
)
624 bres_server
*rs
= vp
;
628 /* --- @answer@ --- *
630 * Arguments: @int fd@ = file descriptor which is ready
631 * @unsigned mode@ = what it's doing now
632 * @void *vp@ = pointer to server block
636 * Use: Retrieves an answer from a name resolver process.
639 static void attach(bres_client */
*rc*/
);
641 static void answer(int fd
, unsigned mode
, void *vp
)
643 bres_server
*rs
= vp
;
644 bres_client
*rc
= rs
->rc
;
645 struct hostent
*h
= 0;
649 /* --- Report the result to my client --- */
653 if (doread(fd
, &resp
, sizeof(resp
)) == 0) {
656 doread(fd
, &h_errno
, sizeof(h_errno
));
667 if (rc
->q
== BRES_BYNAME
)
677 /* --- Wrap up the various structures --- */
681 rs
->next
= FREE
->next
;
683 FREE
->next
->prev
= rs
;
686 /* --- Tie a timer onto the server block --- */
691 gettimeofday(&tv
, 0);
692 tv
.tv_sec
+= BRES_IDLE
;
693 sel_addtimer(sel
, &rs
->t
, &tv
, idle
, rs
);
696 /* --- If there are any clients waiting, attach one --- */
698 if (QUEUE
->next
!= QUEUE
) {
700 QUEUE
->next
= rc
->next
;
701 rc
->next
->prev
= QUEUE
;
708 * Arguments: @bres_server *rs@ = pointer to a server block
710 * Returns: Zero if OK, nonzero if something failed.
712 * Use: Starts up a child resolver process.
715 static int start(bres_server
*rs
)
720 /* --- Make the pipes --- */
727 /* --- Start up the child process --- */
729 if ((kid
= fork()) < 0)
736 dup2(cfd
[0], STDIN_FILENO
);
737 dup2(rfd
[1], STDOUT_FILENO
);
740 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 -------------------------------------------------*/