chiark / gitweb /
yaid.c: Time out idle connections after 30s.
[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 struct policy default_policy = POLICY_INIT(A_NAME);
80 static policy_v policy = DA_INIT;       /* Vector of global policy rules */
81 static fwatch polfw;                    /* Watch policy file for changes */
82
83 static unsigned char tokenbuf[4096];    /* Random-ish data for tokens */
84 static size_t tokenptr = sizeof(tokenbuf); /* Current read position */
85 static int randfd;                      /* File descriptor for random data */
86
87 /*----- Ident protocol parsing --------------------------------------------*/
88
89 /* Advance *PP over whitespace characters. */
90 static void skipws(const char **pp)
91   { while (isspace((unsigned char )**pp)) (*pp)++; }
92
93 /* Copy a token of no more than N bytes starting at *PP into Q, advancing *PP
94  * over it.
95  */
96 static int idtoken(const char **pp, char *q, size_t n)
97 {
98   const char *p = *pp;
99
100   skipws(&p);
101   n--;
102   for (;;) {
103     if (*p == ':' || *p <= 32 || *p >= 127) break;
104     if (!n) return (-1);
105     *q++ = *p++;
106     n--;
107   }
108   *q++ = 0;
109   *pp = p;
110   return (0);
111 }
112
113 /* Read an unsigned decimal number from *PP, and store it in *II.  Check that
114  * it's between MIN and MAX, and advance *PP over it.  Return zero for
115  * success, or nonzero if something goes wrong.
116  */
117 static int unum(const char **pp, unsigned *ii, unsigned min, unsigned max)
118 {
119   char *q;
120   unsigned long i;
121   int e;
122
123   skipws(pp);
124   if (!isdigit((unsigned char)**pp)) return (-1);
125   e = errno; errno = 0;
126   i = strtoul(*pp, &q, 10);
127   if (errno) return (-1);
128   *pp = q;
129   errno = e;
130   if (i < min || i > max) return (-1);
131   *ii = i;
132   return (0);
133 }
134
135 /*----- Asynchronous writing ----------------------------------------------*/
136
137 /* Callback for actually writing stuff from a `writebuf'. */
138 static void write_out(int fd, unsigned mode, void *p)
139 {
140   ssize_t n;
141   struct writebuf *wb = p;
142
143   /* Try to write something. */
144   if ((n = write(fd, wb->buf + wb->o, wb->n)) < 0) {
145     if (errno == EAGAIN || errno == EWOULDBLOCK) return;
146     wb->n = 0;
147     sel_rmfile(&wb->wr);
148     wb->func(errno, wb->p);
149   }
150   wb->o += n;
151   wb->n -= n;
152
153   /* If there's nothing left then restore the buffer to its empty state. */
154   if (!wb->n) {
155     wb->o = 0;
156     sel_rmfile(&wb->wr);
157     wb->func(0, wb->p);
158   }
159 }
160
161 /* Queue N bytes starting at P to be written. */
162 static int queue_write(struct writebuf *wb, const void *p, size_t n)
163 {
164   /* Maybe there's nothing to actually do. */
165   if (!n) return (0);
166
167   /* Make sure it'll fit. */
168   if (wb->n - wb->o + n > WRBUFSZ) return (-1);
169
170   /* If there's anything there already, then make sure it's at the start of
171    * the available space.
172    */
173   if (wb->o) {
174     memmove(wb->buf, wb->buf + wb->o, wb->n);
175     wb->o = 0;
176   }
177
178   /* If there's nothing currently there, then we're not requesting write
179    * notifications, so set that up, and force an initial wake-up.
180    */
181   if (!wb->n) {
182     sel_addfile(&wb->wr);
183     sel_force(&wb->wr);
184   }
185
186   /* Copy the new material over. */
187   memcpy(wb->buf + wb->n, p, n);
188   wb->n += n;
189
190   /* Done. */
191   return (0);
192 }
193
194 /* Release resources allocated to WB. */
195 static void free_writebuf(struct writebuf *wb)
196   { if (wb->n) sel_rmfile(&wb->wr); }
197
198 /* Initialize a writebuf in *WB, writing to file descriptor FD.  On
199  * completion, call FUNC, passing it P and an error indicator: either 0 for
200  * success or an `errno' value on failure.
201  */
202 static void init_writebuf(struct writebuf *wb,
203                           int fd, void (*func)(int, void *), void *p)
204 {
205   sel_initfile(&sel, &wb->wr, fd, SEL_WRITE, write_out, wb);
206   wb->func = func;
207   wb->p = p;
208   wb->n = wb->o = 0;
209 }
210
211 /*----- General utilities -------------------------------------------------*/
212
213 /* Format and log MSG somewhere sensible, at the syslog(3) priority PRIO.
214  * Prefix it with a description of the query Q, if non-null.
215  */
216 void logmsg(const struct query *q, int prio, const char *msg, ...)
217 {
218   va_list ap;
219   dstr d = DSTR_INIT;
220
221   va_start(ap, msg);
222   if (q) {
223     dputsock(&d, q->ao, &q->s[L]);
224     dstr_puts(&d, " <-> ");
225     dputsock(&d, q->ao, &q->s[R]);
226     dstr_puts(&d, ": ");
227   }
228   dstr_vputf(&d, msg, &ap);
229   va_end(ap);
230   fprintf(stderr, "yaid: %s\n", d.buf);
231   dstr_destroy(&d);
232 }
233
234 /* Fix up a socket FD so that it won't bite us.  Returns zero on success, or
235  * nonzero on error.
236  */
237 static int fix_up_socket(int fd, const char *what)
238 {
239   int yes = 1;
240
241   if (fdflags(fd, O_NONBLOCK, O_NONBLOCK, 0, 0)) {
242     logmsg(0, LOG_ERR, "failed to set %s connection nonblocking: %s",
243            what, strerror(errno));
244     return (-1);
245   }
246
247   if (setsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &yes, sizeof(yes))) {
248     logmsg(0, LOG_ERR,
249            "failed to disable `out-of-band' data on %s connection: %s",
250            what, strerror(errno));
251     return (-1);
252   }
253
254   return (0);
255 }
256
257 /*----- Client output functions -------------------------------------------*/
258
259 static void disconnect_client(struct client *c);
260
261 /* Notification that output has been written.  If successful, re-enable the
262  * input buffer and prepare for another query.
263  */
264 static void done_client_write(int err, void *p)
265 {
266   struct client *c = p;
267
268   if (!err)
269     selbuf_enable(&c->b);
270   else {
271     logmsg(&c->q, LOG_ERR, "failed to send reply: %s", strerror(err));
272     disconnect_client(c);
273   }
274 }
275
276 /* Format the message FMT and queue it to be sent to the client.  Client
277  * input will be disabled until the write completes.
278  */
279 static void write_to_client(struct client *c, const char *fmt, ...)
280 {
281   va_list ap;
282   char buf[WRBUFSZ];
283   ssize_t n;
284
285   va_start(ap, fmt);
286   n = vsnprintf(buf, sizeof(buf), fmt, ap);
287   if (n < 0) {
288     logmsg(&c->q, LOG_ERR, "failed to format output: %s", strerror(errno));
289     disconnect_client(c);
290     return;
291   } else if (n > sizeof(buf)) {
292     logmsg(&c->q, LOG_ERR, "output too long for client send buffer");
293     disconnect_client(c);
294     return;
295   }
296
297   selbuf_disable(&c->b);
298   if (queue_write(&c->wb, buf, n)) {
299     logmsg(&c->q, LOG_ERR, "write buffer overflow");
300     disconnect_client(c);
301   }
302 }
303
304 /* Format a reply to the client, with the form LPORT:RPORT:TY:TOK0[:TOK1].
305  * Typically, TY will be `ERROR' or `USERID'.  In the former case, TOK0 will
306  * be the error token and TOK1 will be null; in the latter case, TOK0 will be
307  * the operating system and TOK1 the user name.
308  */
309 static void reply(struct client *c, const char *ty,
310                   const char *tok0, const char *tok1)
311 {
312   write_to_client(c, "%u,%u:%s:%s%s%s\r\n",
313                   c->q.s[L].port, c->q.s[R].port, ty,
314                   tok0, tok1 ? ":" : "", tok1 ? tok1 : "");
315 }
316
317 /* Mapping from error codes to their protocol tokens. */
318 const char *const errtok[] = {
319 #define DEFTOK(err, tok) tok,
320   ERROR(DEFTOK)
321 #undef DEFTOK
322 };
323
324 /* Report an error with code ERR to the client. */
325 static void reply_error(struct client *c, unsigned err)
326 {
327   assert(err < E_LIMIT);
328   reply(c, "ERROR", errtok[err], 0);
329 }
330
331 /*----- NAT proxy functions -----------------------------------------------*/
332
333 /* Cancel the proxy operation PX, closing the connection and releasing
334  * resources.  This is used for both normal and unexpected closures.
335  */
336 static void cancel_proxy(struct proxy *px)
337 {
338   if (px->fd == -1)
339     conn_kill(&px->cn);
340   else {
341     close(px->fd);
342     selbuf_destroy(&px->b);
343     free_writebuf(&px->wb);
344   }
345   selbuf_enable(&px->c->b);
346   px->c->px = 0;
347   xfree(px);
348 }
349
350 /* Notification that a line (presumably a reply) has been received from the
351  * server.  We should check it, log it, and propagate the answer back.
352  * Whatever happens, this proxy operation is now complete.
353  */
354 static void proxy_line(char *line, size_t sz, void *p)
355 {
356   struct proxy *px = p;
357   char buf[1024];
358   const char *q = line;
359   unsigned lp, rp;
360
361   /* Trim trailing space. */
362   while (sz && isspace((unsigned char)line[sz - 1])) sz--;
363
364   /* Parse the port numbers.  These should match the request. */
365   if (unum(&q, &lp, 1, 65535)) goto syntax;
366   skipws(&q); if (*q != ',') goto syntax; q++;
367   if (unum(&q, &rp, 1, 65535)) goto syntax;
368   skipws(&q); if (*q != ':') goto syntax; q++;
369   if (lp != px->c->q.u.nat.port || rp != px->c->q.s[R].port) goto syntax;
370
371   /* Find out what kind of reply this is. */
372   if (idtoken(&q, buf, sizeof(buf))) goto syntax;
373   skipws(&q); if (*q != ':') goto syntax; q++;
374
375   if (strcmp(buf, "ERROR") == 0) {
376
377     /* Report the error without interpreting it.  It might be meaningful to
378      * the client.
379      */
380     skipws(&q);
381     logmsg(&px->c->q, LOG_ERR, "proxy error from %s: %s", px->nat, q);
382     reply(px->c, "ERROR", q, 0);
383
384   } else if (strcmp(buf, "USERID") == 0) {
385
386     /* Parse out the operating system and user name, and pass them on. */
387     if (idtoken(&q, buf, sizeof(buf))) goto syntax;
388     skipws(&q); if (*q != ':') goto syntax; q++;
389     skipws(&q);
390     logmsg(&px->c->q, LOG_ERR, "user `%s'; proxy = %s, os = %s",
391            q, px->nat, buf);
392     reply(px->c, "USERID", buf, q);
393
394   } else
395     goto syntax;
396   goto done;
397
398 syntax:
399   /* We didn't understand the message from the client. */
400   logmsg(&px->c->q, LOG_ERR, "failed to parse response from %s", px->nat);
401   reply_error(px->c, E_UNKNOWN);
402 done:
403   /* All finished, no matter what. */
404   cancel_proxy(px);
405 }
406
407 /* Notification that we have written the query to the server.  Await a
408  * response if successful.
409  */
410 static void done_proxy_write(int err, void *p)
411 {
412   struct proxy *px = p;
413
414   if (err) {
415     logmsg(&px->c->q, LOG_ERR, "failed to proxy query to %s: %s",
416            px->nat, strerror(errno));
417     reply_error(px->c, E_UNKNOWN);
418     cancel_proxy(px);
419     return;
420   }
421   selbuf_enable(&px->b);
422 }
423
424 /* Notification that the connection to the server is either established or
425  * failed.  In the former case, queue the right query.
426  */
427 static void proxy_connected(int fd, void *p)
428 {
429   struct proxy *px = p;
430   char buf[16];
431   int n;
432
433   /* If the connection failed then report the problem and give up. */
434   if (fd < 0) {
435     logmsg(&px->c->q, LOG_ERR,
436            "failed to make %s proxy connection to %s: %s",
437            px->c->l->ao->name, px->nat, strerror(errno));
438     reply_error(px->c, E_UNKNOWN);
439     cancel_proxy(px);
440     return;
441   }
442
443   /* We're now ready to go, so set things up. */
444   px->fd = fd;
445   selbuf_init(&px->b, &sel, fd, proxy_line, px);
446   selbuf_setsize(&px->b, 1024);
447   selbuf_disable(&px->b);
448   init_writebuf(&px->wb, fd, done_proxy_write, px);
449
450   /* Write the query.  This buffer is large enough because we've already
451    * range-checked the remote the port number and the local one came from the
452    * kernel, which we trust not to do anything stupid.
453    */
454   n = sprintf(buf, "%u,%u\r\n", px->c->q.u.nat.port, px->c->q.s[R].port);
455   queue_write(&px->wb, buf, n);
456 }
457
458 /* Proxy the query through to a client machine for which we're providing NAT
459  * disservice.
460  */
461 static void proxy_query(struct client *c)
462 {
463   struct socket s;
464   struct sockaddr_storage ss;
465   size_t ssz;
466   struct proxy *px;
467   int fd;
468
469   /* Allocate the context structure for the NAT. */
470   px = xmalloc(sizeof(*px));
471
472   /* We'll use the client host's address in lots of log messages, so we may
473    * as well format it once and use it over and over.
474    */
475   inet_ntop(c->q.ao->af, &c->q.u.nat.addr, px->nat, sizeof(px->nat));
476
477   /* Create the socket for the connection. */
478   if ((fd = socket(c->q.ao->af, SOCK_STREAM, 0)) < 0) {
479     logmsg(&c->q, LOG_ERR, "failed to make %s socket for proxy: %s",
480            c->l->ao->name, strerror(errno));
481     goto err_0;
482   }
483   if (fix_up_socket(fd, "proxy")) goto err_1;
484
485   /* Set up the connection to the client host.  The connection interface is a
486    * bit broken: if the connection completes immediately, then the callback
487    * function is called synchronously, and that might decide to shut
488    * everything down.  So we must have fully initialized our context before
489    * calling `conn_init', and mustn't touch it again afterwards -- since the
490    * block may have been freed.
491    */
492   s = c->q.u.nat;
493   s.port = 113;
494   c->l->ao->socket_to_sockaddr(&s, &ss, &ssz);
495   selbuf_disable(&c->b);
496   c->px = px; px->c = c;
497   px->fd = -1;
498   if (conn_init(&px->cn, &sel, fd, (struct sockaddr *)&ss, ssz,
499                 proxy_connected, px)) {
500     logmsg(&c->q, LOG_ERR, "failed to make %s proxy connection to %s: %s",
501            c->l->ao->name, px->nat, strerror(errno));
502     goto err_2;
503   }
504
505   /* All ready to go. */
506   return;
507
508   /* Tidy up after various kinds of failures. */
509 err_2:
510   selbuf_enable(&c->b);
511 err_1:
512   close(px->fd);
513 err_0:
514   xfree(px);
515   reply_error(c, E_UNKNOWN);
516 }
517
518 /*----- Client connection functions ---------------------------------------*/
519
520 /* Disconnect a client, freeing up any associated resources. */
521 static void disconnect_client(struct client *c)
522 {
523   close(c->fd);
524   selbuf_destroy(&c->b);
525   sel_rmtimer(&c->t);
526   free_writebuf(&c->wb);
527   if (c->px) cancel_proxy(c->px);
528   xfree(c);
529 }
530
531 /* Time out a client because it's been idle for too long. */
532 static void timeout_client(struct timeval *tv, void *p)
533 {
534   struct client *c = p;
535   logmsg(&c->q, LOG_NOTICE, "timing out idle or stuck client");
536   sel_addtimer(&sel, &c->t, tv, timeout_client, 0);
537   disconnect_client(c);
538 }
539
540 /* Reset the client idle timer, as a result of activity.  Set EXISTP if
541  * there is an existing timer which needs to be removed.
542  */
543 static void reset_client_timer(struct client *c, int existp)
544 {
545   struct timeval tv;
546
547   gettimeofday(&tv, 0);
548   tv.tv_sec += 30;
549   if (existp) sel_rmtimer(&c->t);
550   sel_addtimer(&sel, &c->t, &tv, timeout_client, c);
551 }
552
553 /* Write a pseudorandom token into the buffer at P, which must have space for
554  * at least TOKENSZ bytes.
555  */
556 #define TOKENRANDSZ 8
557 #define TOKENSZ ((4*TOKENRANDSZ + 5)/3)
558 static void user_token(char *p)
559 {
560   unsigned a = 0;
561   unsigned b = 0;
562   int i;
563   static const char tokmap[64] =
564     "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.-";
565
566   /* If there's not enough pseudorandom stuff lying around, then read more
567    * from the kernel.
568    */
569   if (tokenptr + TOKENRANDSZ >= sizeof(tokenbuf)) {
570     if (read(randfd, tokenbuf, sizeof(tokenbuf)) < sizeof(tokenbuf))
571       die(1, "unexpected short read or error from `/dev/urandom'");
572     tokenptr = 0;
573   }
574
575   /* Now encode the bytes using a slightly tweaked base-64 encoding.  Read
576    * bytes into the accumulator and write out characters while there's
577    * enough material.
578    */
579   for (i = 0; i < TOKENRANDSZ; i++) {
580     a = (a << 8) | tokenbuf[tokenptr++]; b += 8;
581     while (b >= 6) {
582       b -= 6;
583       *p++ = tokmap[(a >> b) & 0x3f];
584     }
585   }
586
587   /* If there's anything left in the accumulator then flush it out. */
588   if (b)
589     *p++ = tokmap[(a << (6 - b)) & 0x3f];
590
591   /* Null-terminate the token. */
592   *p++ = 0;
593 }
594
595 /* Notification that a line has been received from the client.  Parse it,
596  * find out about the connection it's referring to, apply the relevant
597  * policy rules, and produce a response.  This is where almost everything
598  * interesting happens.
599  */
600 static void client_line(char *line, size_t len, void *p)
601 {
602   struct client *c = p;
603   const char *q;
604   struct passwd *pw = 0;
605   const struct policy *pol;
606   dstr d = DSTR_INIT;
607   struct policy upol = POLICY_INIT(A_LIMIT);
608   struct policy_file pf;
609   char buf[16];
610   int i;
611
612   /* If the connection has closed, then tidy stuff away. */
613   c->q.s[L].port = c->q.s[R].port = 0;
614   if (!line) {
615     disconnect_client(c);
616     return;
617   }
618
619   /* Client activity, so update the timer. */
620   reset_client_timer(c, 1);
621
622   /* See if the policy file has changed since we last looked.  If so, try to
623    * read the new version.
624    */
625   if (fwatch_update(&polfw, "yaid.policy")) {
626     logmsg(0, LOG_INFO, "reload master policy file `%s'", "yaid.policy");
627     load_policy_file("yaid.policy", &policy);
628   }
629
630   /* Read the local and remote port numbers into the query structure. */
631   q = line;
632   if (unum(&q, &c->q.s[L].port, 1, 65535)) goto bad;
633   skipws(&q); if (*q != ',') goto bad; q++;
634   if (unum(&q, &c->q.s[R].port, 1, 65535)) goto bad;
635   skipws(&q); if (*q) goto bad;
636
637   /* Identify the connection.  Act on the result. */
638   identify(&c->q);
639   switch (c->q.resp) {
640
641     case R_UID:
642       /* We found a user.  Track down the user's password entry, because
643        * we'll want that later.  Most of the processing for this case is
644        * below.
645        */
646       if ((pw = getpwuid(c->q.u.uid)) == 0) {
647         logmsg(&c->q, LOG_ERR, "no passwd entry for user %d", c->q.u.uid);
648         reply_error(c, E_NOUSER);
649         return;
650       }
651       break;
652
653     case R_NAT:
654       /* We've acted as a NAT for this connection.  Proxy the query through
655        * to the actal client host.
656        */
657       proxy_query(c);
658       return;
659
660     case R_ERROR:
661       /* We failed to identify the connection for some reason.  We should
662        * already have logged an error, so there's not much to do here.
663        */
664       reply_error(c, c->q.u.error);
665       return;
666
667     default:
668       /* Something happened that we don't understand. */
669       abort();
670   }
671
672   /* Search the table of policy rules to find a match. */
673   for (i = 0; i < DA_LEN(&policy); i++) {
674     pol = &DA(&policy)[i];
675     if (!match_policy(pol, &c->q)) continue;
676
677     /* If this is something simple, then apply the resulting policy rule. */
678     if (pol->act.act != A_USER) goto match;
679
680     /* The global policy has decided to let the user have a say, so we must
681      * parse the user file.
682      */
683     DRESET(&d);
684     dstr_putf(&d, "%s/.yaid.policy", pw->pw_dir);
685     if (open_policy_file(&pf, d.buf, "user policy file", &c->q))
686       continue;
687     while (!read_policy_file(&pf)) {
688
689       /* Give up after 100 lines.  If the user's policy is that complicated,
690        * something's gone very wrong.  Or there's too much commentary or
691        * something.
692        */
693       if (pf.lno > 100) {
694         logmsg(&c->q, LOG_ERR, "%s:%d: user policy file too long",
695                pf.name, pf.lno);
696         break;
697       }
698
699       /* If this isn't a match, go around for the next rule. */
700       if (!match_policy(&pf.p, &c->q)) continue;
701
702       /* Check that the user is allowed to request this action.  If not, see
703        * if there's a more acceptable action later on.
704        */
705       if (!(pol->act.u.user & (1 << pf.p.act.act))) {
706         logmsg(&c->q, LOG_ERR,
707                "%s:%d: user action forbidden by global policy",
708                pf.name, pf.lno);
709         continue;
710       }
711
712       /* We've found a match, so grab it, close the file, and say we're
713        * done.
714        */
715       upol = pf.p; pol = &upol;
716       init_policy(&pf.p);
717       close_policy_file(&pf);
718       DDESTROY(&d);
719       goto match;
720     }
721     close_policy_file(&pf);
722     DDESTROY(&d);
723   }
724
725   /* No match: apply the built-in default policy. */
726   pol = &default_policy;
727
728 match:
729   switch (pol->act.act) {
730
731     case A_NAME:
732       /* Report the actual user's name. */
733       logmsg(&c->q, LOG_INFO, "user `%s' (%d)", pw->pw_name, c->q.u.uid);
734       reply(c, "USERID", "UNIX", pw->pw_name);
735       break;
736
737     case A_TOKEN:
738       /* Report an arbitrary token which we can look up in our log file. */
739       user_token(buf);
740       logmsg(&c->q, LOG_INFO, "user `%s' (%d); token = %s",
741              pw->pw_name, c->q.u.uid, buf);
742       reply(c, "USERID", "OTHER", buf);
743       break;
744
745     case A_DENY:
746       /* Deny that there's anyone there at all. */
747       logmsg(&c->q, LOG_INFO, "user `%s' (%d); denying",
748              pw->pw_name, c->q.u.uid);
749       break;
750
751     case A_HIDE:
752       /* Report the user as being hidden. */
753       logmsg(&c->q, LOG_INFO, "user `%s' (%d); hiding",
754              pw->pw_name, c->q.u.uid);
755       reply_error(c, E_HIDDEN);
756       break;
757
758     case A_LIE:
759       /* Tell an egregious lie about who the user is. */
760       logmsg(&c->q, LOG_INFO, "user `%s' (%d); lie = `%s'",
761              pw->pw_name, c->q.u.uid, pol->act.u.lie);
762       reply(c, "USERID", "UNIX", pol->act.u.lie);
763       break;
764
765     default:
766       /* Something has gone very wrong. */
767       abort();
768   }
769
770   /* All done. */
771   free_policy(&upol);
772   return;
773
774 bad:
775   logmsg(&c->q, LOG_ERR, "failed to parse query from client");
776   disconnect_client(c);
777 }
778
779 /* Notification that a new client has connected.  Prepare to read a query. */
780 static void accept_client(int fd, unsigned mode, void *p)
781 {
782   struct listen *l = p;
783   struct client *c;
784   struct sockaddr_storage ssr, ssl;
785   size_t ssz = sizeof(ssr);
786   int sk;
787
788   /* Accept the new connection. */
789   if ((sk = accept(fd, (struct sockaddr *)&ssr, &ssz)) < 0) {
790     if (errno != EAGAIN && errno == EWOULDBLOCK) {
791       logmsg(0, LOG_ERR, "failed to accept incoming %s connection: %s",
792              l->ao->name, strerror(errno));
793     }
794     return;
795   }
796   if (fix_up_socket(sk, "incoming client")) { close(sk); return; }
797
798   /* Build a client block and fill it in. */
799   c = xmalloc(sizeof(*c));
800   c->l = l;
801   c->q.ao = l->ao;
802
803   /* Collect the local and remote addresses. */
804   l->ao->sockaddr_to_addr(&ssr, &c->q.s[R].addr);
805   ssz = sizeof(ssl);
806   if (getsockname(sk, (struct sockaddr *)&ssl, &ssz)) {
807     logmsg(0, LOG_ERR,
808            "failed to read local address for incoming %s connection: %s",
809            l->ao->name, strerror(errno));
810     close(sk);
811     xfree(c);
812     return;
813   }
814   l->ao->sockaddr_to_addr(&ssl, &c->q.s[L].addr);
815   c->q.s[L].port = c->q.s[R].port = 0;
816
817   /* Set stuff up for reading the query and sending responses. */
818   selbuf_init(&c->b, &sel, sk, client_line, c);
819   selbuf_setsize(&c->b, 1024);
820   reset_client_timer(c, 0);
821   c->fd = sk;
822   c->px = 0;
823   init_writebuf(&c->wb, sk, done_client_write, c);
824 }
825
826 /*----- Main code ---------------------------------------------------------*/
827
828 /* Set up a listening socket for the address family described by AO,
829  * listening on PORT.
830  */
831 static int make_listening_socket(const struct addrops *ao, int port)
832 {
833   int fd;
834   int yes = 1;
835   struct socket s;
836   struct sockaddr_storage ss;
837   struct listen *l;
838   size_t ssz;
839
840   /* Make the socket. */
841   if ((fd = socket(ao->af, SOCK_STREAM, 0)) < 0) {
842     if (errno == EAFNOSUPPORT) return (-1);
843     die(1, "failed to create %s listening socket: %s",
844         ao->name, strerror(errno));
845   }
846
847   /* Build the appropriate local address. */
848   s.addr = *ao->any;
849   s.port = port;
850   ao->socket_to_sockaddr(&s, &ss, &ssz);
851
852   /* Perform any initialization specific to the address type. */
853   if (ao->init_listen_socket(fd)) {
854     die(1, "failed to initialize %s listening socket: %s",
855         ao->name, strerror(errno));
856   }
857
858   /* Bind to the address. */
859   setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
860   if (bind(fd, (struct sockaddr *)&ss, ssz)) {
861     die(1, "failed to bind %s listening socket: %s",
862         ao->name, strerror(errno));
863   }
864
865   /* Avoid unpleasant race conditions. */
866   if (fdflags(fd, O_NONBLOCK, O_NONBLOCK, 0, 0)) {
867     die(1, "failed to set %s listening socket nonblocking: %s",
868         ao->name, strerror(errno));
869   }
870
871   /* Prepare to listen. */
872   if (listen(fd, 5))
873     die(1, "failed to listen for %s: %s", ao->name, strerror(errno));
874
875   /* Make a record of all of this. */
876   l = xmalloc(sizeof(*l));
877   l->ao = ao;
878   sel_initfile(&sel, &l->f, fd, SEL_READ, accept_client, l);
879   sel_addfile(&l->f);
880
881   /* Done. */
882   return (0);
883 }
884
885 int main(int argc, char *argv[])
886 {
887   int port = 113;
888   const struct addrops *ao;
889   int any = 0;
890
891   ego(argv[0]);
892
893   fwatch_init(&polfw, "yaid.policy");
894   init_sys();
895   if (load_policy_file("yaid.policy", &policy))
896     exit(1);
897   { int i;
898     for (i = 0; i < DA_LEN(&policy); i++)
899       print_policy(&DA(&policy)[i]);
900   }
901
902   if ((randfd = open("/dev/urandom", O_RDONLY)) < 0) {
903     die(1, "failed to open `/dev/urandom' for reading: %s",
904         strerror(errno));
905   }
906
907   sel_init(&sel);
908   for (ao = addroptab; ao->name; ao++)
909     if (!make_listening_socket(ao, port)) any = 1;
910   if (!any)
911     die(1, "no IP protocols supported");
912
913   for (;;)
914     if (sel_select(&sel)) die(1, "select failed: %s", strerror(errno));
915
916   return (0);
917 }
918
919 /*----- That's all, folks -------------------------------------------------*/