Makefile.am: Tweak `silent-rules' machinery.
[yaid] / yaid.c
diff --git a/yaid.c b/yaid.c
index f70c2a3..d0d917a 100644 (file)
--- a/yaid.c
+++ b/yaid.c
 
 /*----- Data structures ---------------------------------------------------*/
 
-struct listen {
-  const struct addrops *ao;
-  sel_file f;
-};
-
+/* A write buffer is the gadget which keeps track of our output and writes
+ * portions of it out as and when connections are ready for it.
+ */
 #define WRBUFSZ 1024
 struct writebuf {
-  size_t o, n;
-  sel_file wr;
-  void (*func)(int, void *);
-  void *p;
-  unsigned char buf[WRBUFSZ];
+  size_t o;                            /* Offset of remaining data */
+  size_t n;                            /* Length of remaining data */
+  sel_file wr;                         /* Write selector */
+  void (*func)(int /*err*/, void *);   /* Function to call on completion */
+  void *p;                             /* Context for `func' */
+  unsigned char buf[WRBUFSZ];          /* Output buffer */
 };
 
-struct proxy {
-  struct client *c;
-  int fd;
-  conn cn;
-  selbuf b;
-  struct writebuf wb;
-  char nat[ADDRLEN];
+/* Structure for a listening socket.  There's one of these for each address
+ * family we're looking after.
+ */
+struct listen {
+  const struct addrops *ao;            /* Address family operations */
+  sel_file f;                          /* Watch for incoming connections */
 };
 
+/* The main structure for a client. */
 struct client {
-  selbuf b;
-  int fd;
-  struct query q;
-  struct listen *l;
-  struct writebuf wb;
-  struct proxy *px;
+  int fd;                              /* The connection to the client */
+  selbuf b;                            /* Accumulate lines of input */
+  union addr raddr;                    /* Remote address */
+  struct query q;                      /* The clients query and our reply */
+  struct sel_timer t;                  /* Timeout for idle or doomed conn */
+  struct listen *l;                    /* Back to the listener (and ops) */
+  struct writebuf wb;                  /* Write buffer for our reply */
+  struct proxy *px;                    /* Proxy if conn goes via NAT */
+  struct client *next;                 /* Next in a chain of clients */
+};
+
+/* A proxy connection. */
+struct proxy {
+  int fd;                              /* Connection; -1 if in progress */
+  struct client *c;                    /* Back to the client */
+  conn cn;                             /* Nonblocking connection */
+  selbuf b;                            /* Accumulate the response line */
+  struct writebuf wb;                  /* Write buffer for query */
+  char nat[ADDRLEN];                   /* Server address, as text */
+  struct proxy *next;                  /* Next in a chain of proxies */
 };
 
 /*----- Static variables --------------------------------------------------*/
 
-static sel_state sel;
+static sel_state sel;                  /* I/O multiplexer state */
 
-static policy_v policy = DA_INIT;
-static fwatch polfw;
+static const char *pidfile = 0;                /* Where to write daemon's pid */
 
-static unsigned char tokenbuf[4096];
-static size_t tokenptr = sizeof(tokenbuf);
-static int randfd;
+static const char *policyfile = POLICYFILE; /* Filename for global policy */
+static const struct policy default_policy = POLICY_INIT(A_NAME);
+static policy_v policy = DA_INIT;      /* Vector of global policy rules */
+static fwatch polfw;                   /* Watch policy file for changes */
 
-/*----- Main code ---------------------------------------------------------*/
+static unsigned char tokenbuf[4096];   /* Random-ish data for tokens */
+static size_t tokenptr = sizeof(tokenbuf); /* Current read position */
 
-void logmsg(const struct query *q, int prio, const char *msg, ...)
+static struct client *dead_clients = 0;        /* List of defunct clients */
+static struct proxy *dead_proxies = 0; /* List of defunct proxies */
+
+static unsigned flags = 0;             /* Various interesting flags */
+#define F_SYSLOG 1u                    /*   Use syslog for logging */
+#define F_RUNNING 2u                   /*   Running properly now */
+
+/*----- Ident protocol parsing --------------------------------------------*/
+
+/* Advance *PP over whitespace characters. */
+static void skipws(const char **pp)
+  { while (isspace((unsigned char )**pp)) (*pp)++; }
+
+/* Copy a token of no more than N bytes starting at *PP into Q, advancing *PP
+ * over it.
+ */
+static int idtoken(const char **pp, char *q, size_t n)
 {
-  va_list ap;
-  dstr d = DSTR_INIT;
+  const char *p = *pp;
 
-  va_start(ap, msg);
-  if (q) {
-    dputsock(&d, q->ao, &q->s[L]);
-    dstr_puts(&d, " <-> ");
-    dputsock(&d, q->ao, &q->s[R]);
-    dstr_puts(&d, ": ");
+  skipws(&p);
+  n--;
+  for (;;) {
+    if (*p == ':' || *p <= 32 || *p >= 127) break;
+    if (!n) return (-1);
+    *q++ = *p++;
+    n--;
   }
-  dstr_vputf(&d, msg, &ap);
-  va_end(ap);
-  fprintf(stderr, "yaid: %s\n", d.buf);
-  dstr_destroy(&d);
+  *q++ = 0;
+  *pp = p;
+  return (0);
 }
 
+/* Read an unsigned decimal number from *PP, and store it in *II.  Check that
+ * it's between MIN and MAX, and advance *PP over it.  Return zero for
+ * success, or nonzero if something goes wrong.
+ */
+static int unum(const char **pp, unsigned *ii, unsigned min, unsigned max)
+{
+  char *q;
+  unsigned long i;
+  int e;
+
+  skipws(pp);
+  if (!isdigit((unsigned char)**pp)) return (-1);
+  e = errno; errno = 0;
+  i = strtoul(*pp, &q, 10);
+  if (errno) return (-1);
+  *pp = q;
+  errno = e;
+  if (i < min || i > max) return (-1);
+  *ii = i;
+  return (0);
+}
+
+/*----- Asynchronous writing ----------------------------------------------*/
+
+/* Callback for actually writing stuff from a `writebuf'. */
 static void write_out(int fd, unsigned mode, void *p)
 {
   ssize_t n;
   struct writebuf *wb = p;
 
+  /* Try to write something. */
   if ((n = write(fd, wb->buf + wb->o, wb->n)) < 0) {
     if (errno == EAGAIN || errno == EWOULDBLOCK) return;
     wb->n = 0;
@@ -106,6 +161,8 @@ static void write_out(int fd, unsigned mode, void *p)
   }
   wb->o += n;
   wb->n -= n;
+
+  /* If there's nothing left then restore the buffer to its empty state. */
   if (!wb->n) {
     wb->o = 0;
     sel_rmfile(&wb->wr);
@@ -113,26 +170,47 @@ static void write_out(int fd, unsigned mode, void *p)
   }
 }
 
+/* Queue N bytes starting at P to be written. */
 static int queue_write(struct writebuf *wb, const void *p, size_t n)
 {
+  /* Maybe there's nothing to actually do. */
   if (!n) return (0);
+
+  /* Make sure it'll fit. */
   if (wb->n - wb->o + n > WRBUFSZ) return (-1);
+
+  /* If there's anything there already, then make sure it's at the start of
+   * the available space.
+   */
   if (wb->o) {
     memmove(wb->buf, wb->buf + wb->o, wb->n);
     wb->o = 0;
   }
-  memcpy(wb->buf + wb->n, p, n);
+
+  /* If there's nothing currently there, then we're not requesting write
+   * notifications, so set that up, and force an initial wake-up.
+   */
   if (!wb->n) {
     sel_addfile(&wb->wr);
     sel_force(&wb->wr);
   }
+
+  /* Copy the new material over. */
+  memcpy(wb->buf + wb->n, p, n);
   wb->n += n;
+
+  /* Done. */
   return (0);
 }
 
+/* Release resources allocated to WB. */
 static void free_writebuf(struct writebuf *wb)
   { if (wb->n) sel_rmfile(&wb->wr); }
 
+/* Initialize a writebuf in *WB, writing to file descriptor FD.  On
+ * completion, call FUNC, passing it P and an error indicator: either 0 for
+ * success or an `errno' value on failure.
+ */
 static void init_writebuf(struct writebuf *wb,
                          int fd, void (*func)(int, void *), void *p)
 {
@@ -142,29 +220,91 @@ static void init_writebuf(struct writebuf *wb,
   wb->n = wb->o = 0;
 }
 
-static void cancel_proxy(struct proxy *px)
+/*----- General utilities -------------------------------------------------*/
+
+static void vlogmsg(const struct query *q, int prio,
+                   const char *msg, va_list *ap)
 {
-  if (px->fd == -1)
-    conn_kill(&px->cn);
+  dstr d = DSTR_INIT;
+  time_t t;
+  struct tm *tm;
+  char buf[64];
+
+  if (q) {
+    dputsock(&d, q->ao, &q->s[L]);
+    dstr_puts(&d, " <-> ");
+    dputsock(&d, q->ao, &q->s[R]);
+    dstr_puts(&d, ": ");
+  }
+  dstr_vputf(&d, msg, ap);
+
+  if (!(flags & F_RUNNING))
+    moan("%s", d.buf);
+  else if (flags & F_SYSLOG)
+    syslog(prio, "%s", d.buf);
   else {
-    close(px->fd);
-    selbuf_destroy(&px->b);
-    free_writebuf(&px->wb);
+    t = time(0);
+    tm = localtime(&t);
+    strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S %z", tm);
+    fprintf(stderr, "%s %s: %s\n", buf, QUIS, d.buf);
   }
-  selbuf_enable(&px->c->b);
-  px->c->px = 0;
-  xfree(px);
+
+  dstr_destroy(&d);
 }
 
-static void disconnect_client(struct client *c)
+/* Format and log MSG somewhere sensible, at the syslog(3) priority PRIO.
+ * Prefix it with a description of the query Q, if non-null.
+ */
+void logmsg(const struct query *q, int prio, const char *msg, ...)
 {
-  close(c->fd);
-  selbuf_destroy(&c->b);
-  free_writebuf(&c->wb);
-  if (c->px) cancel_proxy(c->px);
-  xfree(c);
+  va_list ap;
+
+  va_start(ap, msg);
+  vlogmsg(q, prio, msg, &ap);
+  va_end(ap);
+}
+
+/* Format and report MSG as a fatal error, and exit. */
+void fatal(const char *msg, ...)
+{
+  va_list ap;
+
+  va_start(ap, msg);
+  vlogmsg(0, LOG_CRIT, msg, &ap);
+  va_end(ap);
+  exit(1);
 }
 
+/* Fix up a socket FD so that it won't bite us.  Returns zero on success, or
+ * nonzero on error.
+ */
+static int fix_up_socket(int fd, const char *what)
+{
+  int yes = 1;
+
+  if (fdflags(fd, O_NONBLOCK, O_NONBLOCK, 0, 0)) {
+    logmsg(0, LOG_ERR, "failed to set %s connection nonblocking: %s",
+          what, strerror(errno));
+    return (-1);
+  }
+
+  if (setsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &yes, sizeof(yes))) {
+    logmsg(0, LOG_ERR,
+          "failed to disable `out-of-band' data on %s connection: %s",
+          what, strerror(errno));
+    return (-1);
+  }
+
+  return (0);
+}
+
+/*----- Client output functions -------------------------------------------*/
+
+static void disconnect_client(struct client *c);
+
+/* Notification that output has been written.  If successful, re-enable the
+ * input buffer and prepare for another query.
+ */
 static void done_client_write(int err, void *p)
 {
   struct client *c = p;
@@ -177,7 +317,11 @@ static void done_client_write(int err, void *p)
   }
 }
 
-static void write_to_client(struct client *c, const char *fmt, ...)
+/* Format the message FMT and queue it to be sent to the client.  Client
+ * input will be disabled until the write completes.
+ */
+static void PRINTF_LIKE(2, 3)
+  write_to_client(struct client *c, const char *fmt, ...)
 {
   va_list ap;
   char buf[WRBUFSZ];
@@ -202,62 +346,72 @@ static void write_to_client(struct client *c, const char *fmt, ...)
   }
 }
 
