noip.c: Add commentary to some hairier functions.
[preload-hacks] / noip.c
diff --git a/noip.c b/noip.c
index 423822d..8806d02 100644 (file)
--- a/noip.c
+++ b/noip.c
@@ -60,7 +60,6 @@
 /*----- Data structures ---------------------------------------------------*/
 
 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, AF_INET6, -1 };
@@ -89,6 +88,14 @@ typedef struct aclnode {
   unsigned short minport, maxport;
 } aclnode;
 
+/* Implicit bind records */
+typedef struct impbind {
+  struct impbind *next;
+  int af, how;
+  ipaddr minaddr, maxaddr, bindaddr;
+} impbind;
+enum { EXPLICIT, SAME };
+
 /* A type for an address range */
 typedef struct addrrange {
   int type;
@@ -116,6 +123,7 @@ static unsigned minautoport = 16384, maxautoport = 65536;
 /* Access control lists */
 static aclnode *bind_real, **bind_tail = &bind_real;
 static aclnode *connect_real,  **connect_tail = &connect_real;
+static impbind *impbinds, **impbind_tail = &impbinds;
 
 /*----- Import the real versions of functions -----------------------------*/
 
@@ -309,6 +317,23 @@ static void ipaddr_from_sockaddr(ipaddr *a, const struct sockaddr *sa)
   }
 }
 
+/* Store the address A in SA. */
+static void ipaddr_to_sockaddr(struct sockaddr *sa, const ipaddr *a)
+{
+  switch (sa->sa_family) {
+    case AF_INET:
+      SIN(sa)->sin_addr = a->v4;
+      break;
+    case AF_INET6:
+      SIN6(sa)->sin6_addr = a->v6;
+      SIN6(sa)->sin6_scope_id = 0;
+      SIN6(sa)->sin6_flowinfo = 0;
+      break;
+    default:
+      abort();
+  }
+}
+
 /* Copy a whole socket address about. */
 static void copy_sockaddr(struct sockaddr *sa_dst,
                          const struct sockaddr *sa_src)
@@ -571,7 +596,8 @@ static int acl_allows_p(const aclnode *a, const struct sockaddr *sa)
              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) &&
+    if (a->af == sa->sa_family &&
+       sockaddr_in_range_p(sa, &a->minaddr, &a->maxaddr) &&
        a->minport <= port && port <= a->maxport) {
       D( fprintf(stderr, "noip(%d): aha!  %s\n", pid,
                 a->act ? "ALLOW" : "DENY"); )
@@ -615,10 +641,23 @@ static int unix_socket_status(struct sockaddr_un *sun, int quickp)
   int rc;
   char buf[256];
 
+  /* If we can't find the socket node, then it's definitely not in use.  If
+   * we get some other error, then this socket is weird.
+   */
   if (stat(sun->sun_path, &st))
     return (errno == ENOENT ? UNUSED : USED);
+
+  /* If it's not a socket, then something weird is going on.  If we're just
+   * probing quickly to find a spare port, then existence is sufficient to
+   * discourage us now.
+   */
   if (!S_ISSOCK(st.st_mode) || quickp)
     return (USED);
+
+  /* The socket's definitely there, but is anyone actually still holding it
+   * open?  The only way I know to discover this is to trundle through
+   * `/proc/net/unix'.  If there's no entry, then the socket must be stale.
+   */
   rc = USED;
   if ((fp = fopen("/proc/net/unix", "r")) == 0)
     goto done;
@@ -635,6 +674,8 @@ static int unix_socket_status(struct sockaddr_un *sun, int quickp)
   rc = STALE;
 done:
   if (fp) fclose(fp);
+
+  /* All done. */
   return (rc);
 }
 
