noip.c: Have parsers fail if there's trailing junk.
[preload-hacks] / noip.c
diff --git a/noip.c b/noip.c
index ec66340..12c9f9c 100644 (file)
--- a/noip.c
+++ b/noip.c
@@ -34,6 +34,7 @@
 #include <assert.h>
 #include <ctype.h>
 #include <errno.h>
+#include <stdarg.h>
 #include <stddef.h>
 #include <stdio.h>
 #include <stdlib.h>
@@ -62,19 +63,21 @@ enum { UNUSED, STALE, USED };               /* Unix socket status values */
 enum { WANT_FRESH, WANT_EXISTING };    /* Socket address dispositions */
 enum { DENY, ALLOW };                  /* ACL verdicts */
 
-static int address_families[] = { AF_INET, -1 };
+static int address_families[] = { AF_INET, AF_INET6, -1 };
 
 #define ADDRBUFSZ 64
 
 /* Address representations. */
 typedef union ipaddr {
   struct in_addr v4;
+  struct in6_addr v6;
 } ipaddr;
 
 /* Convenient socket address hacking. */
 typedef union address {
   struct sockaddr sa;
   struct sockaddr_in sin;
+  struct sockaddr_in6 sin6;
 } address;
 
 /* Access control list nodes */
@@ -91,7 +94,7 @@ typedef struct full_ipaddr {
   int af;
   ipaddr addr;
 } full_ipaddr;
-#define MAX_LOCAL_IPADDRS 16
+#define MAX_LOCAL_IPADDRS 64
 static full_ipaddr local_ipaddrs[MAX_LOCAL_IPADDRS];
 static int n_local_ipaddrs;
 
@@ -123,7 +126,8 @@ static aclnode *connect_real,  **connect_tail = &connect_real;
   _(recvfrom, ssize_t, (int, void *buf, size_t, int,                   \
                        struct sockaddr *from, socklen_t *fromlen))     \
   _(sendmsg, ssize_t, (int, const struct msghdr *, int))               \
-  _(recvmsg, ssize_t, (int, struct msghdr *, int))
+  _(recvmsg, ssize_t, (int, struct msghdr *, int))                     \
+  _(ioctl, int, (int, unsigned long, ...))
 
 /* Function pointers to set up. */
 #define DECL(imp, ret, args) static ret (*real_##imp) args;
@@ -144,6 +148,7 @@ static void import(void)
 /* Socket address casts */
 #define SA(sa) ((struct sockaddr *)(sa))
 #define SIN(sa) ((struct sockaddr_in *)(sa))
+#define SIN6(sa) ((struct sockaddr_in6 *)(sa))
 #define SUN(sa) ((struct sockaddr_un *)(sa))
 
 /* Raw bytes */
@@ -156,8 +161,10 @@ static void import(void)
 /* Debugging */
 #ifdef DEBUG
 #  define D(body) { if (debug) { body } }
+#  define Dpid pid_t pid = debug ? getpid() : -1
 #else
 #  define D(body) ;
+#  define Dpid
 #endif
 
 /* Preservation of error status */
@@ -202,6 +209,7 @@ static int family_known_p(int af)
 {
   switch (af) {
     case AF_INET:
+    case AF_INET6:
       return (1);
     default:
       return (0);
@@ -213,6 +221,7 @@ static socklen_t family_socklen(int af)
 {
   switch (af) {
     case AF_INET: return (sizeof(struct sockaddr_in));
+    case AF_INET6: return (sizeof(struct sockaddr_in6));
     default: abort();
   }
 }
@@ -222,6 +231,7 @@ static int address_width(int af)
 {
   switch (af) {
     case AF_INET: return 32;
+    case AF_INET6: return 128;
     default: abort();
   }
 }
@@ -238,6 +248,23 @@ static int common_prefix_length(int af, const ipaddr *a, const ipaddr *b)
       if ((aa&m) == 0 && (bb&m) == m) return (32 - simple_mask_length(m));
       else return (-1);
     } break;
+    case AF_INET6: {
+      const uint8_t *aa = a->v6.s6_addr, *bb = b->v6.s6_addr;
+      unsigned m;
+      unsigned n;
+      int i;
+
+      for (i = 0; i < 16 && aa[i] == bb[i]; i++);
+      n = 8*i;
+      if (i < 16) {
+       m = aa[i]^bb[i];
+       if ((aa[i]&m) != 0 || (bb[i]&m) != m) return (-1);
+       n += 8 - simple_mask_length(m);
+       for (i++; i < 16; i++)
+         if (aa[i] || bb[i] != 0xff) return (-1);
+      }
+      return (n);
+    } break;
     default:
       abort();
   }
