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