@@ -650,71 +691,107 @@ static int encode_unused_inet_addr(struct sockaddr *sa,
   struct sockaddr_un wsun;
   int rc;
   char buf[ADDRBUFSZ];
+  int port = port_from_sockaddr(sa);
 
+  /* First, look for an exact match.  Only look quickly unless we're
+   * desperate.  If the socket is in use, we fail here.  (This could get
+   * racy.  Let's not worry about that for now.)
+   */
   snprintf(sun->sun_path, sizeof(sun->sun_path), "%s/%s", sockdir,
           present_sockaddr(sa, 0, buf, sizeof(buf)));
   if ((rc = unix_socket_status(sun, !desperatep)) == USED) return (-1);
   else if (rc == STALE) unlink(sun->sun_path);
 
+  /* Next, check the corresponding wildcard address, so as to avoid
+   * inadvertant collisions with listeners.  Do this in the same way.
+   */
   wildcard_address(sa->sa_family, &waddr.sa);
-  port_to_sockaddr(&waddr.sa, port_from_sockaddr(sa));
+  port_to_sockaddr(&waddr.sa, port);
   snprintf(wsun.sun_path, sizeof(wsun.sun_path), "%s/%s", sockdir,
           present_sockaddr(&waddr.sa, 0, buf, sizeof(buf)));
   if ((rc = unix_socket_status(&wsun, !desperatep)) == USED) return (-1);
   else if (rc == STALE) unlink(wsun.sun_path);
 
+  /* All is well. */
   return (0);
 }
 
-/* Encode the Internet address SA as a Unix-domain address SUN.  If WANT is
- * WANT_FRESH, and SA's port number is zero, then we pick an arbitrary local
- * port.  Otherwise we pick the port given.  There's an unpleasant hack to
- * find servers bound to local wildcard addresses.  Returns zero on success;
- * -1 on failure.
+/* Encode the Internet address SA as a Unix-domain address SUN.  If the flag
+ * `ENCF_FRESH' is set, and SA's port number is zero, then we pick an
+ * arbitrary local port.  Otherwise we pick the port given.  There's an
+ * unpleasant hack to find servers bound to local wildcard addresses.
+ * Returns zero on success; -1 on failure.
  */
+#define ENCF_FRESH 1u
 static int encode_inet_addr(struct sockaddr_un *sun,
                            const struct sockaddr *sa,
-                           int want)
+                           unsigned f)
 {
   int i;
   int desperatep = 0;
   address addr;
+  int port = port_from_sockaddr(sa);
   char buf[ADDRBUFSZ];
   int rc;
 
   D( fprintf(stderr, "noip(%d): encode %s (%s)", getpid(),
             present_sockaddr(sa, 0, buf, sizeof(buf)),
-            want == WANT_EXISTING ? "EXISTING" : "FRESH"); )
+            (f&ENCF_FRESH) ? "FRESH" : "EXISTING"); )
+
+  /* Start making the Unix-domain address. */
   sun->sun_family = AF_UNIX;
