Makefile.am: Tweak `silent-rules' machinery.
[yaid] / linux.c
diff --git a/linux.c b/linux.c
index 25fcb6c..412fae8 100644 (file)
--- a/linux.c
+++ b/linux.c
 /*----- Static variables --------------------------------------------------*/
 
 static FILE *natfp;                    /* File handle for NAT table */
+static int randfd;                     /* File descriptor for random data */
+
+/*----- Miscellaneous system services -------------------------------------*/
+
+/* Fill the buffer at P with SZ random bytes.  The buffer will be moderately
+ * large: this is intended to be a low-level interface, not a general-purpose
+ * utility.
+ */
+void fill_random(void *p, size_t sz)
+{
+  ssize_t n;
+
+  n = read(randfd, p, sz);
+  if (n < 0) fatal("error reading `/dev/urandom': %s", strerror(errno));
+  else if (n < sz) fatal("unexpected short read from `/dev/urandom'");
+}
 
 /*----- Address-type operations -------------------------------------------*/
 
@@ -102,7 +118,7 @@ static int get_default_gw(int af, union addr *a)
 
   /* Open a netlink socket for interrogating the kernel. */
   if ((fd = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE)) < 0)
-    die(1, "failed to create netlink socket: %s", strerror(errno));
+    fatal("failed to create netlink socket: %s", strerror(errno));
 
   /* We want to read the routing table.  There doesn't seem to be a good way
    * to do this without just crawling through the whole thing.
@@ -119,14 +135,14 @@ static int get_default_gw(int af, union addr *a)
   rtgen->rtgen_family = af;
 
   if (write(fd, nlmsg, nlmsg->nlmsg_len) < 0)
-    die(1, "failed to send RTM_GETROUTE request: %s", strerror(errno));
+    fatal("failed to send RTM_GETROUTE request: %s", strerror(errno));
 
   /* Now we try to parse the answer. */
   for (;;) {
 
     /* Not finished yet, so read another chunk of answer. */
     if ((n = read(fd, buf, sizeof(buf))) < 0)
-      die(1, "failed to read RTM_GETROUTE response: %s", strerror(errno));
+      fatal("failed to read RTM_GETROUTE response: %s", strerror(errno));
 
     /* Start at the beginning of the response. */
     nlmsg = (struct nlmsghdr *)buf;
@@ -174,58 +190,48 @@ done:
   return (rc);
 }
 
-/* Find out who is responsible for the connection described in the query Q.
- * Write the answer to Q.  Errors are logged and reported via the query
- * structure.
+/* Initially, PP points into a string containing whitespace-separated fields.
+ * Point P to the next field, null-terminate it, and advance PP so that we
+ * can read the next field in the next call.
  */
-void identify(struct query *q)
+#define NEXTFIELD do {                                                 \
+  for (p = pp; isspace((unsigned char)*p); p++);                       \
+  for (pp = p; *pp && !isspace((unsigned char)*pp); pp++);             \
+  if (*pp) *pp++ = 0;                                                  \
+} while (0)
+
+/* Search the `tcp' connection table for the address family AO, looking for a
+ * connection between the addresses in QS.  GWP is nonzero if the query's
+ * remote address is our gateway and we shouldn't expect the remote address
+ * in the system table to actually match it because of NAT.  Return nonzero
+ * if we have filled in Q conclusively; return zero if the caller should try
+ * a different approach.
+ */
+static int search_tcp_file(struct query *q, int gwp,
+                          const struct addrops *ao,
+                          struct socket qs[NDIR])
 {
   FILE *fp = 0;
   dstr d = DSTR_INIT;
   char *p, *pp;
-  struct socket s[4];
+  struct socket s[NDIR];
   int i;
-  int gwp = 0;
-  unsigned fl;
-#define F_SADDR 1u
-#define F_SPORT 2u
-#define F_DADDR 4u
-#define F_DPORT 8u
-#define F_ALL (F_SADDR | F_SPORT | F_DADDR | F_DPORT)
-#define F_ESTAB 16u
   uid_t uid;
   enum { LOC, REM, ST, UID, NFIELD };
   int f, ff[NFIELD];
-
-  /* If we have a default gateway, and it matches the remote address then
-   * this may be a proxy connection from our NAT, so remember this, and don't
-   * inspect the remote addresses in the TCP tables.
-   */
-  if (!get_default_gw(q->ao->af, &s[0].addr) &&
-      q->ao->addreq(&s[0].addr, &q->s[R].addr))
-    gwp = 1;
+  int rc = 1;
 
   /* Open the relevant TCP connection table. */
-  if ((fp = fopen(q->ao->sys->procfile, "r")) == 0) {
+  if ((fp = fopen(ao->sys->procfile, "r")) == 0) {
     logmsg(q, LOG_ERR, "failed to open `%s' for reading: %s",
-          q->ao->sys->procfile, strerror(errno));
+          ao->sys->procfile, strerror(errno));
     goto err_unk;
   }
 
-  /* Initially, PP points into a string containing whitespace-separated
-   * fields.  Point P to the next field, null-terminate it, and advance PP
-   * so that we can read the next field in the next call.
-   */
-#define NEXTFIELD do {                                                 \
-  for (p = pp; isspace((unsigned char)*p); p++);                       \
-  for (pp = p; *pp && !isspace((unsigned char)*pp); pp++);             \
-  if (*pp) *pp++ = 0;                                                  \
-} while (0)
-
   /* Read the header line from the file. */
   if (dstr_putline(&d, fp) == EOF) {
     logmsg(q, LOG_ERR, "failed to read header line from `%s': %s",
-          q->ao->sys->procfile,
+          ao->sys->procfile,
           ferror(fp) ? strerror(errno) : "unexpected EOF");
     goto err_unk;
   }