-static void reply(struct client *c, const char *ty, const char *msg)
+/* Format a reply to the client, with the form LPORT:RPORT:TY:TOK0[:TOK1].
+ * Typically, TY will be `ERROR' or `USERID'.  In the former case, TOK0 will
+ * be the error token and TOK1 will be null; in the latter case, TOK0 will be
+ * the operating system and TOK1 the user name.
+ */
+static void reply(struct client *c, const char *ty,
+                 const char *tok0, const char *tok1)
 {
-  write_to_client(c, "%u,%u:%s:%s\r\n",
-                 c->q.s[L].port, c->q.s[R].port, ty, msg);
+  write_to_client(c, "%u,%u:%s:%s%s%s\r\n",
+                 c->q.s[L].port, c->q.s[R].port, ty,
+                 tok0, tok1 ? ":" : "", tok1 ? tok1 : "");
 }
 
+/* Mapping from error codes to their protocol tokens. */
 const char *const errtok[] = {
 #define DEFTOK(err, tok) tok,
   ERROR(DEFTOK)
 #undef DEFTOK
 };
 
+/* Report an error with code ERR to the client. */
 static void reply_error(struct client *c, unsigned err)
 {
   assert(err < E_LIMIT);
-  reply(c, "ERROR", errtok[err]);
+  reply(c, "ERROR", errtok[err], 0);
 }
 