-  if (port_from_sockaddr(sa) || want == WANT_EXISTING) {
+
+  if (port || !(f&ENCF_FRESH)) {
+
+    /* Try the address as given.  If it's in use, or we don't necessarily
+     * want an existing socket, then we're done.
+     */
     snprintf(sun->sun_path, sizeof(sun->sun_path), "%s/%s", sockdir,
             present_sockaddr(sa, 0, buf, sizeof(buf)));
     rc = unix_socket_status(sun, 0);
     if (rc == STALE) unlink(sun->sun_path);
-    if (rc != USED && want == WANT_EXISTING) {
-      wildcard_address(sa->sa_family, &addr.sa);
-      port_to_sockaddr(&addr.sa, port_from_sockaddr(sa));
-      snprintf(sun->sun_path, sizeof(sun->sun_path), "%s/%s", sockdir,
-              present_sockaddr(&addr.sa, 0, buf, sizeof(buf)));
-      if (unix_socket_status(sun, 0) == STALE) unlink(sun->sun_path);
-    }
+    if (rc == USED || (f&ENCF_FRESH)) goto found;
+
+    /* We're looking for a socket which already exists.  Try the
+     * corresponding wildcard address.
+     */
+    wildcard_address(sa->sa_family, &addr.sa);
+    port_to_sockaddr(&addr.sa, port);
+    snprintf(sun->sun_path, sizeof(sun->sun_path), "%s/%s", sockdir,
+            present_sockaddr(&addr.sa, 0, buf, sizeof(buf)));
+    if (unix_socket_status(sun, 0) == STALE) unlink(sun->sun_path);
+
   } else {
+    /* We want a fresh new socket. */
+
+    /* Make a copy of the given address, because we're going to mangle it. */
     copy_sockaddr(&addr.sa, sa);
+
+    /* Try a few random-ish port numbers to see if any of them is spare. */
     for (i = 0; i < 10; i++) {
       port_to_sockaddr(&addr.sa, randrange(minautoport, maxautoport));
       if (!encode_unused_inet_addr(&addr.sa, sun, 0)) goto found;
     }
+
+    /* Things must be getting tight.  Work through all of the autoport range
+     * to see if we can find a spare one.  The first time, just do it the
+     * quick way; if that doesn't work, then check harder for stale sockets.
+     */
     for (desperatep = 0; desperatep < 2; desperatep++) {
       for (i = minautoport; i <= maxautoport; i++) {
        port_to_sockaddr(&addr.sa, i);
        if (!encode_unused_inet_addr(&addr.sa, sun, 0)) goto found;
       }
     }
+
+    /* We failed to find any free ports. */
     errno = EADDRINUSE;
     D( fprintf(stderr, " -- can't resolve\n"); )
     return (-1);
-  found:;
   }
+
+  /* Success. */
+found:
   D( fprintf(stderr, " -> `%s'\n", sun->sun_path); )
   return (0);
 }
@@ -825,6 +902,58 @@ static int fixup_real_ip_socket(int sk, int af_hint, int *tmp)
   return (0);
 }
 
