5 * (c) 2012 Straylight/Edgeware
8 /*----- Licensing notice --------------------------------------------------*
10 * This file is part of Yet Another Ident Daemon (YAID).
12 * YAID is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
17 * YAID is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with YAID; if not, write to the Free Software Foundation,
24 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
27 /*----- Header files ------------------------------------------------------*/
31 /*----- Data structures ---------------------------------------------------*/
33 /* A write buffer is the gadget which keeps track of our output and writes
34 * portions of it out as and when connections are ready for it.
38 size_t o; /* Offset of remaining data */
39 size_t n; /* Length of remaining data */
40 sel_file wr; /* Write selector */
41 void (*func)(int /*err*/, void *); /* Function to call on completion */
42 void *p; /* Context for `func' */
43 unsigned char buf[WRBUFSZ]; /* Output buffer */
46 /* Structure for a listening socket. There's one of these for each address
47 * family we're looking after.
50 const struct addrops *ao; /* Address family operations */
51 sel_file f; /* Watch for incoming connections */
54 /* The main structure for a client. */
56 int fd; /* The connection to the client */
57 selbuf b; /* Accumulate lines of input */
58 union addr raddr; /* Remote address */
59 struct query q; /* The clients query and our reply */
60 struct sel_timer t; /* Timeout for idle or doomed conn */
61 struct listen *l; /* Back to the listener (and ops) */
62 struct writebuf wb; /* Write buffer for our reply */
63 struct proxy *px; /* Proxy if conn goes via NAT */
66 /* A proxy connection. */
68 int fd; /* Connection; -1 if in progress */
69 struct client *c; /* Back to the client */
70 conn cn; /* Nonblocking connection */
71 selbuf b; /* Accumulate the response line */
72 struct writebuf wb; /* Write buffer for query */
73 char nat[ADDRLEN]; /* Server address, as text */
76 /*----- Static variables --------------------------------------------------*/
78 static sel_state sel; /* I/O multiplexer state */
80 static const char *pidfile = 0; /* Where to write daemon's pid */
82 static const char *policyfile = POLICYFILE; /* Filename for global policy */
83 static const struct policy default_policy = POLICY_INIT(A_NAME);
84 static policy_v policy = DA_INIT; /* Vector of global policy rules */
85 static fwatch polfw; /* Watch policy file for changes */
87 static unsigned char tokenbuf[4096]; /* Random-ish data for tokens */
88 static size_t tokenptr = sizeof(tokenbuf); /* Current read position */
89 static int randfd; /* File descriptor for random data */
91 static unsigned flags = 0; /* Various interesting flags */
92 #define F_SYSLOG 1u /* Use syslog for logging */
93 #define F_RUNNING 2u /* Running properly now */
95 /*----- Ident protocol parsing --------------------------------------------*/
97 /* Advance *PP over whitespace characters. */
98 static void skipws(const char **pp)
99 { while (isspace((unsigned char )**pp)) (*pp)++; }
101 /* Copy a token of no more than N bytes starting at *PP into Q, advancing *PP
104 static int idtoken(const char **pp, char *q, size_t n)
111 if (*p == ':' || *p <= 32 || *p >= 127) break;
121 /* Read an unsigned decimal number from *PP, and store it in *II. Check that
122 * it's between MIN and MAX, and advance *PP over it. Return zero for
123 * success, or nonzero if something goes wrong.
125 static int unum(const char **pp, unsigned *ii, unsigned min, unsigned max)
132 if (!isdigit((unsigned char)**pp)) return (-1);
133 e = errno; errno = 0;
134 i = strtoul(*pp, &q, 10);
135 if (errno) return (-1);
138 if (i < min || i > max) return (-1);
143 /*----- Asynchronous writing ----------------------------------------------*/
145 /* Callback for actually writing stuff from a `writebuf'. */
146 static void write_out(int fd, unsigned mode, void *p)
149 struct writebuf *wb = p;
151 /* Try to write something. */
152 if ((n = write(fd, wb->buf + wb->o, wb->n)) < 0) {
153 if (errno == EAGAIN || errno == EWOULDBLOCK) return;
156 wb->func(errno, wb->p);
161 /* If there's nothing left then restore the buffer to its empty state. */
169 /* Queue N bytes starting at P to be written. */
170 static int queue_write(struct writebuf *wb, const void *p, size_t n)
172 /* Maybe there's nothing to actually do. */
175 /* Make sure it'll fit. */
176 if (wb->n - wb->o + n > WRBUFSZ) return (-1);
178 /* If there's anything there already, then make sure it's at the start of
179 * the available space.
182 memmove(wb->buf, wb->buf + wb->o, wb->n);
186 /* If there's nothing currently there, then we're not requesting write
187 * notifications, so set that up, and force an initial wake-up.
190 sel_addfile(&wb->wr);
194 /* Copy the new material over. */
195 memcpy(wb->buf + wb->n, p, n);
202 /* Release resources allocated to WB. */
203 static void free_writebuf(struct writebuf *wb)
204 { if (wb->n) sel_rmfile(&wb->wr); }
206 /* Initialize a writebuf in *WB, writing to file descriptor FD. On
207 * completion, call FUNC, passing it P and an error indicator: either 0 for
208 * success or an `errno' value on failure.
210 static void init_writebuf(struct writebuf *wb,
211 int fd, void (*func)(int, void *), void *p)
213 sel_initfile(&sel, &wb->wr, fd, SEL_WRITE, write_out, wb);
219 /*----- General utilities -------------------------------------------------*/
221 /* Format and log MSG somewhere sensible, at the syslog(3) priority PRIO.
222 * Prefix it with a description of the query Q, if non-null.
224 void logmsg(const struct query *q, int prio, const char *msg, ...)
234 dputsock(&d, q->ao, &q->s[L]);
235 dstr_puts(&d, " <-> ");
236 dputsock(&d, q->ao, &q->s[R]);
239 dstr_vputf(&d, msg, &ap);
242 if (!(flags & F_RUNNING))
244 else if (flags & F_SYSLOG)
245 syslog(prio, "%s", d.buf);
249 strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S %z", tm);
250 fprintf(stderr, "%s %s: %s\n", buf, QUIS, d.buf);
256 /* Fix up a socket FD so that it won't bite us. Returns zero on success, or
259 static int fix_up_socket(int fd, const char *what)
263 if (fdflags(fd, O_NONBLOCK, O_NONBLOCK, 0, 0)) {
264 logmsg(0, LOG_ERR, "failed to set %s connection nonblocking: %s",
265 what, strerror(errno));
269 if (setsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &yes, sizeof(yes))) {
271 "failed to disable `out-of-band' data on %s connection: %s",
272 what, strerror(errno));
279 /*----- Client output functions -------------------------------------------*/
281 static void disconnect_client(struct client *c);
283 /* Notification that output has been written. If successful, re-enable the
284 * input buffer and prepare for another query.
286 static void done_client_write(int err, void *p)
288 struct client *c = p;
291 selbuf_enable(&c->b);
293 logmsg(&c->q, LOG_ERR, "failed to send reply: %s", strerror(err));
294 disconnect_client(c);
298 /* Format the message FMT and queue it to be sent to the client. Client
299 * input will be disabled until the write completes.
301 static void write_to_client(struct client *c, const char *fmt, ...)
308 n = vsnprintf(buf, sizeof(buf), fmt, ap);
310 logmsg(&c->q, LOG_ERR, "failed to format output: %s", strerror(errno));
311 disconnect_client(c);
313 } else if (n > sizeof(buf)) {
314 logmsg(&c->q, LOG_ERR, "output too long for client send buffer");
315 disconnect_client(c);
319 selbuf_disable(&c->b);
320 if (queue_write(&c->wb, buf, n)) {
321 logmsg(&c->q, LOG_ERR, "write buffer overflow");
322 disconnect_client(c);
326 /* Format a reply to the client, with the form LPORT:RPORT:TY:TOK0[:TOK1].
327 * Typically, TY will be `ERROR' or `USERID'. In the former case, TOK0 will
328 * be the error token and TOK1 will be null; in the latter case, TOK0 will be
329 * the operating system and TOK1 the user name.
331 static void reply(struct client *c, const char *ty,
332 const char *tok0, const char *tok1)
334 write_to_client(c, "%u,%u:%s:%s%s%s\r\n",
335 c->q.s[L].port, c->q.s[R].port, ty,
336 tok0, tok1 ? ":" : "", tok1 ? tok1 : "");
339 /* Mapping from error codes to their protocol tokens. */
340 const char *const errtok[] = {
341 #define DEFTOK(err, tok) tok,
346 /* Report an error with code ERR to the client. */
347 static void reply_error(struct client *c, unsigned err)
349 assert(err < E_LIMIT);
350 reply(c, "ERROR", errtok[err], 0);
353 /*----- NAT proxy functions -----------------------------------------------*/
355 /* Cancel the proxy operation PX, closing the connection and releasing
356 * resources. This is used for both normal and unexpected closures.
358 static void cancel_proxy(struct proxy *px)
364 selbuf_destroy(&px->b);
365 free_writebuf(&px->wb);
367 selbuf_enable(&px->c->b);
372 /* Notification that a line (presumably a reply) has been received from the
373 * server. We should check it, log it, and propagate the answer back.
374 * Whatever happens, this proxy operation is now complete.
376 static void proxy_line(char *line, size_t sz, void *p)
378 struct proxy *px = p;
380 const char *q = line;
383 /* Trim trailing space. */
384 while (sz && isspace((unsigned char)line[sz - 1])) sz--;
386 /* Parse the port numbers. These should match the request. */
387 if (unum(&q, &lp, 1, 65535)) goto syntax;
388 skipws(&q); if (*q != ',') goto syntax; q++;
389 if (unum(&q, &rp, 1, 65535)) goto syntax;
390 skipws(&q); if (*q != ':') goto syntax; q++;
391 if (lp != px->c->q.u.nat.port || rp != px->c->q.s[R].port) goto syntax;
393 /* Find out what kind of reply this is. */
394 if (idtoken(&q, buf, sizeof(buf))) goto syntax;
395 skipws(&q); if (*q != ':') goto syntax; q++;
397 if (strcmp(buf, "ERROR") == 0) {
399 /* Report the error without interpreting it. It might be meaningful to
403 logmsg(&px->c->q, LOG_ERR, "proxy error from %s: %s", px->nat, q);
404 reply(px->c, "ERROR", q, 0);
406 } else if (strcmp(buf, "USERID") == 0) {
408 /* Parse out the operating system and user name, and pass them on. */
409 if (idtoken(&q, buf, sizeof(buf))) goto syntax;
410 skipws(&q); if (*q != ':') goto syntax; q++;
412 logmsg(&px->c->q, LOG_ERR, "user `%s'; proxy = %s, os = %s",
414 reply(px->c, "USERID", buf, q);
421 /* We didn't understand the message from the client. */
422 logmsg(&px->c->q, LOG_ERR, "failed to parse response from %s", px->nat);
423 reply_error(px->c, E_UNKNOWN);
425 /* All finished, no matter what. */
429 /* Notification that we have written the query to the server. Await a
430 * response if successful.
432 static void done_proxy_write(int err, void *p)
434 struct proxy *px = p;
437 logmsg(&px->c->q, LOG_ERR, "failed to proxy query to %s: %s",
438 px->nat, strerror(errno));
439 reply_error(px->c, E_UNKNOWN);
443 selbuf_enable(&px->b);
446 /* Notification that the connection to the server is either established or
447 * failed. In the former case, queue the right query.
449 static void proxy_connected(int fd, void *p)
451 struct proxy *px = p;
455 /* If the connection failed then report the problem and give up. */
457 logmsg(&px->c->q, LOG_ERR,
458 "failed to make %s proxy connection to %s: %s",
459 px->c->l->ao->name, px->nat, strerror(errno));
460 reply_error(px->c, E_UNKNOWN);
465 /* We're now ready to go, so set things up. */
467 selbuf_init(&px->b, &sel, fd, proxy_line, px);
468 selbuf_setsize(&px->b, 1024);
469 selbuf_disable(&px->b);
470 init_writebuf(&px->wb, fd, done_proxy_write, px);
472 /* Write the query. This buffer is large enough because we've already
473 * range-checked the remote the port number and the local one came from the
474 * kernel, which we trust not to do anything stupid.
476 n = sprintf(buf, "%u,%u\r\n", px->c->q.u.nat.port, px->c->q.s[R].port);
477 queue_write(&px->wb, buf, n);
480 /* Proxy the query through to a client machine for which we're providing NAT
483 static void proxy_query(struct client *c)
486 struct sockaddr_storage ss;
491 /* Allocate the context structure for the NAT. */
492 px = xmalloc(sizeof(*px));
494 /* We'll use the client host's address in lots of log messages, so we may
495 * as well format it once and use it over and over.
497 inet_ntop(c->q.ao->af, &c->q.u.nat.addr, px->nat, sizeof(px->nat));
499 /* Create the socket for the connection. */
500 if ((fd = socket(c->q.ao->af, SOCK_STREAM, 0)) < 0) {
501 logmsg(&c->q, LOG_ERR, "failed to make %s socket for proxy: %s",
502 c->l->ao->name, strerror(errno));
505 if (fix_up_socket(fd, "proxy")) goto err_1;
507 /* Set up the connection to the client host. The connection interface is a
508 * bit broken: if the connection completes immediately, then the callback
509 * function is called synchronously, and that might decide to shut
510 * everything down. So we must have fully initialized our context before
511 * calling `conn_init', and mustn't touch it again afterwards -- since the
512 * block may have been freed.
516 c->l->ao->socket_to_sockaddr(&s, &ss, &ssz);
517 selbuf_disable(&c->b);
518 c->px = px; px->c = c;
520 if (conn_init(&px->cn, &sel, fd, (struct sockaddr *)&ss, ssz,
521 proxy_connected, px)) {
522 logmsg(&c->q, LOG_ERR, "failed to make %s proxy connection to %s: %s",
523 c->l->ao->name, px->nat, strerror(errno));
527 /* All ready to go. */
530 /* Tidy up after various kinds of failures. */
532 selbuf_enable(&c->b);
537 reply_error(c, E_UNKNOWN);
540 /*----- Client connection functions ---------------------------------------*/
542 /* Disconnect a client, freeing up any associated resources. */
543 static void disconnect_client(struct client *c)
546 selbuf_destroy(&c->b);
548 free_writebuf(&c->wb);
549 if (c->px) cancel_proxy(c->px);
553 /* Time out a client because it's been idle for too long. */
554 static void timeout_client(struct timeval *tv, void *p)
556 struct client *c = p;
557 logmsg(&c->q, LOG_NOTICE, "timing out idle or stuck client");
558 sel_addtimer(&sel, &c->t, tv, timeout_client, 0);
559 disconnect_client(c);
562 /* Reset the client idle timer, as a result of activity. Set EXISTP if
563 * there is an existing timer which needs to be removed.
565 static void reset_client_timer(struct client *c, int existp)
569 gettimeofday(&tv, 0);
571 if (existp) sel_rmtimer(&c->t);
572 sel_addtimer(&sel, &c->t, &tv, timeout_client, c);
575 /* Write a pseudorandom token into the buffer at P, which must have space for
576 * at least TOKENSZ bytes.
578 #define TOKENRANDSZ 8
579 #define TOKENSZ ((4*TOKENRANDSZ + 5)/3)
580 static void user_token(char *p)
585 static const char tokmap[64] =
586 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.-";
588 /* If there's not enough pseudorandom stuff lying around, then read more
591 if (tokenptr + TOKENRANDSZ >= sizeof(tokenbuf)) {
592 if (read(randfd, tokenbuf, sizeof(tokenbuf)) < sizeof(tokenbuf))
593 die(1, "unexpected short read or error from `/dev/urandom'");
597 /* Now encode the bytes using a slightly tweaked base-64 encoding. Read
598 * bytes into the accumulator and write out characters while there's
601 for (i = 0; i < TOKENRANDSZ; i++) {
602 a = (a << 8) | tokenbuf[tokenptr++]; b += 8;
605 *p++ = tokmap[(a >> b) & 0x3f];
609 /* If there's anything left in the accumulator then flush it out. */
611 *p++ = tokmap[(a << (6 - b)) & 0x3f];
613 /* Null-terminate the token. */
617 /* Notification that a line has been received from the client. Parse it,
618 * find out about the connection it's referring to, apply the relevant
619 * policy rules, and produce a response. This is where almost everything
620 * interesting happens.
622 static void client_line(char *line, size_t len, void *p)
624 struct client *c = p;
626 struct passwd *pw = 0;
627 const struct policy *pol;
629 struct policy upol = POLICY_INIT(A_LIMIT);
630 struct policy_file pf;
634 /* If the connection has closed, then tidy stuff away. */
635 c->q.s[L].port = c->q.s[R].port = 0;
637 disconnect_client(c);
641 /* Client activity, so update the timer. */
642 reset_client_timer(c, 1);
644 /* See if the policy file has changed since we last looked. If so, try to
645 * read the new version.
647 if (fwatch_update(&polfw, policyfile)) {
648 logmsg(0, LOG_INFO, "reload master policy file `%s'", policyfile);
649 load_policy_file(policyfile, &policy);
652 /* Read the local and remote port numbers into the query structure. */
654 if (unum(&q, &c->q.s[L].port, 1, 65535)) goto bad;
655 skipws(&q); if (*q != ',') goto bad; q++;
656 if (unum(&q, &c->q.s[R].port, 1, 65535)) goto bad;
657 skipws(&q); if (*q) goto bad;
659 /* Identify the connection. Act on the result. */
660 c->q.s[R].addr = c->raddr;
665 /* We found a user. Track down the user's password entry, because
666 * we'll want that later. Most of the processing for this case is
669 if ((pw = getpwuid(c->q.u.uid)) == 0) {
670 logmsg(&c->q, LOG_ERR, "no passwd entry for user %d", c->q.u.uid);
671 reply_error(c, E_NOUSER);
677 /* We've acted as a NAT for this connection. Proxy the query through
678 * to the actal client host.
684 /* We failed to identify the connection for some reason. We should
685 * already have logged an error, so there's not much to do here.
687 reply_error(c, c->q.u.error);
691 /* Something happened that we don't understand. */
695 /* Search the table of policy rules to find a match. */
696 for (i = 0; i < DA_LEN(&policy); i++) {
697 pol = &DA(&policy)[i];
698 if (!match_policy(pol, &c->q)) continue;
700 /* If this is something simple, then apply the resulting policy rule. */
701 if (pol->act.act != A_USER) goto match;
703 /* The global policy has decided to let the user have a say, so we must
704 * parse the user file.
707 dstr_putf(&d, "%s/.yaid.policy", pw->pw_dir);
708 if (open_policy_file(&pf, d.buf, "user policy file", &c->q))
710 while (!read_policy_file(&pf)) {
712 /* Give up after 100 lines. If the user's policy is that complicated,
713 * something's gone very wrong. Or there's too much commentary or
717 logmsg(&c->q, LOG_ERR, "%s:%d: user policy file too long",
722 /* If this isn't a match, go around for the next rule. */
723 if (!match_policy(&pf.p, &c->q)) continue;
725 /* Check that the user is allowed to request this action. If not, see
726 * if there's a more acceptable action later on.
728 if (!(pol->act.u.user & (1 << pf.p.act.act))) {
729 logmsg(&c->q, LOG_ERR,
730 "%s:%d: user action forbidden by global policy",
735 /* We've found a match, so grab it, close the file, and say we're
738 upol = pf.p; pol = &upol;
740 close_policy_file(&pf);
744 close_policy_file(&pf);
748 /* No match: apply the built-in default policy. */
749 pol = &default_policy;
752 switch (pol->act.act) {
755 /* Report the actual user's name. */
756 logmsg(&c->q, LOG_INFO, "user `%s' (%d)", pw->pw_name, c->q.u.uid);
757 reply(c, "USERID", "UNIX", pw->pw_name);
761 /* Report an arbitrary token which we can look up in our log file. */
763 logmsg(&c->q, LOG_INFO, "user `%s' (%d); token = %s",
764 pw->pw_name, c->q.u.uid, buf);
765 reply(c, "USERID", "OTHER", buf);
769 /* Deny that there's anyone there at all. */
770 logmsg(&c->q, LOG_INFO, "user `%s' (%d); denying",
771 pw->pw_name, c->q.u.uid);
775 /* Report the user as being hidden. */
776 logmsg(&c->q, LOG_INFO, "user `%s' (%d); hiding",
777 pw->pw_name, c->q.u.uid);
778 reply_error(c, E_HIDDEN);
782 /* Tell an egregious lie about who the user is. */
783 logmsg(&c->q, LOG_INFO, "user `%s' (%d); lie = `%s'",
784 pw->pw_name, c->q.u.uid, pol->act.u.lie);
785 reply(c, "USERID", "UNIX", pol->act.u.lie);
789 /* Something has gone very wrong. */
798 logmsg(&c->q, LOG_ERR, "failed to parse query from client");
799 disconnect_client(c);
802 /* Notification that a new client has connected. Prepare to read a query. */
803 static void accept_client(int fd, unsigned mode, void *p)
805 struct listen *l = p;
807 struct sockaddr_storage ssr, ssl;
808 size_t ssz = sizeof(ssr);
811 /* Accept the new connection. */
812 if ((sk = accept(fd, (struct sockaddr *)&ssr, &ssz)) < 0) {
813 if (errno != EAGAIN && errno == EWOULDBLOCK) {
814 logmsg(0, LOG_ERR, "failed to accept incoming %s connection: %s",
815 l->ao->name, strerror(errno));
819 if (fix_up_socket(sk, "incoming client")) { close(sk); return; }
821 /* Build a client block and fill it in. */
822 c = xmalloc(sizeof(*c));
826 /* Collect the local and remote addresses. */
827 l->ao->sockaddr_to_addr(&ssr, &c->raddr);
829 if (getsockname(sk, (struct sockaddr *)&ssl, &ssz)) {
831 "failed to read local address for incoming %s connection: %s",
832 l->ao->name, strerror(errno));
837 l->ao->sockaddr_to_addr(&ssl, &c->q.s[L].addr);
838 c->q.s[L].port = c->q.s[R].port = 0;
840 /* Set stuff up for reading the query and sending responses. */
841 selbuf_init(&c->b, &sel, sk, client_line, c);
842 selbuf_setsize(&c->b, 1024);
843 reset_client_timer(c, 0);
846 init_writebuf(&c->wb, sk, done_client_write, c);
849 /*----- Main code ---------------------------------------------------------*/
851 /* Set up a listening socket for the address family described by AO,
854 static int make_listening_socket(const struct addrops *ao, int port)
859 struct sockaddr_storage ss;
863 /* Make the socket. */
864 if ((fd = socket(ao->af, SOCK_STREAM, 0)) < 0) {
865 if (errno == EAFNOSUPPORT) return (-1);
866 die(1, "failed to create %s listening socket: %s",
867 ao->name, strerror(errno));
870 /* Build the appropriate local address. */
873 ao->socket_to_sockaddr(&s, &ss, &ssz);
875 /* Perform any initialization specific to the address type. */
876 if (ao->init_listen_socket(fd)) {
877 die(1, "failed to initialize %s listening socket: %s",
878 ao->name, strerror(errno));
881 /* Bind to the address. */
882 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
883 if (bind(fd, (struct sockaddr *)&ss, ssz)) {
884 die(1, "failed to bind %s listening socket: %s",
885 ao->name, strerror(errno));
888 /* Avoid unpleasant race conditions. */
889 if (fdflags(fd, O_NONBLOCK, O_NONBLOCK, 0, 0)) {
890 die(1, "failed to set %s listening socket nonblocking: %s",
891 ao->name, strerror(errno));
894 /* Prepare to listen. */
896 die(1, "failed to listen for %s: %s", ao->name, strerror(errno));
898 /* Make a record of all of this. */
899 l = xmalloc(sizeof(*l));
901 sel_initfile(&sel, &l->f, fd, SEL_READ, accept_client, l);
908 /* Quit because of a fatal signal. */
909 static void quit(int sig, void *p)
911 const char *signame = p;
913 logmsg(0, LOG_NOTICE, "shutting down on %s", signame);
914 if (pidfile) unlink(pidfile);
918 /* Answer whether the string pointed to by P consists entirely of digits. */
919 static int numericp(const char *p)
922 if (!isdigit((unsigned char)*p++)) return (0);
926 static void usage(FILE *fp)
928 pquis(fp, "Usage: $ [-Dl] [-G GROUP] [-U USER] [-P FILE] "
929 "[-c FILE] [-p PORT]\n");
932 static void version(FILE *fp)
933 { pquis(fp, "$, version " VERSION "\n"); }
935 static void help(FILE *fp)
937 version(fp); fputc('\n', fp);
940 Yet Another Ident Daemon. Really, the world doesn't need such a thing.\n\
941 It's just a shame none of the others do the right things.\n\
945 -h, --help Show this help message.\n\
946 -v, --version Show the version number.\n\
947 -u, --usage Show a very short usage summary.\n\
949 -D, --daemon Become a daemon, running in the background.\n\
950 -G, --group=GROUP Set group after initialization.\n\
951 -P, --pidfile=FILE Write process id to FILE.\n\
952 -U, --user=USER Set user after initialization.\n\
953 -c, --config=FILE Read global policy from FILE.\n\
954 -l, --syslog Write log messages using syslog(3).\n\
955 -p, --port=PORT Listen for connections on this port.\n",
959 int main(int argc, char *argv[])
964 struct passwd *pw = 0;
973 const struct addrops *ao;
978 /* Parse command-line options. */
980 const struct option opts[] = {
981 { "help", 0, 0, 'h' },
982 { "version", 0, 0, 'v' },
983 { "usage", 0, 0, 'u' },
984 { "daemon", 0, 0, 'D' },
985 { "group", OPTF_ARGREQ, 0, 'G' },
986 { "pidfile", OPTF_ARGREQ, 0, 'P' },
987 { "user", OPTF_ARGREQ, 0, 'U' },
988 { "config", OPTF_ARGREQ, 0, 'c' },
989 { "syslog", 0, 0, 'l' },
990 { "port", OPTF_ARGREQ, 0, 'p' },
994 if ((i = mdwopt(argc, argv, "hvuDG:P:U:c:lp:", opts, 0, 0, 0)) < 0)
997 case 'h': help(stdout); exit(0);
998 case 'v': version(stdout); exit(0);
999 case 'u': usage(stdout); exit(0);
1000 case 'D': f |= f_daemon; break;
1001 case 'P': pidfile = optarg; break;
1002 case 'c': policyfile = optarg; break;
1003 case 'l': flags |= F_SYSLOG; break;
1005 if (numericp(optarg))
1007 else if ((gr = getgrnam(optarg)) == 0)
1008 die(1, "unknown group `%s'", optarg);
1013 if (numericp(optarg))
1015 else if ((pw = getpwnam(optarg)) == 0)
1016 die(1, "unknown user `%s'", optarg);
1021 if (numericp(optarg))
1022 port = atoi(optarg);
1023 else if ((s = getservbyname(optarg, "tcp")) == 0)
1024 die(1, "unknown service name `%s'", optarg);
1026 port = ntohs(s->s_port);
1028 default: f |= f_bogus; break;
1031 if (optind < argc) f |= f_bogus;
1032 if (f & f_bogus) { usage(stderr); exit(1); }
1034 /* If a user has been requested, but no group, then find the user's primary
1035 * group. If the user was given by name, then we already have a password
1036 * entry and should use that, in case two differently-named users have the
1037 * same uid but distinct gids.
1039 if (u != -1 && g == -1) {
1040 if (!pw && (pw = getpwuid(u)) == 0) {
1041 die(1, "failed to find password entry for user %d: "
1042 "request group explicitly", u);
1047 /* Initialize system-specific machinery. */
1050 /* Load the global policy rules. */
1051 fwatch_init(&polfw, policyfile);
1052 if (load_policy_file(policyfile, &policy))
1055 /* Open the random data source. */
1056 if ((randfd = open("/dev/urandom", O_RDONLY)) < 0) {
1057 die(1, "failed to open `/dev/urandom' for reading: %s",
1061 /* Set up the I/O event system. */
1064 /* Watch for some interesting signals. */
1066 sig_add(&sigint, SIGINT, quit, "SIGINT");
1067 sig_add(&sigterm, SIGTERM, quit, "SIGTERM");
1069 /* Listen for incoming connections. */
1070 for (ao = addroptab; ao->name; ao++)
1071 if (!make_listening_socket(ao, port)) any = 1;
1072 if (!any) die(1, "no IP protocols supported");
1074 /* Open the pidfile now, in case it's somewhere we can't write. */
1075 if (pidfile && (fp = fopen(pidfile, "w")) == 0) {
1076 die(1, "failed to open pidfile `%s' for writing: %s",
1077 pidfile, strerror(errno));
1080 /* If we're meant to use syslog, then open the log. */
1081 if (flags & F_SYSLOG)
1082 openlog(QUIS, 0, LOG_DAEMON);
1084 /* Drop privileges. */
1085 if ((g != -1 && (setegid(g) || setgid(g) ||
1086 (getuid() == 0 && setgroups(1, &g)))) ||
1087 (u != -1 && setuid(u)))
1088 die(1, "failed to drop privileges: %s", strerror(errno));
1090 /* Become a background process, if requested. */
1091 if ((f & f_daemon) && daemonize())
1092 die(1, "failed to become daemon: %s", strerror(errno));
1094 /* Write the process id to the pidfile. */
1096 fprintf(fp, "%d\n", getpid());
1100 /* And now we're going. */
1103 /* Read events and process them. */
1105 if (sel_select(&sel) && errno != EINTR)
1106 die(1, "select failed: %s", strerror(errno));
1109 /* This just keeps the compiler happy. */
1113 /*----- That's all, folks -------------------------------------------------*/