chiark / gitweb /
Makefile.am: Include `confsubst' machinery.
[yaid] / yaid.c
1 /* -*-c-*-
2  *
3  * Main daemon
4  *
5  * (c) 2012 Straylight/Edgeware
6  */
7
8 /*----- Licensing notice --------------------------------------------------*
9  *
10  * This file is part of Yet Another Ident Daemon (YAID).
11  *
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.
16  *
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.
21  *
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.
25  */
26
27 /*----- Header files ------------------------------------------------------*/
28
29 #include "yaid.h"
30
31 /*----- Data structures ---------------------------------------------------*/
32
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.
35  */
36 #define WRBUFSZ 1024
37 struct writebuf {
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 */
44 };
45
46 /* Structure for a listening socket.  There's one of these for each address
47  * family we're looking after.
48  */
49 struct listen {
50   const struct addrops *ao;             /* Address family operations */
51   sel_file f;                           /* Watch for incoming connections */
52 };
53
54 /* The main structure for a client. */
55 struct client {
56   int fd;                               /* The connection to the client */
57   selbuf b;                             /* Accumulate lines of input */
58   struct query q;                       /* The clients query and our reply */
59   struct sel_timer t;                   /* Timeout for idle or doomed conn */
60   struct listen *l;                     /* Back to the listener (and ops) */
61   struct writebuf wb;                   /* Write buffer for our reply */
62   struct proxy *px;                     /* Proxy if conn goes via NAT */
63 };
64
65 /* A proxy connection. */
66 struct proxy {
67   int fd;                               /* Connection; -1 if in progress */
68   struct client *c;                     /* Back to the client */
69   conn cn;                              /* Nonblocking connection */
70   selbuf b;                             /* Accumulate the response line */
71   struct writebuf wb;                   /* Write buffer for query */
72   char nat[ADDRLEN];                    /* Server address, as text */
73 };
74
75 /*----- Static variables --------------------------------------------------*/
76
77 static sel_state sel;                   /* I/O multiplexer state */
78
79 static const char *pidfile = 0;         /* Where to write daemon's pid */
80
81 static const char *policyfile = POLICYFILE; /* Filename for global policy */
82 static const struct policy default_policy = POLICY_INIT(A_NAME);
83 static policy_v policy = DA_INIT;       /* Vector of global policy rules */
84 static fwatch polfw;                    /* Watch policy file for changes */
85
86 static unsigned char tokenbuf[4096];    /* Random-ish data for tokens */
87 static size_t tokenptr = sizeof(tokenbuf); /* Current read position */
88 static int randfd;                      /* File descriptor for random data */
89
90 static unsigned flags = 0;              /* Various interesting flags */
91 #define F_SYSLOG 1u                     /*   Use syslog for logging */
92 #define F_RUNNING 2u                    /*   Running properly now */
93
94 /*----- Ident protocol parsing --------------------------------------------*/
95
96 /* Advance *PP over whitespace characters. */
97 static void skipws(const char **pp)
98   { while (isspace((unsigned char )**pp)) (*pp)++; }
99
100 /* Copy a token of no more than N bytes starting at *PP into Q, advancing *PP
101  * over it.
102  */
103 static int idtoken(const char **pp, char *q, size_t n)
104 {
105   const char *p = *pp;
106
107   skipws(&p);
108   n--;
109   for (;;) {
110     if (*p == ':' || *p <= 32 || *p >= 127) break;
111     if (!n) return (-1);
112     *q++ = *p++;
113     n--;
114   }
115   *q++ = 0;
116   *pp = p;
117   return (0);
118 }
119
120 /* Read an unsigned decimal number from *PP, and store it in *II.  Check that
121  * it's between MIN and MAX, and advance *PP over it.  Return zero for
122  * success, or nonzero if something goes wrong.
123  */
124 static int unum(const char **pp, unsigned *ii, unsigned min, unsigned max)
125 {
126   char *q;
127   unsigned long i;
128   int e;
129
130   skipws(pp);
131   if (!isdigit((unsigned char)**pp)) return (-1);
132   e = errno; errno = 0;
133   i = strtoul(*pp, &q, 10);
134   if (errno) return (-1);
135   *pp = q;
136   errno = e;
137   if (i < min || i > max) return (-1);
138   *ii = i;
139   return (0);
140 }
141
142 /*----- Asynchronous writing ----------------------------------------------*/
143
144 /* Callback for actually writing stuff from a `writebuf'. */
145 static void write_out(int fd, unsigned mode, void *p)
146 {
147   ssize_t n;
148   struct writebuf *wb = p;
149
150   /* Try to write something. */
151   if ((n = write(fd, wb->buf + wb->o, wb->n)) < 0) {
152     if (errno == EAGAIN || errno == EWOULDBLOCK) return;
153     wb->n = 0;
154     sel_rmfile(&wb->wr);
155     wb->func(errno, wb->p);
156   }
157   wb->o += n;
158   wb->n -= n;
159
160   /* If there's nothing left then restore the buffer to its empty state. */
161   if (!wb->n) {
162     wb->o = 0;
163     sel_rmfile(&wb->wr);
164     wb->func(0, wb->p);
165   }
166 }
167
168 /* Queue N bytes starting at P to be written. */
169 static int queue_write(struct writebuf *wb, const void *p, size_t n)
170 {
171   /* Maybe there's nothing to actually do. */
172   if (!n) return (0);
173
174   /* Make sure it'll fit. */
175   if (wb->n - wb->o + n > WRBUFSZ) return (-1);
176
177   /* If there's anything there already, then make sure it's at the start of
178    * the available space.
179    */
180   if (wb->o) {
181     memmove(wb->buf, wb->buf + wb->o, wb->n);
182     wb->o = 0;
183   }
184
185   /* If there's nothing currently there, then we're not requesting write
186    * notifications, so set that up, and force an initial wake-up.
187    */
188   if (!wb->n) {
189     sel_addfile(&wb->wr);
190     sel_force(&wb->wr);
191   }
192
193   /* Copy the new material over. */
194   memcpy(wb->buf + wb->n, p, n);
195   wb->n += n;
196
197   /* Done. */
198   return (0);
199 }
200
201 /* Release resources allocated to WB. */
202 static void free_writebuf(struct writebuf *wb)
203   { if (wb->n) sel_rmfile(&wb->wr); }
204
205 /* Initialize a writebuf in *WB, writing to file descriptor FD.  On
206  * completion, call FUNC, passing it P and an error indicator: either 0 for
207  * success or an `errno' value on failure.
208  */
209 static void init_writebuf(struct writebuf *wb,
210                           int fd, void (*func)(int, void *), void *p)
211 {
212   sel_initfile(&sel, &wb->wr, fd, SEL_WRITE, write_out, wb);
213   wb->func = func;
214   wb->p = p;
215   wb->n = wb->o = 0;
216 }
217
218 /*----- General utilities -------------------------------------------------*/
219
220 /* Format and log MSG somewhere sensible, at the syslog(3) priority PRIO.
221  * Prefix it with a description of the query Q, if non-null.
222  */
223 void logmsg(const struct query *q, int prio, const char *msg, ...)
224 {
225   va_list ap;
226   dstr d = DSTR_INIT;
227   time_t t;
228   struct tm *tm;
229   char buf[64];
230
231   va_start(ap, msg);
232   if (q) {
233     dputsock(&d, q->ao, &q->s[L]);
234     dstr_puts(&d, " <-> ");
235     dputsock(&d, q->ao, &q->s[R]);
236     dstr_puts(&d, ": ");
237   }
238   dstr_vputf(&d, msg, &ap);
239   va_end(ap);
240
241   if (!(flags & F_RUNNING))
242     moan("%s", d.buf);
243   else if (flags & F_SYSLOG)
244     syslog(prio, "%s", d.buf);
245   else {
246     t = time(0);
247     tm = localtime(&t);
248     strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S %z", tm);
249     fprintf(stderr, "%s %s: %s\n", buf, QUIS, d.buf);
250   }
251
252   dstr_destroy(&d);
253 }
254
255 /* Fix up a socket FD so that it won't bite us.  Returns zero on success, or
256  * nonzero on error.
257  */
258 static int fix_up_socket(int fd, const char *what)
259 {
260   int yes = 1;
261
262   if (fdflags(fd, O_NONBLOCK, O_NONBLOCK, 0, 0)) {
263     logmsg(0, LOG_ERR, "failed to set %s connection nonblocking: %s",
264            what, strerror(errno));
265     return (-1);
266   }
267
268   if (setsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &yes, sizeof(yes))) {
269     logmsg(0, LOG_ERR,
270            "failed to disable `out-of-band' data on %s connection: %s",
271            what, strerror(errno));
272     return (-1);
273   }
274
275   return (0);
276 }
277
278 /*----- Client output functions -------------------------------------------*/
279
280 static void disconnect_client(struct client *c);
281
282 /* Notification that output has been written.  If successful, re-enable the
283  * input buffer and prepare for another query.
284  */
285 static void done_client_write(int err, void *p)
286 {
287   struct client *c = p;
288
289   if (!err)
290     selbuf_enable(&c->b);
291   else {
292     logmsg(&c->q, LOG_ERR, "failed to send reply: %s", strerror(err));
293     disconnect_client(c);
294   }
295 }
296
297 /* Format the message FMT and queue it to be sent to the client.  Client
298  * input will be disabled until the write completes.
299  */
300 static void write_to_client(struct client *c, const char *fmt, ...)
301 {
302   va_list ap;
303   char buf[WRBUFSZ];
304   ssize_t n;
305
306   va_start(ap, fmt);
307   n = vsnprintf(buf, sizeof(buf), fmt, ap);
308   if (n < 0) {
309     logmsg(&c->q, LOG_ERR, "failed to format output: %s", strerror(errno));
310     disconnect_client(c);
311     return;
312   } else if (n > sizeof(buf)) {
313     logmsg(&c->q, LOG_ERR, "output too long for client send buffer");
314     disconnect_client(c);
315     return;
316   }
317
318   selbuf_disable(&c->b);
319   if (queue_write(&c->wb, buf, n)) {
320     logmsg(&c->q, LOG_ERR, "write buffer overflow");
321     disconnect_client(c);
322   }
323 }
324
325 /* Format a reply to the client, with the form LPORT:RPORT:TY:TOK0[:TOK1].
326  * Typically, TY will be `ERROR' or `USERID'.  In the former case, TOK0 will
327  * be the error token and TOK1 will be null; in the latter case, TOK0 will be
328  * the operating system and TOK1 the user name.
329  */
330 static void reply(struct client *c, const char *ty,
331                   const char *tok0, const char *tok1)
332 {
333   write_to_client(c, "%u,%u:%s:%s%s%s\r\n",
334                   c->q.s[L].port, c->q.s[R].port, ty,
335                   tok0, tok1 ? ":" : "", tok1 ? tok1 : "");
336 }
337
338 /* Mapping from error codes to their protocol tokens. */
339 const char *const errtok[] = {
340 #define DEFTOK(err, tok) tok,
341   ERROR(DEFTOK)
342 #undef DEFTOK
343 };
344
345 /* Report an error with code ERR to the client. */
346 static void reply_error(struct client *c, unsigned err)
347 {
348   assert(err < E_LIMIT);
349   reply(c, "ERROR", errtok[err], 0);
350 }
351
352 /*----- NAT proxy functions -----------------------------------------------*/
353
354 /* Cancel the proxy operation PX, closing the connection and releasing
355  * resources.  This is used for both normal and unexpected closures.
356  */
357 static void cancel_proxy(struct proxy *px)
358 {
359   if (px->fd == -1)
360     conn_kill(&px->cn);
361   else {
362     close(px->fd);
363     selbuf_destroy(&px->b);
364     free_writebuf(&px->wb);
365   }
366   selbuf_enable(&px->c->b);
367   px->c->px = 0;
368   xfree(px);
369 }
370
371 /* Notification that a line (presumably a reply) has been received from the
372  * server.  We should check it, log it, and propagate the answer back.
373  * Whatever happens, this proxy operation is now complete.
374  */
375 static void proxy_line(char *line, size_t sz, void *p)
376 {
377   struct proxy *px = p;
378   char buf[1024];
379   const char *q = line;
380   unsigned lp, rp;
381
382   /* Trim trailing space. */
383   while (sz && isspace((unsigned char)line[sz - 1])) sz--;
384
385   /* Parse the port numbers.  These should match the request. */
386   if (unum(&q, &lp, 1, 65535)) goto syntax;
387   skipws(&q); if (*q != ',') goto syntax; q++;
388   if (unum(&q, &rp, 1, 65535)) goto syntax;
389   skipws(&q); if (*q != ':') goto syntax; q++;
390   if (lp != px->c->q.u.nat.port || rp != px->c->q.s[R].port) goto syntax;
391
392   /* Find out what kind of reply this is. */
393   if (idtoken(&q, buf, sizeof(buf))) goto syntax;
394   skipws(&q); if (*q != ':') goto syntax; q++;
395
396   if (strcmp(buf, "ERROR") == 0) {
397
398     /* Report the error without interpreting it.  It might be meaningful to
399      * the client.
400      */
401     skipws(&q);
402     logmsg(&px->c->q, LOG_ERR, "proxy error from %s: %s", px->nat, q);
403     reply(px->c, "ERROR", q, 0);
404
405   } else if (strcmp(buf, "USERID") == 0) {
406
407     /* Parse out the operating system and user name, and pass them on. */
408     if (idtoken(&q, buf, sizeof(buf))) goto syntax;
409     skipws(&q); if (*q != ':') goto syntax; q++;
410     skipws(&q);
411     logmsg(&px->c->q, LOG_ERR, "user `%s'; proxy = %s, os = %s",
412            q, px->nat, buf);
413     reply(px->c, "USERID", buf, q);
414
415   } else
416     goto syntax;
417   goto done;
418
419 syntax:
420   /* We didn't understand the message from the client. */
421   logmsg(&px->c->q, LOG_ERR, "failed to parse response from %s", px->nat);
422   reply_error(px->c, E_UNKNOWN);
423 done:
424   /* All finished, no matter what. */
425   cancel_proxy(px);
426 }
427
428 /* Notification that we have written the query to the server.  Await a
429  * response if successful.
430  */
431 static void done_proxy_write(int err, void *p)
432 {
433   struct proxy *px = p;
434
435   if (err) {
436     logmsg(&px->c->q, LOG_ERR, "failed to proxy query to %s: %s",
437            px->nat, strerror(errno));
438     reply_error(px->c, E_UNKNOWN);
439     cancel_proxy(px);
440     return;
441   }
442   selbuf_enable(&px->b);
443 }
444
445 /* Notification that the connection to the server is either established or
446  * failed.  In the former case, queue the right query.
447  */
448 static void proxy_connected(int fd, void *p)
449 {
450   struct proxy *px = p;
451   char buf[16];
452   int n;
453
454   /* If the connection failed then report the problem and give up. */
455   if (fd < 0) {
456     logmsg(&px->c->q, LOG_ERR,
457            "failed to make %s proxy connection to %s: %s",
458            px->c->l->ao->name, px->nat, strerror(errno));
459     reply_error(px->c, E_UNKNOWN);
460     cancel_proxy(px);
461     return;
462   }
463
464   /* We're now ready to go, so set things up. */
465   px->fd = fd;
466   selbuf_init(&px->b, &sel, fd, proxy_line, px);
467   selbuf_setsize(&px->b, 1024);
468   selbuf_disable(&px->b);
469   init_writebuf(&px->wb, fd, done_proxy_write, px);
470
471   /* Write the query.  This buffer is large enough because we've already
472    * range-checked the remote the port number and the local one came from the
473    * kernel, which we trust not to do anything stupid.
474    */
475   n = sprintf(buf, "%u,%u\r\n", px->c->q.u.nat.port, px->c->q.s[R].port);
476   queue_write(&px->wb, buf, n);
477 }
478
479 /* Proxy the query through to a client machine for which we're providing NAT
480  * disservice.
481  */
482 static void proxy_query(struct client *c)
483 {
484   struct socket s;
485   struct sockaddr_storage ss;
486   size_t ssz;
487   struct proxy *px;
488   int fd;
489
490   /* Allocate the context structure for the NAT. */
491   px = xmalloc(sizeof(*px));
492
493   /* We'll use the client host's address in lots of log messages, so we may
494    * as well format it once and use it over and over.
495    */
496   inet_ntop(c->q.ao->af, &c->q.u.nat.addr, px->nat, sizeof(px->nat));
497
498   /* Create the socket for the connection. */
499   if ((fd = socket(c->q.ao->af, SOCK_STREAM, 0)) < 0) {
500     logmsg(&c->q, LOG_ERR, "failed to make %s socket for proxy: %s",
501            c->l->ao->name, strerror(errno));
502     goto err_0;
503   }
504   if (fix_up_socket(fd, "proxy")) goto err_1;
505
506   /* Set up the connection to the client host.  The connection interface is a
507    * bit broken: if the connection completes immediately, then the callback
508    * function is called synchronously, and that might decide to shut
509    * everything down.  So we must have fully initialized our context before
510    * calling `conn_init', and mustn't touch it again afterwards -- since the
511    * block may have been freed.
512    */
513   s = c->q.u.nat;
514   s.port = 113;
515   c->l->ao->socket_to_sockaddr(&s, &ss, &ssz);
516   selbuf_disable(&c->b);
517   c->px = px; px->c = c;
518   px->fd = -1;
519   if (conn_init(&px->cn, &sel, fd, (struct sockaddr *)&ss, ssz,
520                 proxy_connected, px)) {
521     logmsg(&c->q, LOG_ERR, "failed to make %s proxy connection to %s: %s",
522            c->l->ao->name, px->nat, strerror(errno));
523     goto err_2;
524   }
525
526   /* All ready to go. */
527   return;
528
529   /* Tidy up after various kinds of failures. */
530 err_2:
531   selbuf_enable(&c->b);
532 err_1:
533   close(px->fd);
534 err_0:
535   xfree(px);
536   reply_error(c, E_UNKNOWN);
537 }
538
539 /*----- Client connection functions ---------------------------------------*/
540
541 /* Disconnect a client, freeing up any associated resources. */
542 static void disconnect_client(struct client *c)
543 {
544   close(c->fd);
545   selbuf_destroy(&c->b);
546   sel_rmtimer(&c->t);
547   free_writebuf(&c->wb);
548   if (c->px) cancel_proxy(c->px);
549   xfree(c);
550 }
551
552 /* Time out a client because it's been idle for too long. */
553 static void timeout_client(struct timeval *tv, void *p)
554 {
555   struct client *c = p;
556   logmsg(&c->q, LOG_NOTICE, "timing out idle or stuck client");
557   sel_addtimer(&sel, &c->t, tv, timeout_client, 0);
558   disconnect_client(c);
559 }
560
561 /* Reset the client idle timer, as a result of activity.  Set EXISTP if
562  * there is an existing timer which needs to be removed.
563  */
564 static void reset_client_timer(struct client *c, int existp)
565 {
566   struct timeval tv;
567
568   gettimeofday(&tv, 0);
569   tv.tv_sec += 30;
570   if (existp) sel_rmtimer(&c->t);
571   sel_addtimer(&sel, &c->t, &tv, timeout_client, c);
572 }
573
574 /* Write a pseudorandom token into the buffer at P, which must have space for
575  * at least TOKENSZ bytes.
576  */
577 #define TOKENRANDSZ 8
578 #define TOKENSZ ((4*TOKENRANDSZ + 5)/3)
579 static void user_token(char *p)
580 {
581   unsigned a = 0;
582   unsigned b = 0;
583   int i;
584   static const char tokmap[64] =
585     "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.-";
586
587   /* If there's not enough pseudorandom stuff lying around, then read more
588    * from the kernel.
589    */
590   if (tokenptr + TOKENRANDSZ >= sizeof(tokenbuf)) {
591     if (read(randfd, tokenbuf, sizeof(tokenbuf)) < sizeof(tokenbuf))
592       die(1, "unexpected short read or error from `/dev/urandom'");
593     tokenptr = 0;
594   }
595
596   /* Now encode the bytes using a slightly tweaked base-64 encoding.  Read
597    * bytes into the accumulator and write out characters while there's
598    * enough material.
599    */
600   for (i = 0; i < TOKENRANDSZ; i++) {
601     a = (a << 8) | tokenbuf[tokenptr++]; b += 8;
602     while (b >= 6) {
603       b -= 6;
604       *p++ = tokmap[(a >> b) & 0x3f];
605     }
606   }
607
608   /* If there's anything left in the accumulator then flush it out. */
609   if (b)
610     *p++ = tokmap[(a << (6 - b)) & 0x3f];
611
612   /* Null-terminate the token. */
613   *p++ = 0;
614 }
615
616 /* Notification that a line has been received from the client.  Parse it,
617  * find out about the connection it's referring to, apply the relevant
618  * policy rules, and produce a response.  This is where almost everything
619  * interesting happens.
620  */
621 static void client_line(char *line, size_t len, void *p)
622 {
623   struct client *c = p;
624   const char *q;
625   struct passwd *pw = 0;
626   const struct policy *pol;
627   dstr d = DSTR_INIT;
628   struct policy upol = POLICY_INIT(A_LIMIT);
629   struct policy_file pf;
630   char buf[16];
631   int i;
632
633   /* If the connection has closed, then tidy stuff away. */
634   c->q.s[L].port = c->q.s[R].port = 0;
635   if (!line) {
636     disconnect_client(c);
637     return;
638   }
639
640   /* Client activity, so update the timer. */
641   reset_client_timer(c, 1);
642
643   /* See if the policy file has changed since we last looked.  If so, try to
644    * read the new version.
645    */
646   if (fwatch_update(&polfw, policyfile)) {
647     logmsg(0, LOG_INFO, "reload master policy file `%s'", policyfile);
648     load_policy_file(policyfile, &policy);
649   }
650
651   /* Read the local and remote port numbers into the query structure. */
652   q = line;
653   if (unum(&q, &c->q.s[L].port, 1, 65535)) goto bad;
654   skipws(&q); if (*q != ',') goto bad; q++;
655   if (unum(&q, &c->q.s[R].port, 1, 65535)) goto bad;
656   skipws(&q); if (*q) goto bad;
657
658   /* Identify the connection.  Act on the result. */
659   identify(&c->q);
660   switch (c->q.resp) {
661
662     case R_UID:
663       /* We found a user.  Track down the user's password entry, because
664        * we'll want that later.  Most of the processing for this case is
665        * below.
666        */
667       if ((pw = getpwuid(c->q.u.uid)) == 0) {
668         logmsg(&c->q, LOG_ERR, "no passwd entry for user %d", c->q.u.uid);
669         reply_error(c, E_NOUSER);
670         return;
671       }
672       break;
673
674     case R_NAT:
675       /* We've acted as a NAT for this connection.  Proxy the query through
676        * to the actal client host.
677        */
678       proxy_query(c);
679       return;
680
681     case R_ERROR:
682       /* We failed to identify the connection for some reason.  We should
683        * already have logged an error, so there's not much to do here.
684        */
685       reply_error(c, c->q.u.error);
686       return;
687
688     default:
689       /* Something happened that we don't understand. */
690       abort();
691   }
692
693   /* Search the table of policy rules to find a match. */
694   for (i = 0; i < DA_LEN(&policy); i++) {
695     pol = &DA(&policy)[i];
696     if (!match_policy(pol, &c->q)) continue;
697
698     /* If this is something simple, then apply the resulting policy rule. */
699     if (pol->act.act != A_USER) goto match;
700
701     /* The global policy has decided to let the user have a say, so we must
702      * parse the user file.
703      */
704     DRESET(&d);
705     dstr_putf(&d, "%s/.yaid.policy", pw->pw_dir);
706     if (open_policy_file(&pf, d.buf, "user policy file", &c->q))
707       continue;
708     while (!read_policy_file(&pf)) {
709
710       /* Give up after 100 lines.  If the user's policy is that complicated,
711        * something's gone very wrong.  Or there's too much commentary or
712        * something.
713        */
714       if (pf.lno > 100) {
715         logmsg(&c->q, LOG_ERR, "%s:%d: user policy file too long",
716                pf.name, pf.lno);
717         break;
718       }
719
720       /* If this isn't a match, go around for the next rule. */
721       if (!match_policy(&pf.p, &c->q)) continue;
722
723       /* Check that the user is allowed to request this action.  If not, see
724        * if there's a more acceptable action later on.
725        */
726       if (!(pol->act.u.user & (1 << pf.p.act.act))) {
727         logmsg(&c->q, LOG_ERR,
728                "%s:%d: user action forbidden by global policy",
729                pf.name, pf.lno);
730         continue;
731       }
732
733       /* We've found a match, so grab it, close the file, and say we're
734        * done.
735        */
736       upol = pf.p; pol = &upol;
737       init_policy(&pf.p);
738       close_policy_file(&pf);
739       DDESTROY(&d);
740       goto match;
741     }
742     close_policy_file(&pf);
743     DDESTROY(&d);
744   }
745
746   /* No match: apply the built-in default policy. */
747   pol = &default_policy;
748
749 match:
750   switch (pol->act.act) {
751
752     case A_NAME:
753       /* Report the actual user's name. */
754       logmsg(&c->q, LOG_INFO, "user `%s' (%d)", pw->pw_name, c->q.u.uid);
755       reply(c, "USERID", "UNIX", pw->pw_name);
756       break;
757
758     case A_TOKEN:
759       /* Report an arbitrary token which we can look up in our log file. */
760       user_token(buf);
761       logmsg(&c->q, LOG_INFO, "user `%s' (%d); token = %s",
762              pw->pw_name, c->q.u.uid, buf);
763       reply(c, "USERID", "OTHER", buf);
764       break;
765
766     case A_DENY:
767       /* Deny that there's anyone there at all. */
768       logmsg(&c->q, LOG_INFO, "user `%s' (%d); denying",
769              pw->pw_name, c->q.u.uid);
770       break;
771
772     case A_HIDE:
773       /* Report the user as being hidden. */
774       logmsg(&c->q, LOG_INFO, "user `%s' (%d); hiding",
775              pw->pw_name, c->q.u.uid);
776       reply_error(c, E_HIDDEN);
777       break;
778
779     case A_LIE:
780       /* Tell an egregious lie about who the user is. */
781       logmsg(&c->q, LOG_INFO, "user `%s' (%d); lie = `%s'",
782              pw->pw_name, c->q.u.uid, pol->act.u.lie);
783       reply(c, "USERID", "UNIX", pol->act.u.lie);
784       break;
785
786     default:
787       /* Something has gone very wrong. */
788       abort();
789   }
790
791   /* All done. */
792   free_policy(&upol);
793   return;
794
795 bad:
796   logmsg(&c->q, LOG_ERR, "failed to parse query from client");
797   disconnect_client(c);
798 }
799
800 /* Notification that a new client has connected.  Prepare to read a query. */
801 static void accept_client(int fd, unsigned mode, void *p)
802 {
803   struct listen *l = p;
804   struct client *c;
805   struct sockaddr_storage ssr, ssl;
806   size_t ssz = sizeof(ssr);
807   int sk;
808
809   /* Accept the new connection. */
810   if ((sk = accept(fd, (struct sockaddr *)&ssr, &ssz)) < 0) {
811     if (errno != EAGAIN && errno == EWOULDBLOCK) {
812       logmsg(0, LOG_ERR, "failed to accept incoming %s connection: %s",
813              l->ao->name, strerror(errno));
814     }
815     return;
816   }
817   if (fix_up_socket(sk, "incoming client")) { close(sk); return; }
818
819   /* Build a client block and fill it in. */
820   c = xmalloc(sizeof(*c));
821   c->l = l;
822   c->q.ao = l->ao;
823
824   /* Collect the local and remote addresses. */
825   l->ao->sockaddr_to_addr(&ssr, &c->q.s[R].addr);
826   ssz = sizeof(ssl);
827   if (getsockname(sk, (struct sockaddr *)&ssl, &ssz)) {
828     logmsg(0, LOG_ERR,
829            "failed to read local address for incoming %s connection: %s",
830            l->ao->name, strerror(errno));
831     close(sk);
832     xfree(c);
833     return;
834   }
835   l->ao->sockaddr_to_addr(&ssl, &c->q.s[L].addr);
836   c->q.s[L].port = c->q.s[R].port = 0;
837
838   /* Set stuff up for reading the query and sending responses. */
839   selbuf_init(&c->b, &sel, sk, client_line, c);
840   selbuf_setsize(&c->b, 1024);
841   reset_client_timer(c, 0);
842   c->fd = sk;
843   c->px = 0;
844   init_writebuf(&c->wb, sk, done_client_write, c);
845 }
846
847 /*----- Main code ---------------------------------------------------------*/
848
849 /* Set up a listening socket for the address family described by AO,
850  * listening on PORT.
851  */
852 static int make_listening_socket(const struct addrops *ao, int port)
853 {
854   int fd;
855   int yes = 1;
856   struct socket s;
857   struct sockaddr_storage ss;
858   struct listen *l;
859   size_t ssz;
860
861   /* Make the socket. */
862   if ((fd = socket(ao->af, SOCK_STREAM, 0)) < 0) {
863     if (errno == EAFNOSUPPORT) return (-1);
864     die(1, "failed to create %s listening socket: %s",
865         ao->name, strerror(errno));
866   }
867
868   /* Build the appropriate local address. */
869   s.addr = *ao->any;
870   s.port = port;
871   ao->socket_to_sockaddr(&s, &ss, &ssz);
872
873   /* Perform any initialization specific to the address type. */
874   if (ao->init_listen_socket(fd)) {
875     die(1, "failed to initialize %s listening socket: %s",
876         ao->name, strerror(errno));
877   }
878
879   /* Bind to the address. */
880   setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
881   if (bind(fd, (struct sockaddr *)&ss, ssz)) {
882     die(1, "failed to bind %s listening socket: %s",
883         ao->name, strerror(errno));
884   }
885
886   /* Avoid unpleasant race conditions. */
887   if (fdflags(fd, O_NONBLOCK, O_NONBLOCK, 0, 0)) {
888     die(1, "failed to set %s listening socket nonblocking: %s",
889         ao->name, strerror(errno));
890   }
891
892   /* Prepare to listen. */
893   if (listen(fd, 5))
894     die(1, "failed to listen for %s: %s", ao->name, strerror(errno));
895
896   /* Make a record of all of this. */
897   l = xmalloc(sizeof(*l));
898   l->ao = ao;
899   sel_initfile(&sel, &l->f, fd, SEL_READ, accept_client, l);
900   sel_addfile(&l->f);
901
902   /* Done. */
903   return (0);
904 }
905
906 /* Quit because of a fatal signal. */
907 static void quit(int sig, void *p)
908 {
909   const char *signame = p;
910
911   logmsg(0, LOG_NOTICE, "shutting down on %s", signame);
912   if (pidfile) unlink(pidfile);
913   exit(0);
914 }
915
916 /* Answer whether the string pointed to by P consists entirely of digits. */
917 static int numericp(const char *p)
918 {
919   while (*p)
920     if (!isdigit((unsigned char)*p++)) return (0);
921   return (1);
922 }
923
924 static void usage(FILE *fp)
925 {
926   pquis(fp, "Usage: $ [-Dl] [-G GROUP] [-U USER] [-P FILE] "
927         "[-c FILE] [-p PORT]\n");
928 }
929
930 static void version(FILE *fp)
931   { pquis(fp, "$, version " VERSION "\n"); }
932
933 static void help(FILE *fp)
934 {
935   version(fp); fputc('\n', fp);
936   usage(fp);
937   fputs("\n\
938 Yet Another Ident Daemon.  Really, the world doesn't need such a thing.\n\
939 It's just a shame none of the others do the right things.\n\
940 \n\
941 Options:\n\
942 \n\
943   -h, --help            Show this help message.\n\
944   -v, --version         Show the version number.\n\
945   -u, --usage           Show a very short usage summary.\n\
946 \n\
947   -D, --daemon          Become a daemon, running in the background.\n\
948   -G, --group=GROUP     Set group after initialization.\n\
949   -P, --pidfile=FILE    Write process id to FILE.\n\
950   -U, --user=USER       Set user after initialization.\n\
951   -c, --config=FILE     Read global policy from FILE.\n\
952   -l, --syslog          Write log messages using syslog(3).\n\
953   -p, --port=PORT       Listen for connections on this port.\n",
954         fp);
955 }
956
957 int main(int argc, char *argv[])
958 {
959   int port = 113;
960   uid_t u = -1;
961   gid_t g = -1;
962   struct passwd *pw = 0;
963   struct group *gr;
964   struct servent *s;
965   sig sigint, sigterm;
966   FILE *fp = 0;
967   int i;
968   unsigned f = 0;
969 #define f_bogus 1u
970 #define f_daemon 2u
971   const struct addrops *ao;
972   int any = 0;
973
974   ego(argv[0]);
975
976   /* Parse command-line options. */
977   for (;;) {
978     const struct option opts[] = {
979       { "help",         0,              0,      'h' },
980       { "version",      0,              0,      'v' },
981       { "usage",        0,              0,      'u' },
982       { "daemon",       0,              0,      'D' },
983       { "group",        OPTF_ARGREQ,    0,      'G' },
984       { "pidfile",      OPTF_ARGREQ,    0,      'P' },
985       { "user",         OPTF_ARGREQ,    0,      'U' },
986       { "config",       OPTF_ARGREQ,    0,      'c' },
987       { "syslog",       0,              0,      'l' },
988       { "port",         OPTF_ARGREQ,    0,      'p' },
989       { 0,              0,              0,      0 }
990     };
991
992     if ((i = mdwopt(argc, argv, "hvuDG:P:U:c:lp:", opts, 0, 0, 0)) < 0)
993       break;
994     switch (i) {
995       case 'h': help(stdout); exit(0);
996       case 'v': version(stdout); exit(0);
997       case 'u': usage(stdout); exit(0);
998       case 'D': f |= f_daemon; break;
999       case 'P': pidfile = optarg; break;
1000       case 'c': policyfile = optarg; break;
1001       case 'l': flags |= F_SYSLOG; break;
1002       case 'G':
1003         if (numericp(optarg))
1004           g = atoi(optarg);
1005         else if ((gr = getgrnam(optarg)) == 0)
1006           die(1, "unknown group `%s'", optarg);
1007         else
1008           g = gr->gr_gid;
1009         break;
1010       case 'U':
1011         if (numericp(optarg))
1012           u = atoi(optarg);
1013         else if ((pw = getpwnam(optarg)) == 0)
1014           die(1, "unknown user `%s'", optarg);
1015         else
1016           u = pw->pw_uid;
1017         break;
1018       case 'p':
1019         if (numericp(optarg))
1020           port = atoi(optarg);
1021         else if ((s = getservbyname(optarg, "tcp")) == 0)
1022           die(1, "unknown service name `%s'", optarg);
1023         else
1024           port = ntohs(s->s_port);
1025         break;
1026       default: f |= f_bogus; break;
1027     }
1028   }
1029   if (optind < argc) f |= f_bogus;
1030   if (f & f_bogus) { usage(stderr); exit(1); }
1031
1032   /* If a user has been requested, but no group, then find the user's primary
1033    * group.  If the user was given by name, then we already have a password
1034    * entry and should use that, in case two differently-named users have the
1035    * same uid but distinct gids.
1036    */
1037   if (u != -1 && g == -1) {
1038     if (!pw && (pw = getpwuid(u)) == 0) {
1039       die(1, "failed to find password entry for user %d: "
1040           "request group explicitly", u);
1041     }
1042     g = pw->pw_gid;
1043   }
1044
1045   /* Initialize system-specific machinery. */
1046   init_sys();
1047
1048   /* Load the global policy rules. */
1049   fwatch_init(&polfw, policyfile);
1050   if (load_policy_file(policyfile, &policy))
1051     exit(1);
1052
1053   /* Open the random data source. */
1054   if ((randfd = open("/dev/urandom", O_RDONLY)) < 0) {
1055     die(1, "failed to open `/dev/urandom' for reading: %s",
1056         strerror(errno));
1057   }
1058
1059   /* Set up the I/O event system. */
1060   sel_init(&sel);
1061
1062   /* Watch for some interesting signals. */
1063   sig_init(&sel);
1064   sig_add(&sigint, SIGINT, quit, "SIGINT");
1065   sig_add(&sigterm, SIGTERM, quit, "SIGTERM");
1066
1067   /* Listen for incoming connections. */
1068   for (ao = addroptab; ao->name; ao++)
1069     if (!make_listening_socket(ao, port)) any = 1;
1070   if (!any) die(1, "no IP protocols supported");
1071
1072   /* Open the pidfile now, in case it's somewhere we can't write. */
1073   if (pidfile && (fp = fopen(pidfile, "w")) == 0) {
1074     die(1, "failed to open pidfile `%s' for writing: %s",
1075         pidfile, strerror(errno));
1076   }
1077
1078   /* If we're meant to use syslog, then open the log. */
1079   if (flags & F_SYSLOG)
1080     openlog(QUIS, 0, LOG_DAEMON);
1081
1082   /* Drop privileges. */
1083   if ((g != -1 && (setegid(g) || setgid(g) ||
1084                    (getuid() == 0 && setgroups(1, &g)))) ||
1085       (u != -1 && setuid(u)))
1086     die(1, "failed to drop privileges: %s", strerror(errno));
1087
1088   /* Become a background process, if requested. */
1089   if ((f & f_daemon) && daemonize())
1090     die(1, "failed to become daemon: %s", strerror(errno));
1091
1092   /* Write the process id to the pidfile. */
1093   if (fp) {
1094     fprintf(fp, "%d\n", getpid());
1095     fclose(fp);
1096   }
1097
1098   /* And now we're going. */
1099   flags |= F_RUNNING;
1100
1101   /* Read events and process them. */
1102   for (;;) {
1103     if (sel_select(&sel) && errno != EINTR)
1104       die(1, "select failed: %s", strerror(errno));
1105   }
1106
1107   /* This just keeps the compiler happy. */
1108   return (0);
1109 }
1110
1111 /*----- That's all, folks -------------------------------------------------*/