+/* We found the real address SA, with length LEN; if it's a Unix-domain
+ * address corresponding to a fake socket, convert it to cover up the
+ * deception.  Whatever happens, put the result at FAKE and store its length
+ * at FAKELEN.
+ */
+static void return_fake_name(struct sockaddr *sa, socklen_t len,
+                            struct sockaddr *fake, socklen_t *fakelen)
+{
+  address addr;
+  socklen_t alen;
+
+  if (sa->sa_family == AF_UNIX &&
+      !decode_inet_addr(&addr.sa, 0, SUN(sa), len)) {
+    sa = &addr.sa;
+    len = family_socklen(addr.sa.sa_family);
+  }
+  alen = len;
+  if (len > *fakelen) len = *fakelen;
+  if (len > 0) memcpy(fake, sa, len);
+  *fakelen = alen;
+}
+
+/*----- Implicit binding --------------------------------------------------*/
+
+#ifdef DEBUG
+
+static void dump_impbind(const impbind *i)
+{
+  char buf[ADDRBUFSZ];
+
+  fprintf(stderr, "noip(%d):   ", getpid());
+  dump_addrrange(i->af, &i->minaddr, &i->maxaddr);
+  switch (i->how) {
+    case SAME: fprintf(stderr, " <self>"); break;
+    case EXPLICIT:
+      fprintf(stderr, " %s", inet_ntop(i->af, &i->bindaddr,
+                                      buf, sizeof(buf)));
+      break;
+    default: abort();
+  }
+  fputc('\n', stderr);
+}
+
+static void dump_impbind_list(void)
+{
+  const impbind *i;
+
+  for (i = impbinds; i; i = i->next) dump_impbind(i);
+}
+
+#endif
+
 /* The socket SK is about to be used to communicate with the remote address
  * SA.  Assign it a local address so that getpeername(2) does something
  * useful.
@@ -834,6 +963,8 @@ static int do_implicit_bind(int sk, const struct sockaddr **sa,
 {
   address addr;
   socklen_t mylen = sizeof(*sun);
+  const impbind *i;
+  Dpid;
 
   if (acl_allows_p(connect_real, *sa)) {
     if (fixup_real_ip_socket(sk, (*sa)->sa_family, 0)) return (-1);
@@ -842,11 +973,24 @@ static int do_implicit_bind(int sk, const struct sockaddr **sa,
     if (sun->sun_family == AF_UNIX) {
       if (mylen < sizeof(*sun)) ((char *)sun)[mylen] = 0;
       if (!sun->sun_path[0]) {
+       D( fprintf(stderr, "noip(%d): checking impbind list...\n", pid); )
+       for (i = impbinds; i; i = i->next) {
+         D( dump_impbind(i); )
+         if ((*sa)->sa_family == i->af &&
+             sockaddr_in_range_p(*sa, &i->minaddr, &i->maxaddr)) {
+           D( fprintf(stderr, "noip(%d): match!\n", pid); )
+           addr.sa.sa_family = (*sa)->sa_family;
+           ipaddr_to_sockaddr(&addr.sa, &i->bindaddr);
+           goto found;
+         }
+       }
+       D( fprintf(stderr, "noip(%d): no match; using wildcard\n", pid); )
        wildcard_address((*sa)->sa_family, &addr.sa);
-       encode_inet_addr(sun, &addr.sa, WANT_FRESH);
+      found:
+       encode_inet_addr(sun, &addr.sa, ENCF_FRESH);
        if (real_bind(sk, SA(sun), SUN_LEN(sun))) return (-1);
       }
-      encode_inet_addr(sun, *sa, WANT_EXISTING);
+      encode_inet_addr(sun, *sa, 0);
       *sa = SA(sun);
       *len = SUN_LEN(sun);
     }
@@ -854,28 +998,6 @@ static int do_implicit_bind(int sk, const struct sockaddr **sa,
   return (0);
 }
 
-/* We found the real address SA, with length LEN; if it's a Unix-domain
- * address corresponding to a fake socket, convert it to cover up the
- * deception.  Whatever happens, put the result at FAKE and store its length
- * at FAKELEN.
- */
-static void return_fake_name(struct sockaddr *sa, socklen_t len,
-                            struct sockaddr *fake, socklen_t *fakelen)
-{
-  address addr;
-  socklen_t alen;
-
-  if (sa->sa_family == AF_UNIX &&
-      !decode_inet_addr(&addr.sa, 0, SUN(sa), len)) {
-    sa = &addr.sa;
-    len = family_socklen(addr.sa.sa_family);
-  }
-  alen = len;
-  if (len > *fakelen) len = *fakelen;
-  if (len > 0) memcpy(fake, sa, len);
-  *fakelen = alen;
-}
-
 /*----- Configuration -----------------------------------------------------*/
 
 /* Return the process owner's home directory. */
@@ -1159,6 +1281,82 @@ static void parse_acl_env(const char *var, aclnode ***tail)
   }
 }
 