@@ -259,7 +265,7 @@ void identify(struct query *q)
   for (i = 0; i < NFIELD; i++) {
     if (ff[i] < 0) {
       logmsg(q, LOG_ERR, "failed to find required fields in `%s'",
-            q->ao->sys->procfile);
+            ao->sys->procfile);
       goto err_unk;
     }
   }
@@ -296,12 +302,13 @@ void identify(struct query *q)
        * query is our gateway then don't check the remote address in the
        * field (but do check the port number).
        */
-      if (q->ao->sys->parseaddr(&p, &s[i].addr)) goto next_row;
-      if (*p != ':') break; p++;
+      if (ao->sys->parseaddr(&p, &s[i].addr)) goto next_row;
+      if (*p != ':') break;
+      p++;
       s[i].port = strtoul(p, 0, 16);
       if ((i == R && gwp) ?
-           q->s[R].port != s[i].port :
-           !sockeq(q->ao, &q->s[i], &s[i]))
+           qs[R].port != s[i].port :
+           !sockeq(ao, &qs[i], &s[i]))
        goto next_row;
     }
 
@@ -312,7 +319,7 @@ void identify(struct query *q)
     if (uid != -1) {
       q->resp = R_UID;
       q->u.uid = uid;
-      if (gwp) q->s[R].addr = s[i].addr;
+      if (gwp) qs[R].addr = s[i].addr;
       goto done;
     }
   next_row:;
@@ -321,9 +328,99 @@ void identify(struct query *q)
   /* We got to the end of the file and didn't find anything. */
   if (ferror(fp)) {
     logmsg(q, LOG_ERR, "failed to read connection table `%s': %s",
-          q->ao->sys->procfile, strerror(errno));
+          ao->sys->procfile, strerror(errno));
     goto err_unk;
   }
