chiark / gitweb /
noip.c (do_implicit_bind): Handle `SAME' impbind entries properly.
[preload-hacks] / noip.c
diff --git a/noip.c b/noip.c
index 423822dc7309e014a41f66d7c7b0d4c764f2505f..345f3251d7c56d2e591fedee22b663e8b330e505 100644 (file)
--- a/noip.c
+++ b/noip.c
 #include <ifaddrs.h>
 #include <netdb.h>
 
+#ifndef SUN_LEN
+#  define SUN_LEN (sun) \
+       (strlen((sun)->sun_path) + offsetof(struct sockaddr_un, sun_path))
+#endif
+
 /*----- Data structures ---------------------------------------------------*/
 
-enum { UNUSED, STALE, USED };          /* Unix socket status values */
-enum { WANT_FRESH, WANT_EXISTING };    /* Socket address dispositions */
+/* Unix socket status values. */
+#define UNUSED 0u                      /* No sign of anyone using it */
+#define STALE 1u                       /* Socket exists, but is abandoned */
+#define USED 16u                       /* Socket is in active use */
+#define LISTEN 2u                      /* Socket has an active listener */
+
 enum { DENY, ALLOW };                  /* ACL verdicts */
 
 static int address_families[] = { AF_INET, AF_INET6, -1 };
@@ -89,6 +98,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 +133,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,11 +327,65 @@ 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)
   { memcpy(sa_dst, sa_src, family_socklen(sa_src->sa_family)); }
 
+/* Convert an AF_INET socket address into the equivalent IPv4-mapped AF_INET6
+ * address.
+ */
+static void map_ipv4_sockaddr(struct sockaddr_in6 *a6,
+                             const struct sockaddr_in *a4)
+{
+  size_t i;
+  in_addr_t a = ntohl(a4->sin_addr.s_addr);
+
+  a6->sin6_family = AF_INET6;
+  a6->sin6_port = a4->sin_port;
+  a6->sin6_scope_id = 0;
+  a6->sin6_flowinfo = 0;
+  for (i = 0; i < 10; i++) a6->sin6_addr.s6_addr[i] = 0;
+  for (i = 10; i < 12; i++) a6->sin6_addr.s6_addr[i] = 0xff;
+  for (i = 0; i < 4; i++) a6->sin6_addr.s6_addr[15 - i] = (a >> 8*i)&0xff;
+}
+
+/* Convert an AF_INET6 socket address containing an IPv4-mapped IPv6 address
+ * into the equivalent AF_INET4 address.  Return zero on success, or -1 if
+ * the address has the wrong form.
+ */
+static int unmap_ipv4_sockaddr(struct sockaddr_in *a4,
+                              const struct sockaddr_in6 *a6)
+{
+  size_t i;
+  in_addr_t a;
+
+  for (i = 0; i < 10; i++) if (a6->sin6_addr.s6_addr[i] != 0) return (-1);
+  for (i = 10; i < 12; i++) if (a6->sin6_addr.s6_addr[i] != 0xff) return (-1);
+  for (i = 0, a = 0; i < 4; i++) a |= a6->sin6_addr.s6_addr[15 - i] << 8*i;
+  a4->sin_family = AF_INET;
+  a4->sin_port = a6->sin6_port;
+  a4->sin_addr.s_addr = htonl(a);
+  return (0);
+}
+
 /* Answer whether two addresses are equal. */
 static int ipaddr_equal_p(int af, const ipaddr *a, const ipaddr *b)
 {
@@ -571,7 +643,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"); )
@@ -613,28 +686,65 @@ static int unix_socket_status(struct sockaddr_un *sun, int quickp)
   FILE *fp = 0;
   size_t len, n;
   int rc;
+  unsigned long f;
   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;
   if (!fgets(buf, sizeof(buf), fp)) goto done; /* skip header */
   len = strlen(sun->sun_path);
+  rc = 0;
   while (fgets(buf, sizeof(buf), fp)) {
     n = strlen(buf);
     if (n >= len + 2 && buf[n - len - 2] == ' ' && buf[n - 1] == '\n' &&
-       memcmp(buf + n - len - 1, sun->sun_path, len) == 0)
-      goto done;
+       memcmp(buf + n - len - 1, sun->sun_path, len) == 0) {
+      rc |= USED;
+      if (sscanf(buf, "%*s %*x %*x %lx", &f) < 0 || (f&0x00010000))
+       rc |= LISTEN;
+    }
   }
   if (ferror(fp))
     goto done;
-  rc = STALE;
+  if (!rc) rc = STALE;
 done:
   if (fp) fclose(fp);
+
+  /* All done. */
+  return (rc);
+}
+
+/* Encode SA as a Unix-domain address SUN, and return whether it's currently
+ * in use.
+ */
+static int encode_single_inet_addr(const struct sockaddr *sa,
+                                  struct sockaddr_un *sun,
+                                  int quickp)
+{
+  char buf[ADDRBUFSZ];
+  int rc;
+
+  snprintf(sun->sun_path, sizeof(sun->sun_path), "%s/%s", sockdir,
+          present_sockaddr(sa, 0, buf, sizeof(buf)));
+  rc = unix_socket_status(sun, quickp);
+  if (rc == STALE) unlink(sun->sun_path);
   return (rc);
 }
 
@@ -646,75 +756,155 @@ static int encode_unused_inet_addr(struct sockaddr *sa,
                                   struct sockaddr_un *sun,
                                   int desperatep)
 {
-  address waddr;
+  address waddr, maddr;
   struct sockaddr_un wsun;
-  int rc;
-  char buf[ADDRBUFSZ];
+  int port = port_from_sockaddr(sa);
 
-  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);
+  /* 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.)
+   */
+  if (encode_single_inet_addr(sa, sun, !desperatep)&USED)
+    return (-1);
 
+  /* 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));
-  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);
+  port_to_sockaddr(&waddr.sa, port);
+  if (encode_single_inet_addr(&waddr.sa, &wsun, !desperatep)&USED)
+    return (-1);
+
+  /* We're not done yet.  If this is an IPv4 address, then /also/ check (a)
+   * the v6-mapped version, (b) the v6-mapped v4 wildcard, /and/ (c) the v6
+   * wildcard.  Ugh!
+   */
+  if (sa->sa_family == AF_INET) {
+    map_ipv4_sockaddr(&maddr.sin6, SIN(&sa));
+    if (encode_single_inet_addr(&maddr.sa, &wsun, !desperatep)&USED)
+      return (-1);
+
+    map_ipv4_sockaddr(&maddr.sin6, &waddr.sin);
+    if (encode_single_inet_addr(&maddr.sa, &wsun, !desperatep)&USED)
+      return (-1);
 
+    wildcard_address(AF_INET6, &waddr.sa);
+    port_to_sockaddr(&waddr.sa, port);
+    if (encode_single_inet_addr(&waddr.sa, &wsun, !desperatep)&USED)
+      return (-1);
+  }
+
+  /* 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
+#define ENCF_REUSEADDR 2u
 static int encode_inet_addr(struct sockaddr_un *sun,
                            const struct sockaddr *sa,
-                           int want)
+                           unsigned f)
 {
   int i;
   int desperatep = 0;
   address addr;
-  char buf[ADDRBUFSZ];
+  struct sockaddr_in6 sin6;
+  int port = port_from_sockaddr(sa);
   int rc;
+  char buf[ADDRBUFSZ];
 
   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) {
-    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 (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.
+     */
+    rc = encode_single_inet_addr(sa, sun, 0);
+    if ((f&ENCF_REUSEADDR) && !(rc&LISTEN)) unlink(sun->sun_path);
+    if ((rc&USED) || (f&ENCF_FRESH)) goto found;
+
+    /* We're looking for a socket which already exists.  This is
+     * unfortunately difficult, because we must deal both with wildcards and
+     * v6-mapped IPv4 addresses.
+     *
+     *   * We've just tried searching for a socket whose name is an exact
+     *    match for our remote address.  If the remote address is IPv4, then
+     *    we should try again with the v6-mapped equivalent.
+     *
+     *   * Failing that, we try again with the wildcard address for the
+     *    appropriate address family.
+     *
+     *   * Failing /that/, if the remote address is IPv4, then we try
+     *    /again/, increasingly desperately, first with the v6-mapped IPv4
+     *    wildcard address, and then with the IPv6 wildcard address.  This
+     *    will cause magic v6-mapping to occur when the connection is
+     *    accepted, which we hope won't cause too much trouble.
+     */
+
+    if (sa->sa_family == AF_INET) {
+      map_ipv4_sockaddr(&addr.sin6, SIN(sa));
+      if (encode_single_inet_addr(&addr.sa, sun, 0)&USED) goto found;
     }
+
+    wildcard_address(sa->sa_family, &addr.sa);
+    port_to_sockaddr(&addr.sa, port);
+    if (encode_single_inet_addr(&addr.sa, sun, 0)&USED) goto found;
+
+    if (sa->sa_family == AF_INET) {
+      map_ipv4_sockaddr(&sin6, &addr.sin);
+      if (encode_single_inet_addr(SA(&sin6), sun, 0)&USED) goto found;
+      wildcard_address(AF_INET6, &addr.sa);
+      port_to_sockaddr(&addr.sa, port);
+      if (encode_single_inet_addr(&addr.sa, sun, 0)&USED) goto found;
+    }
+
+    /* Well, this isn't going to work (unless a miraculous race is lost), but
+     * we might as well try.
+     */
+    encode_single_inet_addr(sa, sun, 1);
+
   } 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,50 +1015,30 @@ static int fixup_real_ip_socket(int sk, int af_hint, int *tmp)
   return (0);
 }
 
-/* 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.
- */
-static int do_implicit_bind(int sk, const struct sockaddr **sa,
-                           socklen_t *len, struct sockaddr_un *sun)
-{
-  address addr;
-  socklen_t mylen = sizeof(*sun);
-
-  if (acl_allows_p(connect_real, *sa)) {
-    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) {
-      if (mylen < sizeof(*sun)) ((char *)sun)[mylen] = 0;
-      if (!sun->sun_path[0]) {
-       wildcard_address((*sa)->sa_family, &addr.sa);
-       encode_inet_addr(sun, &addr.sa, WANT_FRESH);
-       if (real_bind(sk, SA(sun), SUN_LEN(sun))) return (-1);
-      }
-      encode_inet_addr(sun, *sa, WANT_EXISTING);
-      *sa = SA(sun);
-      *len = SUN_LEN(sun);
-    }
-  }
-  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.
  */
+#define FNF_V6MAPPED 1u
 static void return_fake_name(struct sockaddr *sa, socklen_t len,
-                            struct sockaddr *fake, socklen_t *fakelen)
+                            struct sockaddr *fake, socklen_t *fakelen,
+                            unsigned f)
 {
   address addr;
+  struct sockaddr_in6 sin6;
   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);
+    if (addr.sa.sa_family != AF_INET || !(f&FNF_V6MAPPED)) {
+      sa = &addr.sa;
+      len = family_socklen(addr.sa.sa_family);
+    } else {
+      map_ipv4_sockaddr(&sin6, &addr.sin);
+      sa = SA(&sin6);
+      len = family_socklen(AF_INET6);
+    }
   }
   alen = len;
   if (len > *fakelen) len = *fakelen;
@@ -876,6 +1046,156 @@ static void return_fake_name(struct sockaddr *sa, socklen_t len,
   *fakelen = alen;
 }
 
+/* Variant of `return_fake_name' above, specifically handling the weirdness
+ * of remote v6-mapped IPv4 addresses.  If SK's fake local address is IPv6,
+ * and the remote address is IPv4, then return a v6-mapped version of the
+ * remote address.
+ */
+static void return_fake_peer(int sk, struct sockaddr *sa, socklen_t len,
+                            struct sockaddr *fake, socklen_t *fakelen)
+{
+  char sabuf[1024];
+  socklen_t mylen = sizeof(sabuf);
+  unsigned fnf = 0;
+  address addr;
+  int rc;
+
+  PRESERVING_ERRNO({
+    rc = real_getsockname(sk, SA(sabuf), &mylen);
+    if (!rc && sa->sa_family == AF_UNIX &&
+       !decode_inet_addr(&addr.sa, 0, SUN(sabuf), mylen) &&
+       addr.sa.sa_family == AF_INET6)
+      fnf |= FNF_V6MAPPED;
+  });
+  return_fake_name(sa, len, fake, fakelen, fnf);
+}
+
+/*----- 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.
+ *
+ * If the flag `IBF_V6MAPPED' is set then, then SA must be an `AF_INET'
+ * address; after deciding on the appropriate local address, convert it to be
+ * an IPv4-mapped IPv6 address before final conversion to a Unix-domain
+ * socket address and actually binding.  Note that this could well mean that
+ * the socket ends up bound to the v6-mapped v4 wildcard address
+ * ::ffff:0.0.0.0, which looks very strange but is meaningful.
+ */
+#define IBF_V6MAPPED 1u
+static int do_implicit_bind(int sk, const struct sockaddr *sa, unsigned f)
+{
+  address addr;
+  struct sockaddr_in6 sin6;
+  struct sockaddr_un sun;
+  const impbind *i;
+  Dpid;
+
+  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;
+      switch (i->how) {
+       case EXPLICIT: ipaddr_to_sockaddr(&addr.sa, &i->bindaddr); break;
+       case SAME: copy_sockaddr(&addr.sa, sa); break;
+      }
+      port_to_sockaddr(&addr.sa, 0);
+      goto found;
+    }
+  }
+  D( fprintf(stderr, "noip(%d): no match; using wildcard\n", pid); )
+  wildcard_address(sa->sa_family, &addr.sa);
+found:
+  if (addr.sa.sa_family != AF_INET || !(f&IBF_V6MAPPED)) sa = &addr.sa;
+  else { map_ipv4_sockaddr(&sin6, &addr.sin); sa = SA(&sin6); }
+  encode_inet_addr(&sun, sa, ENCF_FRESH);
+  D( fprintf(stderr, "noip(%d): implicitly binding to %s\n",
+            pid, sun.sun_path); )
+  if (real_bind(sk, SA(&sun), SUN_LEN(&sun))) return (-1);
+  return (0);
+}
+
+/* The socket SK is about to communicate with the remote address *SA.  Ensure
+ * that the socket has a local address, and adjust *SA to refer to the real
+ * remote endpoint.
+ *
+ * If we need to translate the remote address, then the Unix-domain endpoint
+ * address will end in *SUN, and *SA will be adjusted to point to it.
+ */
+static int fixup_client_socket(int sk, const struct sockaddr **sa_r,
+                              socklen_t *len_r, struct sockaddr_un *sun)
+{
+  struct sockaddr_in sin;
+  socklen_t mylen = sizeof(*sun);
+  const struct sockaddr *sa = *sa_r;
+  unsigned ibf = 0;
+
+  /* If this isn't a Unix-domain socket then there's nothing to do. */
+  if (real_getsockname(sk, SA(sun), &mylen) < 0) return (-1);
+  if (sun->sun_family != AF_UNIX) return (0);
+  if (mylen < sizeof(*sun)) ((char *)sun)[mylen] = 0;
+
+  /* If the remote address is v6-mapped IPv4, then unmap it so as to search
+   * for IPv4 servers.  Also remember to v6-map the local address when we
+   * autobind.
+   */
+  if (sa->sa_family == AF_INET6 && !(unmap_ipv4_sockaddr(&sin, SIN6(sa)))) {
+    sa = SA(&sin);
+    ibf |= IBF_V6MAPPED;
+  }
+
+  /* If we're allowed to talk to a real remote endpoint, then fix things up
+   * as necessary and proceed.
+   */
+  if (acl_allows_p(connect_real, sa)) {
+    if (fixup_real_ip_socket(sk, (*sa_r)->sa_family, 0)) return (-1);
+    return (0);
+  }
+
+  /* Speaking of which, if we don't have a local address, then we should
+   * arrange one now.
+   */
+  if (!sun->sun_path[0] && do_implicit_bind(sk, sa, ibf)) return (-1);
+
+  /* And then come up with a remote address. */
+  encode_inet_addr(sun, sa, 0);
+  *sa_r = SA(sun);
+  *len_r = SUN_LEN(sun);
+  return (0);
+}
+
 /*----- Configuration -----------------------------------------------------*/
 
 /* Return the process owner's home directory. */