+struct add_impbind_ctx {
+  int af, how;
+  ipaddr addr;
+};
+
+static void add_impbind(int af, const ipaddr *min, const ipaddr *max,
+                       void *p)
+{
+  struct add_impbind_ctx *ctx = p;
+  impbind *i;
+
+  if (ctx->af && af != ctx->af) return;
+  NEW(i);
+  i->af = af;
+  i->how = ctx->how;
+  i->minaddr = *min; i->maxaddr = *max;
+  switch (ctx->how) {
+    case EXPLICIT: i->bindaddr = ctx->addr;
+    case SAME: break;
+    default: abort();
+  }
+  *impbind_tail = i; impbind_tail = &i->next;
+}
+
+/* Parse an implicit-bind line.  An implicit-bind entry has the form
+ * ADDR-RANGE {ADDR | same}
+ */
+static void parse_impbind_line(char **pp)
+{
+  struct add_impbind_ctx ctx;
+  char *p = *pp, *q;
+  addrrange r;
+  int del;
+
+  for (;;) {
+    if (parse_addrrange(&p, &r)) goto bad;
+    SKIPSPC;
+    if (KWMATCHP("same")) {
+      ctx.how = SAME;
+      ctx.af = 0;
+    } else {
+      ctx.how = EXPLICIT;
+      parse_nextaddr(&p, &q, &del);
+      ctx.af = guess_address_family(q);
+      if (inet_pton(ctx.af, q, &ctx.addr) < 0) goto bad;
+      RESCAN(del);
+    }
+    foreach_addrrange(&r, add_impbind, &ctx);
+    SKIPSPC;
+    if (*p != ',') break;
+    if (*p) p++;
+  }
+  if (*p) goto bad;
+  *pp = p;
+  return;
+
+bad:
+  D( fprintf(stderr, "noip(%d): bad implicit-bind spec (ignored)\n",
+            getpid()); )
+  return;
+}
+
+/* Parse implicit-bind instructions from an environment variable VAR,
+ * attaching it to the list.
+ */
+static void parse_impbind_env(const char *var)
+{
+  char *p, *q;
+
+  if ((p = getenv(var)) != 0) {
+    p = q = xstrdup(p);
+    parse_impbind_line(&q);
+    free(p);
+  }
+}
+
 /* Parse the autoports configuration directive.  Syntax is MIN - MAX. */
 static void parse_autoports(char **pp)
 {
@@ -1169,7 +1367,8 @@ static void parse_autoports(char **pp)
   SKIPSPC;
   NEXTNUMBER(q, del); x = strtoul(q, 0, 0); RESCAN(del);
   SKIPSPC;
-  if (*p != '-') goto bad; p++;
+  if (*p != '-') goto bad;
+  p++;
   NEXTNUMBER(q, del); y = strtoul(q, 0, 0); RESCAN(del);
   minautoport = x; maxautoport = y;
   SKIPSPC; if (*p) goto bad;
@@ -1192,6 +1391,7 @@ static void readconfig(void)
 
   parse_acl_env("NOIP_REALBIND_BEFORE", &bind_tail);
   parse_acl_env("NOIP_REALCONNECT_BEFORE", &connect_tail);
+  parse_impbind_env("NOIP_IMPBIND_BEFORE");
   if ((p = getenv("NOIP_AUTOPORTS")) != 0) {
     p = q = xstrdup(p);
     parse_autoports(&q);
@@ -1223,22 +1423,27 @@ static void readconfig(void)
       parse_acl_line(&p, &bind_tail);
     else if (strcmp(cmd, "realconnect") == 0)
       parse_acl_line(&p, &connect_tail);
+    else if (strcmp(cmd, "impbind") == 0)
+      parse_impbind_line(&p);
     else if (strcmp(cmd, "autoports") == 0)
       parse_autoports(&p);
     else if (strcmp(cmd, "debug") == 0)
       debug = *p ? atoi(p) : 1;
     else
-      D( fprintf(stderr, "noip: bad config command %s\n", cmd); )
+      D( fprintf(stderr, "noip(%d): bad config command %s\n", pid, cmd); )
   }
   fclose(fp);
 
 done:
   parse_acl_env("NOIP_REALBIND", &bind_tail);
   parse_acl_env("NOIP_REALCONNECT", &connect_tail);
+  parse_impbind_env("NOIP_IMPBIND");
   parse_acl_env("NOIP_REALBIND_AFTER", &bind_tail);
   parse_acl_env("NOIP_REALCONNECT_AFTER", &connect_tail);
+  parse_impbind_env("NOIP_IMPBIND_AFTER");
   *bind_tail = 0;
   *connect_tail = 0;
+  *impbind_tail = 0;
   if (!sockdir) sockdir = getenv("NOIP_SOCKETDIR");
   if (!sockdir) {
     snprintf(buf, sizeof(buf), "%s/noip-%s", tmpdir(), user());
@@ -1250,7 +1455,9 @@ done:
      fprintf(stderr, "noip(%d): realbind acl:\n", pid);
      dump_acl(bind_real);
      fprintf(stderr, "noip(%d): realconnect acl:\n", pid);
-     dump_acl(connect_real); )
+     dump_acl(connect_real);
+     fprintf(stderr, "noip(%d): impbind list:\n", pid);
+     dump_impbind_list(); )
 }
 
 /*----- Overridden system calls -------------------------------------------*/