+  rc = 0;
+
+err_unk:
+  /* Something went wrong and the protocol can't express what.  We should
+   * have logged what the problem actually was.
+   */
+  q->resp = R_ERROR;
+  q->u.error = E_UNKNOWN;
+
+done:
+  /* All done. */
+  dstr_destroy(&d);
+  if (fp) fclose(fp);
+  return (rc);
+}
+
+/* Convert the IPv4 socket address IN into the equivalent IPv4-mapped IPv6
+ * address OUT.
+ */
+static void map_v4(struct socket *out, const struct socket *in)
+{
+  unsigned i;
+  in_addr_t a4 = ntohl(in->addr.ipv4.s_addr);
+
+  for (i = 0; i < 10; i++) out->addr.ipv6.s6_addr[i] = 0;
+  for (i = 10; i < 12; i++) out->addr.ipv6.s6_addr[i] = 0xff;
+  for (i = 0; i < 4; i++) out->addr.ipv6.s6_addr[15 - i] = (a4 >> 8*i)&0xff;
+  out->port = in->port;
+}
+
+/* Convert the IPv4-mapped IPv6 socket address IN into the equivalent IPv4
+ * address OUT; return -1 if the IN address isn't actually IPv4-mapped.
+ */
+static int unmap_v4(struct socket *out, const struct socket *in)
+{
+  unsigned i;
+  in_addr_t a4 = 0;
+
+  for (i = 0; i < 10; i++) if (in->addr.ipv6.s6_addr[i] != 0) return (-1);
+  for (i = 10; i < 12; i++) if (in->addr.ipv6.s6_addr[i] != 0xff) return (-1);
+  for (i = 0; i < 4; i++) a4 |= in->addr.ipv6.s6_addr[15 - i] << 8*i;
+  out->addr.ipv4.s_addr = htonl(a4);
+  out->port = in->port;
+  return (0);
+}
+
+/* Find out who is responsible for the connection described in the query Q.
+ * Write the answer to Q.  Errors are logged and reported via the query
+ * structure.
+ */
+void identify(struct query *q)
+{
+  FILE *fp = 0;
+  dstr d = DSTR_INIT;
+  char *p, *pp;
+  struct socket s[4];
+  int i;
+  int gwp = 0;
+  unsigned fl;
+#define F_SADDR 1u
+#define F_SPORT 2u
+#define F_DADDR 4u
+#define F_DPORT 8u
+#define F_ALL (F_SADDR | F_SPORT | F_DADDR | F_DPORT)
+#define F_ESTAB 16u
+
+  /* If we have a default gateway, and it matches the remote address then
+   * this may be a proxy connection from our NAT, so remember this, and don't
+   * inspect the remote addresses in the TCP tables.
+   */
+  if (!get_default_gw(q->ao->af, &s[0].addr) &&
+      q->ao->addreq(&s[0].addr, &q->s[R].addr))
+    gwp = 1;
+
+  /* Search the main `tcp' table. */
+  if (search_tcp_file(q, gwp, q->ao, q->s)) goto done;
+
+  /* Oh, dear.  If this is IPv4, then the entry might actually be in the IPv6
+   * table, with weird addresses.  So we must try again.
+   */
+  if (q->ao->af == AF_INET) {
+    map_v4(&s[L], &q->s[L]); map_v4(&s[R], &q->s[R]);
+    if (search_tcp_file(q, gwp, &addroptab[ADDR_IPV6], s)) {
+      if (gwp && unmap_v4(&q->s[R], &s[R])) {
+       logmsg(q, LOG_ERR, "can't unmap NATted destination address");
+       goto err_unk;
+      }
+      goto done;
+    }
+  }
 
   /* If we opened the NAT table file, and we're using IPv4, then check to see
    * whether we should proxy the connection.  At least the addresses in this
@@ -417,6 +514,13 @@ void identify(struct query *q)
          !sockeq(q->ao, &s[i^1], &q->s[R]))
        continue;
 
+      /* As a trap for the unwary, this file contains unhelpful entries which
+       * just mirror the source/destination addresses.  If this is one of
+       * those, we'll be stuck in a cycle talking to ourselves.
+       */
+      if (sockeq(q->ao, &s[i], &s[i^3]))
+       continue;
+
       /* We win.  The remaining address must be the client host.  We should
        * proxy this query.
        */
@@ -433,8 +537,6 @@ void identify(struct query *q)
     }
   }
 
-#undef NEXTFIELD
-
   /* We didn't find a match anywhere.  How unfortunate. */
   logmsg(q, LOG_NOTICE, "connection not found");
   q->resp = R_ERROR;
@@ -454,14 +556,23 @@ done:
   if (fp) fclose(fp);
 }
 
+#undef NEXTFIELD
+
 /* Initialize the system-specific code. */
 void init_sys(void)
 {
+  /* Open the NAT connection map. */
   if ((natfp = fopen("/proc/net/nf_conntrack", "r")) == 0 &&
       errno != ENOENT) {
     die(1, "failed to open `/proc/net/nf_conntrack' for reading: %s",
        strerror(errno));
   }
+
+  /* Open the random data source. */
+  if ((randfd = open("/dev/urandom", O_RDONLY)) < 0) {
+    die(1, "failed to open `/dev/urandom' for reading: %s",
+       strerror(errno));
+  }
 }
 
 /*----- That's all, folks -------------------------------------------------*/