@@ -248,6 +275,7 @@ static int port_from_sockaddr(const struct sockaddr *sa)
 {
   switch (sa->sa_family) {
     case AF_INET: return (ntohs(SIN(sa)->sin_port));
+    case AF_INET6: return (ntohs(SIN6(sa)->sin6_port));
     default: abort();
   }
 }
@@ -257,14 +285,17 @@ static void port_to_sockaddr(struct sockaddr *sa, int port)
 {
   switch (sa->sa_family) {
     case AF_INET: SIN(sa)->sin_port = htons(port); break;
+    case AF_INET6: SIN6(sa)->sin6_port = htons(port); break;
     default: abort();
   }
 }
+
 /* Extract the address part from SA and store it in A. */
 static void ipaddr_from_sockaddr(ipaddr *a, const struct sockaddr *sa)
 {
   switch (sa->sa_family) {
     case AF_INET: a->v4 = SIN(sa)->sin_addr; break;
+    case AF_INET6: a->v6 = SIN6(sa)->sin6_addr; break;
     default: abort();
   }
 }
@@ -279,6 +310,7 @@ static int ipaddr_equal_p(int af, const ipaddr *a, const ipaddr *b)
 {
   switch (af) {
     case AF_INET: return (a->v4.s_addr == b->v4.s_addr);
+    case AF_INET6: return (memcmp(a->v6.s6_addr, b->v6.s6_addr, 16) == 0);
     default: abort();
   }
 }
@@ -295,6 +327,19 @@ static int sockaddr_in_range_p(const struct sockaddr *sa,
       return (ntohl(a->v4.s_addr) <= addr &&
              addr <= ntohl(b->v4.s_addr));
     } break;
+    case AF_INET6: {
+      const uint8_t *ss = SIN6(sa)->sin6_addr.s6_addr;
+      const uint8_t *aa = a->v6.s6_addr, *bb = b->v6.s6_addr;
+      int h = 1, l = 1;
+      int i;
+
+      for (i = 0; h && l && i < 16; i++, ss++, aa++, bb++) {
+       if (*ss < *aa || *bb < *ss) return (0);
+       if (*aa < *ss) l = 0;
+       if (*ss < *bb) h = 0;
+      }
+      return (1);
+    } break;
     default:
       abort();
   }
@@ -311,6 +356,15 @@ static void wildcard_address(int af, struct sockaddr *sa)
       sin->sin_port = 0;
       sin->sin_addr.s_addr = INADDR_ANY;
     } break;
+    case AF_INET6: {
+      struct sockaddr_in6 *sin6 = SIN6(sa);
+      memset(sin6, 0, sizeof(*sin6));
+      sin6->sin6_family = AF_INET6;
+      sin6->sin6_port = 0;
+      sin6->sin6_addr = in6addr_any;
+      sin6->sin6_scope_id = 0;
+      sin6->sin6_flowinfo = 0;
+    } break;
     default:
       abort();
   }
@@ -329,6 +383,16 @@ static void mask_address(int af, ipaddr *a, int plen, int highp)
       if (highp) addr |= ~mask;
       a->v4.s_addr = htonl(addr & 0xffffffff);
     } break;
+    case AF_INET6: {
+      int i = plen/8;
+      unsigned m = (0xff << (8 - plen%8)) & 0xff;
+      unsigned s = highp ? 0xff : 0;
+      if (m) {
+       a->v6.s6_addr[i] = (a->v6.s6_addr[i] & m) | (s & ~m);
+       i++;
+      }
+      for (; i < 16; i++) a->v6.s6_addr[i] = s;
+    } break;
     default:
       abort();
   }
@@ -384,7 +448,7 @@ static char *present_sockaddr(const struct sockaddr *sa, socklen_t len,
       }
       WANT(1); PUTC(0);
     } break;