@@ -1344,7 +1551,7 @@ int bind(int sk, const struct sockaddr *sa, socklen_t len)
        if (fixup_real_ip_socket(sk, sa->sa_family, 0))
          return (-1);
       } else {
-       encode_inet_addr(&sun, sa, WANT_FRESH);
+       encode_inet_addr(&sun, sa, ENCF_FRESH);
        sa = SA(&sun);
        len = SUN_LEN(&sun);
       }
@@ -1531,40 +1738,36 @@ int accept(int sk, struct sockaddr *sa, socklen_t *len)
 
 int getsockname(int sk, struct sockaddr *sa, socklen_t *len)
 {
+  char sabuf[1024];
+  socklen_t mylen = sizeof(sabuf);
   int rc;
   Dpid;
 
   D( fprintf(stderr, "noip(%d): GETSOCKNAME sk=%d", pid, sk); )
-  PRESERVING_ERRNO({
-    char sabuf[1024];
-    socklen_t mylen = sizeof(sabuf);
-    rc = real_getsockname(sk, SA(sabuf), &mylen);
-    if (rc >= 0) {
-      D( fprintf(stderr, " -> converting...\n"); )
-      return_fake_name(SA(sabuf), mylen, sa, len);
-      D( fprintf(stderr, "noip(%d): ... GETSOCKNAME", pid); )
-    }
-  });
+  rc = real_getsockname(sk, SA(sabuf), &mylen);
+  if (rc >= 0) {
+    D( fprintf(stderr, " -> converting...\n"); )
+    return_fake_name(SA(sabuf), mylen, sa, len);
+    D( fprintf(stderr, "noip(%d): ... GETSOCKNAME", pid); )
+  }
   D( dump_addrresult(rc, sa, *len); )
   return (rc);
 }
 
 int getpeername(int sk, struct sockaddr *sa, socklen_t *len)
 {
+  char sabuf[1024];
+  socklen_t mylen = sizeof(sabuf);
   int rc;
   Dpid;
 
   D( fprintf(stderr, "noip(%d): GETPEERNAME sk=%d", pid, sk); )
-  PRESERVING_ERRNO({
-    char sabuf[1024];
-    socklen_t mylen = sizeof(sabuf);
-    rc = real_getpeername(sk, SA(sabuf), &mylen);
-    if (rc >= 0) {
-      D( fprintf(stderr, " -> converting...\n"); )
-      return_fake_name(SA(sabuf), mylen, sa, len);
-      D( fprintf(stderr, "noip(%d): ... GETPEERNAME", pid); )
-    }
-  });
+  rc = real_getpeername(sk, SA(sabuf), &mylen);
+  if (rc >= 0) {
+    D( fprintf(stderr, " -> converting...\n"); )
+    return_fake_name(SA(sabuf), mylen, sa, len);
+    D( fprintf(stderr, "noip(%d): ... GETPEERNAME", pid); )
+  }
   D( dump_addrresult(rc, sa, *len); )
   return (0);
 }
@@ -1572,9 +1775,10 @@ int getpeername(int sk, struct sockaddr *sa, socklen_t *len)
 int getsockopt(int sk, int lev, int opt, void *p, socklen_t *len)
 {
   switch (lev) {
-    case SOL_IP:
-    case SOL_TCP:
-    case SOL_UDP:
+    case IPPROTO_IP:
+    case IPPROTO_IPV6:
+    case IPPROTO_TCP:
+    case IPPROTO_UDP:
       if (*len > 0)
        memset(p, 0, *len);
       return (0);
@@ -1585,9 +1789,10 @@ int getsockopt(int sk, int lev, int opt, void *p, socklen_t *len)
 int setsockopt(int sk, int lev, int opt, const void *p, socklen_t len)
 {
   switch (lev) {
-    case SOL_IP:
-    case SOL_TCP:
-    case SOL_UDP:
+    case IPPROTO_IP:
+    case IPPROTO_IPV6:
+    case IPPROTO_TCP:
+    case IPPROTO_UDP:
       return (0);
   }
   switch (opt) {