@@ -1159,6 +1479,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 +1565,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 +1589,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 +1621,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 +1653,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 -------------------------------------------*/
@@ -1329,6 +1734,9 @@ int bind(int sk, const struct sockaddr *sa, socklen_t len)
 {
   struct sockaddr_un sun;
   int rc;
+  unsigned f;
+  int reusep;
+  socklen_t n;
   Dpid;
 
   D({ char buf[ADDRBUFSZ];
@@ -1344,7 +1752,11 @@ 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);
+       f = ENCF_FRESH;
+       n = sizeof(reusep);
+       if (!getsockopt(sk, SOL_SOCKET, SO_REUSEADDR, &reusep, &n) && reusep)
+         f |= ENCF_REUSEADDR;
+       encode_inet_addr(&sun, sa, f);
        sa = SA(&sun);
        len = SUN_LEN(&sun);
       }
@@ -1372,7 +1784,7 @@ int connect(int sk, const struct sockaddr *sa, socklen_t len)
   } else {
     D( fprintf(stderr, " -> checking...\n"); )
     PRESERVING_ERRNO({
-      do_implicit_bind(sk, &sa, &len, &sun);
+      fixup_client_socket(sk, &sa, &len, &sun);
     });
     D( fprintf(stderr, "noip(%d): CONNECT ...", pid); )
     rc = real_connect(sk, sa, len);
@@ -1405,7 +1817,7 @@ ssize_t sendto(int sk, const void *buf, size_t len, int flags,
   else {
     D( fprintf(stderr, " -> checking...\n"); )
     PRESERVING_ERRNO({
-      do_implicit_bind(sk, &to, &tolen, &sun);
+      fixup_client_socket(sk, &to, &tolen, &sun);
     });
     D( fprintf(stderr, "noip(%d): SENDTO ...", pid); )
   }
@@ -1429,14 +1841,14 @@ ssize_t recvfrom(int sk, void *buf, size_t len, int flags,
     D( fprintf(stderr, " -> null addr; pass through"); )
     n = real_recvfrom(sk, buf, len, flags, 0, 0);
   } else {
-    PRESERVING_ERRNO({
-      n = real_recvfrom(sk, buf, len, flags, SA(sabuf), &mylen);
-      if (n >= 0) {
-       D( fprintf(stderr, " -> converting...\n"); )
-       return_fake_name(SA(sabuf), mylen, from, fromlen);
-       D( fprintf(stderr, "noip(%d): ... RECVFROM", pid); )
-      }
-    });
+    n = real_recvfrom(sk, buf, len, flags, SA(sabuf), &mylen);
+    if (n >= 0) {
+      D( fprintf(stderr, " -> converting...\n"); )
+      PRESERVING_ERRNO({
+       return_fake_peer(sk, SA(sabuf), mylen, from, fromlen);
+      });
+      D( fprintf(stderr, "noip(%d): ... RECVFROM", pid); )
+    }
   }
   D( dump_addrresult(n, from, fromlen ? *fromlen : 0); )
   return (n);
@@ -1465,7 +1877,7 @@ ssize_t sendmsg(int sk, const struct msghdr *msg, int flags)
     D( fprintf(stderr, " -> checking...\n"); )
     PRESERVING_ERRNO({
       mymsg = *msg;
-      do_implicit_bind(sk, &sa, &mymsg.msg_namelen, &sun);
+      fixup_client_socket(sk, &sa, &mymsg.msg_namelen, &sun);
       mymsg.msg_name = SA(sa);
       msg = &mymsg;
     });
@@ -1491,18 +1903,18 @@ ssize_t recvmsg(int sk, struct msghdr *msg, int flags)
     D( fprintf(stderr, " -> null addr; pass through"); )
     return (real_recvmsg(sk, msg, flags));
   } else {
-    PRESERVING_ERRNO({
-      msg->msg_name = sabuf;
-      msg->msg_namelen = sizeof(sabuf);
-      n = real_recvmsg(sk, msg, flags);
-      if (n >= 0) {
-       D( fprintf(stderr, " -> converting...\n"); )
-       return_fake_name(SA(sabuf), msg->msg_namelen, sa, &len);
-       D( fprintf(stderr, "noip(%d): ... RECVMSG", pid); )
-      }
-      msg->msg_name = sa;
-      msg->msg_namelen = len;
-    });
+    msg->msg_name = sabuf;
+    msg->msg_namelen = sizeof(sabuf);
+    n = real_recvmsg(sk, msg, flags);
+    if (n >= 0) {
+      D( fprintf(stderr, " -> converting...\n"); )
+      PRESERVING_ERRNO({
+       return_fake_peer(sk, SA(sabuf), msg->msg_namelen, sa, &len);
+      });
+    }
+    D( fprintf(stderr, "noip(%d): ... RECVMSG", pid); )
+    msg->msg_name = sa;
+    msg->msg_namelen = len;
   }
   D( dump_addrresult(n, sa, len); )
   return (n);
@@ -1522,7 +1934,7 @@ int accept(int sk, struct sockaddr *sa, socklen_t *len)
   else if (!sa) D( fprintf(stderr, " -> address not wanted"); )
   else {
     D( fprintf(stderr, " -> converting...\n"); )
-    return_fake_name(SA(sabuf), mylen, sa, len);
+    return_fake_peer(sk, SA(sabuf), mylen, sa, len);
     D( fprintf(stderr, "noip(%d): ... ACCEPT", pid); )
   }
   D( dump_addrresult(nsk, sa, len ? *len : 0); )
@@ -1531,50 +1943,47 @@ 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, 0);
+    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_peer(sk, SA(sabuf), mylen, sa, len);
+    D( fprintf(stderr, "noip(%d): ... GETPEERNAME", pid); )
+  }
   D( dump_addrresult(rc, sa, *len); )
-  return (0);
+  return (rc);
 }
 
 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 +1994,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) {