noip.c: Factor out the non-implicit-binding parts of `do_implicit_bind'.
[preload-hacks] / noip.c
diff --git a/noip.c b/noip.c
index 37ec33c..fd86cb3 100644 (file)
--- a/noip.c
+++ b/noip.c
@@ -641,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;
@@ -661,9 +674,28 @@ static int unix_socket_status(struct sockaddr_un *sun, int quickp)
   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)));
+  if ((rc = unix_socket_status(sun, quickp)) == USED) return (USED);
+  else if (rc == STALE) unlink(sun->sun_path);
+  return (UNUSED);
+}
+
 /* Convert the IP address SA to a Unix-domain address SUN.  Fail if the
  * address seems already taken.  If DESPARATEP then try cleaning up stale old
  * sockets.
@@ -674,22 +706,24 @@ static int encode_unused_inet_addr(struct sockaddr *sa,
 {
   address waddr;
   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);
-  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);
+  if (encode_single_inet_addr(&waddr.sa, &wsun, !desperatep) == USED)
+    return (-1);
 
+  /* All is well. */
   return (0);
 }
 
@@ -709,41 +743,60 @@ static int encode_inet_addr(struct sockaddr_un *sun,
   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)),
             (f&ENCF_FRESH) ? "FRESH" : "EXISTING"); )
+
+  /* Start making the Unix-domain address. */
   sun->sun_family = AF_UNIX;
+
   if (port || !(f&ENCF_FRESH)) {
-    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 && !(f&ENCF_FRESH)) {
-      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);
-    }
+
+    /* Try the address as given.  If it's in use, or we don't necessarily
+     * want an existing socket, then we're done.
+     */
+    if (encode_single_inet_addr(sa, sun, 0) == 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);
+    encode_single_inet_addr(&addr.sa, sun, 0);
+
   } 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);
 }
@@ -910,43 +963,67 @@ static void dump_impbind_list(void)
  * 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)
+static int do_implicit_bind(int sk, const struct sockaddr *sa)
 {
   address addr;
-  socklen_t mylen = sizeof(*sun);
+  struct sockaddr_un sun;
   const impbind *i;
   Dpid;
 
-  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]) {
-       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);
-      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, 0);
-      *sa = SA(sun);
-      *len = SUN_LEN(sun);
+  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);
+found:
+  encode_inet_addr(&sun, &addr.sa, ENCF_FRESH);
+  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)
+{
+  socklen_t mylen = sizeof(*sun);
+  const struct sockaddr *sa = *sa_r;
+
+  /* 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);
+  }
+
+  /* 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;
+
+  /* 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)) 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);
 }
 
@@ -1531,7 +1608,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);
@@ -1564,7 +1641,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); )
   }
@@ -1624,7 +1701,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;
     });
@@ -1690,40 +1767,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);
 }
@@ -1732,6 +1805,7 @@ int getsockopt(int sk, int lev, int opt, void *p, socklen_t *len)
 {
   switch (lev) {
     case IPPROTO_IP:
+    case IPPROTO_IPV6:
     case IPPROTO_TCP:
     case IPPROTO_UDP:
       if (*len > 0)
@@ -1745,6 +1819,7 @@ int setsockopt(int sk, int lev, int opt, const void *p, socklen_t len)
 {
   switch (lev) {
     case IPPROTO_IP:
+    case IPPROTO_IPV6:
     case IPPROTO_TCP:
     case IPPROTO_UDP:
       return (0);