-    case AF_INET: {
+    case AF_INET: case AF_INET6: {
       char addrbuf[NI_MAXHOST], portbuf[NI_MAXSERV];
       int err = getnameinfo(sa, len,
                            addrbuf, sizeof(addrbuf),
@@ -407,7 +471,7 @@ nospace:
 
 /* Guess the family of a textual socket address. */
 static int guess_address_family(const char *p)
-  { return (AF_INET); }
+  { return (strchr(p, ':') ? AF_INET6 : AF_INET); }
 
 /* Parse a socket address P and write the result to SA. */
 static int parse_sockaddr(struct sockaddr *sa, const char *p)
@@ -443,13 +507,13 @@ static int parse_sockaddr(struct sockaddr *sa, const char *p)
 #ifdef DEBUG
 
 /* Write to standard error a description of the ACL node A. */
-static void dump_aclnode(aclnode *a)
+static void dump_aclnode(const aclnode *a)
 {
   char buf[ADDRBUFSZ];
   const char *p;
   int plen;
 
-  fprintf(stderr, "noip:   %c ", a->act ? '+' : '-');
+  fprintf(stderr, "noip(%d):   %c ", getpid(), a->act ? '+' : '-');
   plen = common_prefix_length(a->af, &a->minaddr, &a->maxaddr);
   p = inet_ntop(a->af, &a->minaddr, buf, sizeof(buf));
   fprintf(stderr, strchr(p, ':') ? "[%s]" : "%s", p);
@@ -466,7 +530,7 @@ static void dump_aclnode(aclnode *a)
   fputc('\n', stderr);
 }
 
-static void dump_acl(aclnode *a)
+static void dump_acl(const aclnode *a)
 {
   int act = ALLOW;
 
@@ -474,31 +538,34 @@ static void dump_acl(aclnode *a)
     dump_aclnode(a);
     act = a->act;
   }
-  fprintf(stderr, "noip:   [default policy: %s]\n",
+  fprintf(stderr, "noip(%d):   [default policy: %s]\n", getpid(),
          act == ALLOW ? "DENY" : "ALLOW");
 }
 
 #endif
 
 /* Returns nonzero if the ACL A allows the socket address SA. */
-static int acl_allows_p(aclnode *a, const struct sockaddr *sa)
+static int acl_allows_p(const aclnode *a, const struct sockaddr *sa)
 {
   unsigned short port = port_from_sockaddr(sa);
   int act = ALLOW;
+  Dpid;
 
   D({ char buf[ADDRBUFSZ];
-      fprintf(stderr, "noip: check %s\n",
+      fprintf(stderr, "noip(%d): check %s\n", pid,
              present_sockaddr(sa, 0, buf, sizeof(buf))); })
   for (; a; a = a->next) {
     D( dump_aclnode(a); )
     if (sockaddr_in_range_p(sa, &a->minaddr, &a->maxaddr) &&
        a->minport <= port && port <= a->maxport) {
-      D( fprintf(stderr, "noip: aha!  %s\n", a->act ? "ALLOW" : "DENY"); )
+      D( fprintf(stderr, "noip(%d): aha!  %s\n", pid,
+                a->act ? "ALLOW" : "DENY"); )
       return (a->act);
     }
     act = a->act;
   }
-  D( fprintf(stderr, "noip: nothing found: %s\n", act ? "DENY" : "ALLOW"); )
+  D( fprintf(stderr, "noip(%d): nothing found: %s\n", pid,
+            act ? "DENY" : "ALLOW"); )
   return (!act);
 }
 
@@ -572,7 +639,7 @@ static int encode_inet_addr(struct sockaddr_un *sun,
   char buf[ADDRBUFSZ];
   int rc;
 
-  D( fprintf(stderr, "noip: encode %s (%s)",
+  D( fprintf(stderr, "noip(%d): encode %s (%s)", getpid(),
             present_sockaddr(sa, 0, buf, sizeof(buf)),
             want == WANT_EXISTING ? "EXISTING" : "FRESH"); )
   sun->sun_family = AF_UNIX;
@@ -618,10 +685,10 @@ static int encode_inet_addr(struct sockaddr_un *sun,
 }
 
 /* Decode the Unix address SUN to an Internet address SIN.  If AF_HINT is
- * nonzero, an empty address (indicative of an unbound Unix-domain socket) of
- * the is translated to a wildcard Internet address of the appropriate
- * family.  Returns zero on success; -1 on failure (e.g., it wasn't one of
- * our addresses).
+ * nonzero, an empty address (indicative of an unbound Unix-domain socket) is
+ * translated to a wildcard Internet address of the appropriate family.
+ * Returns zero on success; -1 on failure (e.g., it wasn't one of our
+ * addresses).
  */
 static int decode_inet_addr(struct sockaddr *sa, int af_hint,
                            const struct sockaddr_un *sun,
@@ -636,7 +703,7 @@ static int decode_inet_addr(struct sockaddr *sa, int af_hint,
   if (len > sizeof(*sun)) return (-1);
   ((char *)sun)[len] = 0;
   nn = strlen(sun->sun_path);
-  D( fprintf(stderr, "noip: decode `%s'", sun->sun_path); )
+  D( fprintf(stderr, "noip(%d): decode `%s'", getpid(), sun->sun_path); )
   if (af_hint && !sun->sun_path[0]) {
     wildcard_address(af_hint, sa);
     D( fprintf(stderr, " -- unbound socket\n"); )
@@ -655,9 +722,11 @@ static int decode_inet_addr(struct sockaddr *sa, int af_hint,
 
 /* SK is (or at least might be) a Unix-domain socket we created when an
  * Internet socket was asked for.  We've decided it should be an Internet
- * socket after all, with family AF_HINT, so convert it.
+ * socket after all, with family AF_HINT, so convert it.  If TMP is not null,
+ * then don't replace the existing descriptor: store the new socket in *TMP
+ * and return zero.
  */
-static int fixup_real_ip_socket(int sk, int af_hint)
+static int fixup_real_ip_socket(int sk, int af_hint, int *tmp)
 {
   int nsk;
   int type;
@@ -701,18 +770,22 @@ static int fixup_real_ip_socket(int sk, int af_hint)
 } while (0);
   OPTS(FIX)
 #undef FIX
-  if ((f = fcntl(sk, F_GETFL)) < 0 ||
-      (fd = fcntl(sk, F_GETFD)) < 0 ||
-      fcntl(nsk, F_SETFL, f) < 0 ||
-      dup2(nsk, sk) < 0) {
+  if (tmp)
+    *tmp = nsk;
+  else {
+    if ((f = fcntl(sk, F_GETFL)) < 0 ||
+       (fd = fcntl(sk, F_GETFD)) < 0 ||
+       fcntl(nsk, F_SETFL, f) < 0 ||
+       dup2(nsk, sk) < 0) {
+      close(nsk);
+      return (-1);
+    }
+    unlink(sun.sun_path);
     close(nsk);
-    return (-1);
-  }
-  unlink(sun.sun_path);
-  close(nsk);
-  if (fcntl(sk, F_SETFD, fd) < 0) {
-    perror("noip: fixup_real_ip_socket F_SETFD");
-    abort();
+    if (fcntl(sk, F_SETFD, fd) < 0) {
+      perror("noip: fixup_real_ip_socket F_SETFD");
+      abort();
+    }
   }
   return (0);
 }
@@ -728,7 +801,7 @@ static int do_implicit_bind(int sk, const struct sockaddr **sa,
   socklen_t mylen = sizeof(*sun);
 
   if (acl_allows_p(connect_real, *sa)) {
-    if (fixup_real_ip_socket(sk, (*sa)->sa_family)) return (-1);
+    if (fixup_real_ip_socket(sk, (*sa)->sa_family, 0)) return (-1);
   } else {
     if (real_getsockname(sk, SA(sun), &mylen) < 0) return (-1);
     if (sun->sun_family == AF_UNIX) {
@@ -971,6 +1044,7 @@ static void parse_acl_line(char **pp, aclnode ***tail)
        maxaddr = minaddr;
        mask_address(af, &minaddr, n, 0);
        mask_address(af, &maxaddr, n, 1);
+       RESCAN(del);
       } else
        maxaddr = minaddr;
       parse_ports(&p, &minport, &maxport);
@@ -978,12 +1052,14 @@ static void parse_acl_line(char **pp, aclnode ***tail)
     }
     SKIPSPC;
     if (*p != ',') break;
-    p++;
+    if (*p) p++;
   }
+  if (*p) goto bad;
+  *pp = p;
   return;
 
 bad:
-  D( fprintf(stderr, "noip: bad acl spec (ignored)\n"); )
+  D( fprintf(stderr, "noip(%d): bad acl spec (ignored)\n", getpid()); )
   return;
 }
 
@@ -1000,10 +1076,12 @@ static void parse_autoports(char **pp)
   if (*p != '-') goto bad; p++;
   NEXTNUMBER(q, del); y = strtoul(q, 0, 0); RESCAN(del);
   minautoport = x; maxautoport = y;
+  SKIPSPC; if (*p) goto bad;
+  *pp = p;
   return;
 
 bad:
-  D( fprintf(stderr, "bad port range (ignored)\n"); )
+  D( fprintf(stderr, "noip(%d): bad port range (ignored)\n", getpid()); )
   return;
 }
 
@@ -1027,6 +1105,7 @@ static void readconfig(void)
   char buf[1024];
   size_t n;
   char *p, *q, *cmd;
+  Dpid;
 
   parse_acl_env("NOIP_REALBIND_BEFORE", &bind_tail);
   parse_acl_env("NOIP_REALCONNECT_BEFORE", &connect_tail);
@@ -1037,11 +1116,11 @@ static void readconfig(void)
   }
   if ((p = getenv("NOIP_CONFIG")) == 0)
     snprintf(p = buf, sizeof(buf), "%s/.noip", home());
-  D( fprintf(stderr, "noip: config file: %s\n", p); )
+  D( fprintf(stderr, "noip(%d): config file: %s\n", pid, p); )
 
   if ((fp = fopen(p, "r")) == 0) {
-    D( fprintf(stderr, "noip: couldn't read config: %s\n",
-              strerror(errno)); )
+    D( fprintf(stderr, "noip(%d): couldn't read config: %s\n",
+              pid, strerror(errno)); )
     goto done;
   }
   while (fgets(buf, sizeof(buf), fp)) {
@@ -1082,12 +1161,12 @@ done:
     snprintf(buf, sizeof(buf), "%s/noip-%s", tmpdir(), user());
     sockdir = xstrdup(buf);
   }
-  D( fprintf(stderr, "noip: socketdir: %s\n", sockdir);
-     fprintf(stderr, "noip: autoports: %u-%u\n",
-            minautoport, maxautoport);
-     fprintf(stderr, "noip: realbind acl:\n");
+  D( fprintf(stderr, "noip(%d): socketdir: %s\n", pid, sockdir);
+     fprintf(stderr, "noip(%d): autoports: %u-%u\n",
+            pid, minautoport, maxautoport);
+     fprintf(stderr, "noip(%d): realbind acl:\n", pid);
      dump_acl(bind_real);
-     fprintf(stderr, "noip: realconnect acl:\n");
+     fprintf(stderr, "noip(%d): realconnect acl:\n", pid);
      dump_acl(connect_real); )
 }
 
@@ -1113,7 +1192,7 @@ int socket(int pf, int ty, int proto)
 
 int socketpair(int pf, int ty, int proto, int *sk)
 {
-  if (pf == PF_INET) {
+  if (family_known_p(pf)) {
     pf = PF_UNIX;
     proto = 0;
   }
@@ -1127,7 +1206,7 @@ int bind(int sk, const struct sockaddr *sa, socklen_t len)
   if (family_known_p(sa->sa_family)) {
     PRESERVING_ERRNO({
       if (acl_allows_p(bind_real, sa)) {
-       if (fixup_real_ip_socket(sk, sa->sa_family))
+       if (fixup_real_ip_socket(sk, sa->sa_family, 0))
          return (-1);
       } else {
        encode_inet_addr(&sun, sa, WANT_FRESH);
@@ -1165,7 +1244,7 @@ ssize_t sendto(int sk, const void *buf, size_t len, int flags,
 {
   struct sockaddr_un sun;
 
-  if (to && to->sa_family == AF_INET) {
+  if (to && family_known_p(to->sa_family)) {
     PRESERVING_ERRNO({
       do_implicit_bind(sk, &to, &tolen, &sun);
     });
@@ -1197,7 +1276,7 @@ ssize_t sendmsg(int sk, const struct msghdr *msg, int flags)
   const struct sockaddr *sa;
   struct msghdr mymsg;
 
-  if (msg->msg_name && SA(msg->msg_name)->sa_family == AF_INET) {
+  if (msg->msg_name && family_known_p(SA(msg->msg_name)->sa_family)) {
     PRESERVING_ERRNO({
       sa = SA(msg->msg_name);
       mymsg = *msg;
@@ -1299,6 +1378,36 @@ int setsockopt(int sk, int lev, int opt, const void *p, socklen_t len)
   return (real_setsockopt(sk, lev, opt, p, len));
 }
 
+int ioctl(int fd, unsigned long op, ...)
+{
+  va_list ap;
+  void *arg;
+  int sk;
+  int rc;
+
+  va_start(ap, op);
+  arg = va_arg(ap, void *);
+
+  switch (op) {
+    case SIOCGIFADDR:
+    case SIOCGIFBRDADDR:
+    case SIOCGIFDSTADDR:
+    case SIOCGIFNETMASK:
+      PRESERVING_ERRNO({
+       if (fixup_real_ip_socket(fd, AF_INET, &sk)) goto real;
+      });
+      rc = real_ioctl(sk, op, arg);
+      PRESERVING_ERRNO({ close(sk); });
+      break;
+    default:
+    real:
+      rc = real_ioctl(fd, op, arg);
+      break;
+  }
+  va_end(ap);
+  return (rc);
+}
+
 /*----- Initialization ----------------------------------------------------*/
 
 /* Clean up the socket directory, deleting stale sockets. */
@@ -1309,6 +1418,7 @@ static void cleanup_sockdir(void)
   address addr;
   struct sockaddr_un sun;
   struct stat st;
+  Dpid;
 
   if ((dir = opendir(sockdir)) == 0) return;
   sun.sun_family = AF_UNIX;
@@ -1319,13 +1429,13 @@ static void cleanup_sockdir(void)
     if (decode_inet_addr(&addr.sa, 0, &sun, SUN_LEN(&sun)) ||
        stat(sun.sun_path, &st) ||
        !S_ISSOCK(st.st_mode)) {
-      D( fprintf(stderr, "noip: ignoring unknown socketdir entry `%s'\n",
-                sun.sun_path); )
+      D( fprintf(stderr, "noip(%d): ignoring unknown socketdir entry `%s'\n",
+                pid, sun.sun_path); )
       continue;
     }
     if (unix_socket_status(&sun, 0) == STALE) {
-      D( fprintf(stderr, "noip: clearing away stale socket %s\n",
-                d->d_name); )
+      D( fprintf(stderr, "noip(%d): clearing away stale socket %s\n",
+                pid, d->d_name); )
       unlink(sun.sun_path);
     }
   }
@@ -1340,7 +1450,9 @@ static void get_local_ipaddrs(void)
   struct ifaddrs *ifa_head, *ifa;
   ipaddr a;
   int i;
+  Dpid;
 
+  D( fprintf(stderr, "noip(%d): fetching local addresses...\n", pid); )
   if (getifaddrs(&ifa_head)) { perror("getifaddrs"); return; }
   for (n_local_ipaddrs = 0, ifa = ifa_head;
        n_local_ipaddrs < MAX_LOCAL_IPADDRS && ifa;
@@ -1349,7 +1461,8 @@ static void get_local_ipaddrs(void)
       continue;
     ipaddr_from_sockaddr(&a, ifa->ifa_addr);
     D({ char buf[ADDRBUFSZ];
-       fprintf(stderr, "noip: local addr %s = %s", ifa->ifa_name,
+       fprintf(stderr, "noip(%d):   local addr %s = %s", pid,
+               ifa->ifa_name,
                inet_ntop(ifa->ifa_addr->sa_family, &a,
                          buf, sizeof(buf))); })
     for (i = 0; i < n_local_ipaddrs; i++) {
@@ -1377,13 +1490,13 @@ static void create_sockdir(void)
 {
   struct stat st;
 
-  if (stat(sockdir, &st)) {
+  if (lstat(sockdir, &st)) {
     if (errno == ENOENT) {
       if (mkdir(sockdir, 0700)) {
        perror("noip: creating socketdir");
        exit(127);
       }
-      if (!stat(sockdir, &st))
+      if (!lstat(sockdir, &st))
        goto check;
     }
     perror("noip: checking socketdir");