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