-static void skipws(const char **pp)
-  { while (isspace((unsigned char )**pp)) (*pp)++; }
+/*----- NAT proxy functions -----------------------------------------------*/
 
-static int idtoken(const char **pp, char *q, size_t n)
+/* Cancel the proxy operation PX, closing the connection and releasing
+ * resources.  This is used for both normal and unexpected closures.
+ */
+static void cancel_proxy(struct proxy *px)
 {
-  const char *p = *pp;
-
-  skipws(&p);
-  n--;
-  for (;;) {
-    if (*p == ':' || *p <= 32 || *p >= 127) break;
-    if (!n) return (-1);
-    *q++ = *p++;
-    n--;
+  if (px->fd == -1)
+    conn_kill(&px->cn);
+  else {
+    close(px->fd);
+    selbuf_disable(&px->b);
   }
-  *q++ = 0;
-  *pp = p;
-  return (0);
+  px->c->px = 0;
+  selbuf_enable(&px->c->b);
+  px->next = dead_proxies;
+  dead_proxies = px;
 }
 
-static int unum(const char **pp, unsigned *ii, unsigned min, unsigned max)
+/* Delayed destruction of unsafe parts of proxies. */
+static void reap_dead_proxies(void)
 {
-  char *q;
-  unsigned long i;
-  int e;
+  struct proxy *px, *pp;
 
-  skipws(pp);
-  if (!isdigit((unsigned char)**pp)) return (-1);
-  e = errno; errno = 0;
-  i = strtoul(*pp, &q, 10);
-  if (errno) return (-1);
-  *pp = q;
-  errno = e;
-  if (i < min || i > max) return (-1);
-  *ii = i;
-  return (0);
+  for (px = dead_proxies; px; px = pp) {
+    pp = px->next;
+    if (px->fd != -1) {
+      selbuf_destroy(&px->b);
+      free_writebuf(&px->wb);
+    }
+    xfree(px);
+  }
+  dead_proxies = 0;
 }
 
+/* Notification that a line (presumably a reply) has been received from the
+ * server.  We should check it, log it, and propagate the answer back.
+ * Whatever happens, this proxy operation is now complete.
+ */
 static void proxy_line(char *line, size_t sz, void *p)
 {
   struct proxy *px = p;
@@ -265,39 +419,55 @@ static void proxy_line(char *line, size_t sz, void *p)
   const char *q = line;
   unsigned lp, rp;
 
+  /* Trim trailing space. */
   while (sz && isspace((unsigned char)line[sz - 1])) sz--;
-  printf("received proxy line from %s: %s\n", px->nat, line);
 
+  /* Parse the port numbers.  These should match the request. */
   if (unum(&q, &lp, 1, 65535)) goto syntax;
   skipws(&q); if (*q != ',') goto syntax; q++;
   if (unum(&q, &rp, 1, 65535)) goto syntax;
   skipws(&q); if (*q != ':') goto syntax; q++;
   if (lp != px->c->q.u.nat.port || rp != px->c->q.s[R].port) goto syntax;
+
+  /* Find out what kind of reply this is. */
   if (idtoken(&q, buf, sizeof(buf))) goto syntax;
   skipws(&q); if (*q != ':') goto syntax; q++;
+
   if (strcmp(buf, "ERROR") == 0) {
+
+    /* Report the error without interpreting it.  It might be meaningful to
+     * the client.
+     */
     skipws(&q);
     logmsg(&px->c->q, LOG_ERR, "proxy error from %s: %s", px->nat, q);
-    reply(px->c, "ERROR", q);
+    reply(px->c, "ERROR", q, 0);
+
   } else if (strcmp(buf, "USERID") == 0) {
+
+    /* Parse out the operating system and user name, and pass them on. */
     if (idtoken(&q, buf, sizeof(buf))) goto syntax;
     skipws(&q); if (*q != ':') goto syntax; q++;
     skipws(&q);
     logmsg(&px->c->q, LOG_ERR, "user `%s'; proxy = %s, os = %s",
           q, px->nat, buf);
-    write_to_client(px->c, "%u,%u:USERID:%s:%s\r\n",
-                   px->c->q.s[L].port, px->c->q.s[R].port, buf, q);
+    reply(px->c, "USERID", buf, q);
+
   } else
     goto syntax;
   goto done;
 
 syntax:
+  /* We didn't understand the message from the client. */
   logmsg(&px->c->q, LOG_ERR, "failed to parse response from %s", px->nat);
   reply_error(px->c, E_UNKNOWN);
 done:
+  /* All finished, no matter what. */
   cancel_proxy(px);
 }
 
+/* Notification that we have written the query to the server.  Await a
+ * response if successful.
+ */
 static void done_proxy_write(int err, void *p)
 {
   struct proxy *px = p;
@@ -312,12 +482,16 @@ static void done_proxy_write(int err, void *p)
   selbuf_enable(&px->b);
 }
 
+/* Notification that the connection to the server is either established or
+ * failed.  In the former case, queue the right query.
+ */
 static void proxy_connected(int fd, void *p)
 {
   struct proxy *px = p;
   char buf[16];
   int n;
 
+  /* If the connection failed then report the problem and give up. */
   if (fd < 0) {
     logmsg(&px->c->q, LOG_ERR,
           "failed to make %s proxy connection to %s: %s",
@@ -327,16 +501,24 @@ static void proxy_connected(int fd, void *p)
     return;
   }
 
+  /* We're now ready to go, so set things up. */
   px->fd = fd;
   selbuf_init(&px->b, &sel, fd, proxy_line, px);
   selbuf_setsize(&px->b, 1024);
   selbuf_disable(&px->b);
   init_writebuf(&px->wb, fd, done_proxy_write, px);
 
+  /* Write the query.  This buffer is large enough because we've already
+   * range-checked the remote the port number and the local one came from the
+   * kernel, which we trust not to do anything stupid.
+   */
   n = sprintf(buf, "%u,%u\r\n", px->c->q.u.nat.port, px->c->q.s[R].port);
   queue_write(&px->wb, buf, n);
 }
 
+/* Proxy the query through to a client machine for which we're providing NAT
+ * disservice.
+ */
 static void proxy_query(struct client *c)
 {
   struct socket s;
@@ -345,25 +527,35 @@ static void proxy_query(struct client *c)
   struct proxy *px;
   int fd;
 
+  /* Allocate the context structure for the NAT. */
   px = xmalloc(sizeof(*px));
+
+  /* We'll use the client host's address in lots of log messages, so we may
+   * as well format it once and use it over and over.
+   */
   inet_ntop(c->q.ao->af, &c->q.u.nat.addr, px->nat, sizeof(px->nat));
 
+  /* Create the socket for the connection. */
   if ((fd = socket(c->q.ao->af, SOCK_STREAM, 0)) < 0) {
     logmsg(&c->q, LOG_ERR, "failed to make %s socket for proxy: %s",
           c->l->ao->name, strerror(errno));
     goto err_0;
   }
-
-  if (fdflags(fd, O_NONBLOCK, O_NONBLOCK, 0, 0)) {
-    logmsg(&c->q, LOG_ERR, "failed to set %s proxy socket nonblocking: %s",
-          c->l->ao->name, strerror(errno));
-    goto err_1;
-  }
-
+  if (fix_up_socket(fd, "proxy")) goto err_1;
+
+  /* Set up the connection to the client host.  The connection interface is a
+   * bit broken: if the connection completes immediately, then the callback
+   * function is called synchronously, and that might decide to shut
+   * everything down.  So we must have fully initialized our context before
+   * calling `conn_init', and mustn't touch it again afterwards -- since the
+   * block may have been freed.
+   */
   s = c->q.u.nat;
   s.port = 113;
   c->l->ao->socket_to_sockaddr(&s, &ss, &ssz);
   selbuf_disable(&c->b);
+  c->px = px; px->c = c;
+  px->fd = -1;
   if (conn_init(&px->cn, &sel, fd, (struct sockaddr *)&ss, ssz,
                proxy_connected, px)) {
     logmsg(&c->q, LOG_ERR, "failed to make %s proxy connection to %s: %s",
@@ -371,10 +563,10 @@ static void proxy_query(struct client *c)
     goto err_2;
   }
 
-  c->px = px; px->c = c;
-  px->fd = -1;
+  /* All ready to go. */
   return;
 
+  /* Tidy up after various kinds of failures. */
 err_2:
   selbuf_enable(&c->b);
 err_1:
@@ -384,35 +576,102 @@ err_0:
   reply_error(c, E_UNKNOWN);
 }
 
-static const struct policy default_policy = POLICY_INIT(A_NAME);
+/*----- Client connection functions ---------------------------------------*/
 
+/* Disconnect a client, freeing up any associated resources. */
+static void disconnect_client(struct client *c)
+{
+  selbuf_disable(&c->b);
+  close(c->fd);
+  sel_rmtimer(&c->t);
+  free_writebuf(&c->wb);
+  if (c->px) cancel_proxy(c->px);
+  c->next = dead_clients;
+  dead_clients = c;
+}
+
+/* Throw away dead clients now that we've reached a safe point in the
+ * program.
+ */
+static void reap_dead_clients(void)
+{
+  struct client *c, *cc;
+  for (c = dead_clients; c; c = cc) {
+    cc = c->next;
+    selbuf_destroy(&c->b);
+    xfree(c);
+  }
+  dead_clients = 0;
+}
+
+/* Time out a client because it's been idle for too long. */
+static void timeout_client(struct timeval *tv, void *p)
+{
+  struct client *c = p;
+  logmsg(&c->q, LOG_NOTICE, "timing out idle or stuck client");
+  sel_addtimer(&sel, &c->t, tv, timeout_client, 0);
+  disconnect_client(c);
+}
+
+/* Reset the client idle timer, as a result of activity.  Set EXISTP if
+ * there is an existing timer which needs to be removed.
+ */
+static void reset_client_timer(struct client *c, int existp)
+{
+  struct timeval tv;
+
+  gettimeofday(&tv, 0);
+  tv.tv_sec += 30;
+  if (existp) sel_rmtimer(&c->t);
+  sel_addtimer(&sel, &c->t, &tv, timeout_client, c);
+}
+
+/* Write a pseudorandom token into the buffer at P, which must have space for
+ * at least TOKENSZ bytes.
+ */
+#define TOKENRANDSZ 8
+#define TOKENSZ ((4*TOKENRANDSZ + 5)/3)
 static void user_token(char *p)
 {
-  static const char tokmap[64] =
-    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.-";
   unsigned a = 0;
   unsigned b = 0;
   int i;
-#define TOKENSZ 8
+  static const char tokmap[64] =
+    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.-";
 
-  if (tokenptr + TOKENSZ >= sizeof(tokenbuf)) {
-    if (read(randfd, tokenbuf, sizeof(tokenbuf)) < sizeof(tokenbuf))
-      die(1, "unexpected short read or error from `/dev/urandom'");
+  /* If there's not enough pseudorandom stuff lying around, then read more
+   * from the kernel.
+   */
+  if (tokenptr + TOKENRANDSZ >= sizeof(tokenbuf)) {
+    fill_random(tokenbuf, sizeof(tokenbuf));
     tokenptr = 0;
   }
 
-  for (i = 0; i < TOKENSZ; i++) {
+  /* Now encode the bytes using a slightly tweaked base-64 encoding.  Read
+   * bytes into the accumulator and write out characters while there's
+   * enough material.
+   */
+  for (i = 0; i < TOKENRANDSZ; i++) {
     a = (a << 8) | tokenbuf[tokenptr++]; b += 8;
     while (b >= 6) {
       b -= 6;
       *p++ = tokmap[(a >> b) & 0x3f];
     }
   }
+
+  /* If there's anything left in the accumulator then flush it out. */
   if (b)
     *p++ = tokmap[(a << (6 - b)) & 0x3f];
+
+  /* Null-terminate the token. */
   *p++ = 0;
 }
 
+/* Notification that a line has been received from the client.  Parse it,
+ * find out about the connection it's referring to, apply the relevant
+ * policy rules, and produce a response.  This is where almost everything
+ * interesting happens.
+ */
 static void client_line(char *line, size_t len, void *p)
 {
   struct client *c = p;
@@ -423,107 +682,171 @@ static void client_line(char *line, size_t len, void *p)
   struct policy upol = POLICY_INIT(A_LIMIT);
   struct policy_file pf;
   char buf[16];
-  int i;
+  int i, t;
 
+  /* If the connection has closed, then tidy stuff away. */
+  c->q.s[R].addr = c->raddr;
   c->q.s[L].port = c->q.s[R].port = 0;
   if (!line) {
     disconnect_client(c);
     return;
   }
 
-  if (fwatch_update(&polfw, "yaid.policy")) {
-    logmsg(0, LOG_INFO, "reload master policy file `%s'", "yaid.policy");
-    load_policy_file("yaid.policy", &policy);
+  /* Client activity, so update the timer. */
+  reset_client_timer(c, 1);
+
+  /* See if the policy file has changed since we last looked.  If so, try to
+   * read the new version.
+   */
+  if (fwatch_update(&polfw, policyfile)) {
+    logmsg(0, LOG_INFO, "reload master policy file `%s'", policyfile);
+    load_policy_file(policyfile, &policy);
   }
 
+  /* Read the local and remote port numbers into the query structure. */
   q = line;
   if (unum(&q, &c->q.s[L].port, 1, 65535)) goto bad;
   skipws(&q); if (*q != ',') goto bad; q++;
   if (unum(&q, &c->q.s[R].port, 1, 65535)) goto bad;
   skipws(&q); if (*q) goto bad;
 
+  /* Identify the connection.  Act on the result. */
   identify(&c->q);
   switch (c->q.resp) {
+
     case R_UID:
+      /* We found a user.  Track down the user's password entry, because
+       * we'll want that later.  Most of the processing for this case is
+       * below.
+       */
       if ((pw = getpwuid(c->q.u.uid)) == 0) {
        logmsg(&c->q, LOG_ERR, "no passwd entry for user %d", c->q.u.uid);
        reply_error(c, E_NOUSER);
        return;
       }
       break;
+
     case R_NAT:
+      /* We've acted as a NAT for this connection.  Proxy the query through
+       * to the actal client host.
+       */
       proxy_query(c);
       return;
+
     case R_ERROR:
-      /* Should already be logged. */
+      /* We failed to identify the connection for some reason.  We should
+       * already have logged an error, so there's not much to do here.
+       */
       reply_error(c, c->q.u.error);
       return;
+
     default:
+      /* Something happened that we don't understand. */
       abort();
   }
 
+  /* Search the table of policy rules to find a match. */
   for (i = 0; i < DA_LEN(&policy); i++) {
     pol = &DA(&policy)[i];
     if (!match_policy(pol, &c->q)) continue;
-    if (pol->act.act != A_USER)
-      goto match;
+
+    /* If this is something simple, then apply the resulting policy rule. */
+    if (pol->act.act != A_USER) goto match;
+
+    /* The global policy has decided to let the user have a say, so we must
+     * parse the user file.
+     */
     DRESET(&d);
     dstr_putf(&d, "%s/.yaid.policy", pw->pw_dir);
-    if (open_policy_file(&pf, d.buf, "user policy file", &c->q))
+    if (open_policy_file(&pf, d.buf, "user policy file", &c->q, OPF_NOENTOK))
       continue;
-    while (!read_policy_file(&pf)) {
+    while ((t = read_policy_file(&pf)) < T_ERROR) {
+
+      /* Give up after 100 lines or if there's an error.  If the user's
+       * policy is that complicated, something's gone very wrong.  Or there's
+       * too much commentary or something.
+       */
       if (pf.lno > 100) {
        logmsg(&c->q, LOG_ERR, "%s:%d: user policy file too long",
               pf.name, pf.lno);
        break;
       }
+
+      /* If this was a blank line, just go around again. */
+      if (t != T_OK) continue;
+
+      /* If this isn't a match, go around for the next rule. */
       if (!match_policy(&pf.p, &c->q)) continue;
+
+      /* Check that the user is allowed to request this action.  If not, see
+       * if there's a more acceptable action later on.
+       */
       if (!(pol->act.u.user & (1 << pf.p.act.act))) {
        logmsg(&c->q, LOG_ERR,
               "%s:%d: user action forbidden by global policy",
               pf.name, pf.lno);
        continue;
       }
+
+      /* We've found a match, so grab it, close the file, and say we're
+       * done.
+       */
       upol = pf.p; pol = &upol;
       init_policy(&pf.p);
       close_policy_file(&pf);
+      DDESTROY(&d);
       goto match;
     }
     close_policy_file(&pf);
+    DDESTROY(&d);
   }
+
+  /* No match: apply the built-in default policy. */
   pol = &default_policy;
 
 match:
-  DDESTROY(&d);
   switch (pol->act.act) {
+
     case A_NAME:
+      /* Report the actual user's name. */
       logmsg(&c->q, LOG_INFO, "user `%s' (%d)", pw->pw_name, c->q.u.uid);
-      reply(c, "USERID:UNIX", pw->pw_name);
+      reply(c, "USERID", "UNIX", pw->pw_name);
       break;
+
     case A_TOKEN:
+      /* Report an arbitrary token which we can look up in our log file. */
       user_token(buf);
       logmsg(&c->q, LOG_INFO, "user `%s' (%d); token = %s",
             pw->pw_name, c->q.u.uid, buf);
-      reply(c, "USERID:OTHER", buf);
+      reply(c, "USERID", "OTHER", buf);
       break;
+
     case A_DENY:
+      /* Deny that there's anyone there at all. */
       logmsg(&c->q, LOG_INFO, "user `%s' (%d); denying",
             pw->pw_name, c->q.u.uid);
       break;
+
     case A_HIDE:
+      /* Report the user as being hidden. */
       logmsg(&c->q, LOG_INFO, "user `%s' (%d); hiding",
             pw->pw_name, c->q.u.uid);
       reply_error(c, E_HIDDEN);
       break;
+
     case A_LIE:
+      /* Tell an egregious lie about who the user is. */
       logmsg(&c->q, LOG_INFO, "user `%s' (%d); lie = `%s'",
             pw->pw_name, c->q.u.uid, pol->act.u.lie);
-      reply(c, "USERID:UNIX", pol->act.u.lie);
+      reply(c, "USERID", "UNIX", pol->act.u.lie);
       break;
+
     default:
+      /* Something has gone very wrong. */
       abort();
   }
 
+  /* All done. */
   free_policy(&upol);
   return;
 
@@ -532,14 +855,16 @@ bad:
   disconnect_client(c);
 }
 
+/* Notification that a new client has connected.  Prepare to read a query. */
 static void accept_client(int fd, unsigned mode, void *p)
 {
   struct listen *l = p;
   struct client *c;
   struct sockaddr_storage ssr, ssl;
-  size_t ssz = sizeof(ssr);
+  socklen_t ssz = sizeof(ssr);
   int sk;
 
+  /* Accept the new connection. */
   if ((sk = accept(fd, (struct sockaddr *)&ssr, &ssz)) < 0) {
     if (errno != EAGAIN && errno == EWOULDBLOCK) {
       logmsg(0, LOG_ERR, "failed to accept incoming %s connection: %s",
@@ -547,11 +872,15 @@ static void accept_client(int fd, unsigned mode, void *p)
     }
     return;
   }
+  if (fix_up_socket(sk, "incoming client")) { close(sk); return; }
 
+  /* Build a client block and fill it in. */
   c = xmalloc(sizeof(*c));
   c->l = l;
   c->q.ao = l->ao;
-  l->ao->sockaddr_to_addr(&ssr, &c->q.s[R].addr);
+
+  /* Collect the local and remote addresses. */
+  l->ao->sockaddr_to_addr(&ssr, &c->raddr);
   ssz = sizeof(ssl);
   if (getsockname(sk, (struct sockaddr *)&ssl, &ssz)) {
     logmsg(0, LOG_ERR,
@@ -564,15 +893,20 @@ static void accept_client(int fd, unsigned mode, void *p)
   l->ao->sockaddr_to_addr(&ssl, &c->q.s[L].addr);
   c->q.s[L].port = c->q.s[R].port = 0;
 
-  /* logmsg(&c->q, LOG_INFO, "accepted %s connection", l->ao->name); */
-
+  /* Set stuff up for reading the query and sending responses. */
   selbuf_init(&c->b, &sel, sk, client_line, c);
   selbuf_setsize(&c->b, 1024);
+  reset_client_timer(c, 0);
   c->fd = sk;
   c->px = 0;
   init_writebuf(&c->wb, sk, done_client_write, c);
 }
 
+/*----- Main code ---------------------------------------------------------*/
+
+/* Set up a listening socket for the address family described by AO,
+ * listening on PORT.
+ */
 static int make_listening_socket(const struct addrops *ao, int port)
 {
   int fd;
@@ -582,68 +916,249 @@ static int make_listening_socket(const struct addrops *ao, int port)
   struct listen *l;
   size_t ssz;
 
+  /* Make the socket. */
   if ((fd = socket(ao->af, SOCK_STREAM, 0)) < 0) {
     if (errno == EAFNOSUPPORT) return (-1);
     die(1, "failed to create %s listening socket: %s",
        ao->name, strerror(errno));
   }
-  setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
+
+  /* Build the appropriate local address. */
   s.addr = *ao->any;
   s.port = port;
   ao->socket_to_sockaddr(&s, &ss, &ssz);
+
+  /* Perform any initialization specific to the address type. */
   if (ao->init_listen_socket(fd)) {
     die(1, "failed to initialize %s listening socket: %s",
        ao->name, strerror(errno));
   }
+
+  /* Bind to the address. */
+  setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
   if (bind(fd, (struct sockaddr *)&ss, ssz)) {
     die(1, "failed to bind %s listening socket: %s",
        ao->name, strerror(errno));
   }
+
+  /* Avoid unpleasant race conditions. */
   if (fdflags(fd, O_NONBLOCK, O_NONBLOCK, 0, 0)) {
     die(1, "failed to set %s listening socket nonblocking: %s",
        ao->name, strerror(errno));
   }
+
+  /* Prepare to listen. */
   if (listen(fd, 5))
     die(1, "failed to listen for %s: %s", ao->name, strerror(errno));
 
+  /* Make a record of all of this. */
   l = xmalloc(sizeof(*l));
   l->ao = ao;
   sel_initfile(&sel, &l->f, fd, SEL_READ, accept_client, l);
   sel_addfile(&l->f);
 
+  /* Done. */
   return (0);
 }
 
+/* Quit because of a fatal signal. */
+static void NORETURN quit(int sig, void *p)
+{
+  const char *signame = p;
+
+  logmsg(0, LOG_NOTICE, "shutting down on %s", signame);
+  if (pidfile) unlink(pidfile);
+  exit(0);
+}
+
+/* Answer whether the string pointed to by P consists entirely of digits. */
+static int numericp(const char *p)
+{
+  while (*p)
+    if (!isdigit((unsigned char)*p++)) return (0);
+  return (1);
+}
+
+static void usage(FILE *fp)
+{
+  pquis(fp, "Usage: $ [-Dl] [-G GROUP] [-U USER] [-P FILE] "
+       "[-c FILE] [-p PORT]\n");
+}
+
+static void version(FILE *fp)
+  { pquis(fp, "$, version " VERSION "\n"); }
+
+static void help(FILE *fp)
+{
+  version(fp); fputc('\n', fp);
+  usage(fp);
+  fputs("\n\
+Yet Another Ident Daemon.  Really, the world doesn't need such a thing.\n\
+It's just a shame none of the others do the right things.\n\
+\n\
+Options:\n\
+\n\
+  -h, --help           Show this help message.\n\
+  -v, --version                Show the version number.\n\
+  -u, --usage          Show a very short usage summary.\n\
+\n\
+  -D, --daemon         Become a daemon, running in the background.\n\
+  -G, --group=GROUP    Set group after initialization.\n\
+  -P, --pidfile=FILE   Write process id to FILE.\n\
+  -U, --user=USER      Set user after initialization.\n\
+  -c, --config=FILE    Read global policy from FILE.\n\
+  -l, --syslog         Write log messages using syslog(3).\n\
+  -p, --port=PORT      Listen for connections on this port.\n",
+       fp);
+}
+
 int main(int argc, char *argv[])
 {
   int port = 113;
+  uid_t u = -1;
+  gid_t g = -1;
+  struct passwd *pw = 0;
+  struct group *gr;
+  struct servent *s;
+  sig sigint, sigterm;
+  FILE *fp = 0;
+  int i;
+  unsigned f = 0;
+#define f_bogus 1u
+#define f_daemon 2u
   const struct addrops *ao;
   int any = 0;
 
   ego(argv[0]);
 
-  fwatch_init(&polfw, "yaid.policy");
-  if (load_policy_file("yaid.policy", &policy))
-    exit(1);
-  { int i;
-    for (i = 0; i < DA_LEN(&policy); i++)
-      print_policy(&DA(&policy)[i]);
+  /* Parse command-line options. */
+  for (;;) {
+    const struct option opts[] = {
+      { "help",                0,              0,      'h' },
+      { "version",     0,              0,      'v' },
+      { "usage",       0,              0,      'u' },
+      { "daemon",      0,              0,      'D' },
+      { "group",       OPTF_ARGREQ,    0,      'G' },
+      { "pidfile",     OPTF_ARGREQ,    0,      'P' },
+      { "user",                OPTF_ARGREQ,    0,      'U' },
+      { "config",      OPTF_ARGREQ,    0,      'c' },
+      { "syslog",      0,              0,      'l' },
+      { "port",                OPTF_ARGREQ,    0,      'p' },
+      { 0,             0,              0,      0 }
+    };
+
+    if ((i = mdwopt(argc, argv, "hvuDG:P:U:c:lp:", opts, 0, 0, 0)) < 0)
+      break;
+    switch (i) {
+      case 'h': help(stdout); exit(0);
+      case 'v': version(stdout); exit(0);
+      case 'u': usage(stdout); exit(0);
+      case 'D': f |= f_daemon; break;
+      case 'P': pidfile = optarg; break;
+      case 'c': policyfile = optarg; break;
+      case 'l': flags |= F_SYSLOG; break;
+      case 'G':
+       if (numericp(optarg))
+         g = atoi(optarg);
+       else if ((gr = getgrnam(optarg)) == 0)
+         die(1, "unknown group `%s'", optarg);
+       else
+         g = gr->gr_gid;
+       break;
+      case 'U':
+       if (numericp(optarg))
+         u = atoi(optarg);
+       else if ((pw = getpwnam(optarg)) == 0)
+         die(1, "unknown user `%s'", optarg);
+       else
+         u = pw->pw_uid;
+       break;
+      case 'p':
+       if (numericp(optarg))
+         port = atoi(optarg);
+       else if ((s = getservbyname(optarg, "tcp")) == 0)
+         die(1, "unknown service name `%s'", optarg);
+       else
+         port = ntohs(s->s_port);
+       break;
+      default: f |= f_bogus; break;
+    }
   }
-
-  if ((randfd = open("/dev/urandom", O_RDONLY)) < 0) {
-    die(1, "failed to open `/dev/urandom' for reading: %s",
-       strerror(errno));
+  if (optind < argc) f |= f_bogus;
+  if (f & f_bogus) { usage(stderr); exit(1); }
+
+  /* If a user has been requested, but no group, then find the user's primary
+   * group.  If the user was given by name, then we already have a password
+   * entry and should use that, in case two differently-named users have the
+   * same uid but distinct gids.
+   */
+  if (u != -1 && g == -1) {
+    if (!pw && (pw = getpwuid(u)) == 0) {
+      die(1, "failed to find password entry for user %d: "
+         "request group explicitly", u);
+    }
+    g = pw->pw_gid;
   }
 
+  /* Initialize system-specific machinery. */
+  init_sys();
+
+  /* Load the global policy rules. */
+  fwatch_init(&polfw, policyfile);
+  if (load_policy_file(policyfile, &policy))
+    exit(1);
+
+  /* Set up the I/O event system. */
   sel_init(&sel);
+
+  /* Watch for some interesting signals. */
+  sig_init(&sel);
+  sig_add(&sigint, SIGINT, quit, "SIGINT");
+  sig_add(&sigterm, SIGTERM, quit, "SIGTERM");
+
+  /* Listen for incoming connections. */
   for (ao = addroptab; ao->name; ao++)
     if (!make_listening_socket(ao, port)) any = 1;
-  if (!any)
-    die(1, "no IP protocols supported");
+  if (!any) die(1, "no IP protocols supported");
+
+  /* Open the pidfile now, in case it's somewhere we can't write. */
+  if (pidfile && (fp = fopen(pidfile, "w")) == 0) {
+    die(1, "failed to open pidfile `%s' for writing: %s",
+       pidfile, strerror(errno));
+  }
+
+  /* If we're meant to use syslog, then open the log. */
+  if (flags & F_SYSLOG)
+    openlog(QUIS, 0, LOG_DAEMON);
+
+  /* Drop privileges. */
+  if ((g != -1 && (setegid(g) || setgid(g) ||
+                  (getuid() == 0 && setgroups(1, &g)))) ||
+      (u != -1 && setuid(u)))
+    die(1, "failed to drop privileges: %s", strerror(errno));
 
-  for (;;)
-    if (sel_select(&sel)) die(1, "select failed: %s", strerror(errno));
+  /* Become a background process, if requested. */
+  if ((f & f_daemon) && daemonize())
+    die(1, "failed to become daemon: %s", strerror(errno));
+
+  /* Write the process id to the pidfile. */
+  if (fp) {
+    fprintf(fp, "%d\n", getpid());
+    fclose(fp);
+  }
+
+  /* And now we're going. */
+  flags |= F_RUNNING;
+
+  /* Read events and process them. */
+  for (;;) {
+    if (sel_select(&sel) && errno != EINTR)
+      die(1, "select failed: %s", strerror(errno));
+    reap_dead_proxies();
+    reap_dead_clients();
+  }
 
+  /* This just keeps the compiler happy. */
   return (0);
 }