* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
- * Preload-hacks distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
- * more details.
+ * Preload-hacks are distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * for more details.
*
* You should have received a copy of the GNU General Public License along
- * with mLib; if not, write to the Free Software Foundation, Inc., 59 Temple
- * Place - Suite 330, Boston, MA 02111-1307, USA.
+ * with preload-hacks; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#define _GNU_SOURCE
/*----- Header files ------------------------------------------------------*/
+#include <assert.h>
#include <ctype.h>
#include <errno.h>
+#include <stdarg.h>
+#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <netinet/tcp.h>
#include <netinet/udp.h>
-#include <net/if.h>
+#include <ifaddrs.h>
+#include <netdb.h>
/*----- 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 };
+
+#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 */
typedef struct aclnode {
struct aclnode *next;
int act;
- unsigned long minaddr, maxaddr;
+ int af;
+ ipaddr minaddr, maxaddr;
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;
+ union {
+ struct { int af; ipaddr min, max; } range;
+ } u;
+} addrrange;
+enum { EMPTY, ANY, LOCAL, RANGE };
+
/* Local address records */
-#define MAX_LOCAL_IPADDRS 16
-static struct in_addr local_ipaddrs[MAX_LOCAL_IPADDRS];
+typedef struct full_ipaddr {
+ int af;
+ ipaddr addr;
+} full_ipaddr;
+#define MAX_LOCAL_IPADDRS 64
+static full_ipaddr local_ipaddrs[MAX_LOCAL_IPADDRS];
static int n_local_ipaddrs;
/* General configuration */
/* 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 -----------------------------*/
_(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;
/* 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 */
/* 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 */
memcpy(q, p, n);
return (q);
}
+
+/*----- Address-type hacking ----------------------------------------------*/
+
+/* If M is a simple mask, i.e., consists of a sequence of zero bits followed
+ * by a sequence of one bits, then return the length of the latter sequence
+ * (which may be zero); otherwise return -1.
+ */
+static int simple_mask_length(unsigned long m)
+{
+ int n = 0;
+
+ while (m & 1) { n++; m >>= 1; }
+ return (m ? -1 : n);
+}
+
+/* Answer whether AF is an interesting address family. */
+static int family_known_p(int af)
+{
+ switch (af) {
+ case AF_INET:
+ case AF_INET6:
+ return (1);
+ default:
+ return (0);
+ }
+}
+
+/* Return the socket address length for address family AF. */
+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();
+ }
+}
+
+/* Return the width of addresses of kind AF. */
+static int address_width(int af)
+{
+ switch (af) {
+ case AF_INET: return 32;
+ case AF_INET6: return 128;
+ default: abort();
+ }
+}
+
+/* If addresses A and B share a common prefix then return its length;
+ * otherwise return -1.
+ */
+static int common_prefix_length(int af, const ipaddr *a, const ipaddr *b)
+{
+ switch (af) {
+ case AF_INET: {
+ unsigned long aa = ntohl(a->v4.s_addr), bb = ntohl(b->v4.s_addr);
+ unsigned long m = aa^bb;
+ 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();
+ }
+}
+
+/* Extract the port number (in host byte-order) from SA. */
+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();
+ }
+}
+
+/* Store the port number PORT (in host byte-order) in SA. */
+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();
+ }
+}
+
+/* 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)
+{
+ 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();
+ }
+}
+
+/* Answer whether the address part of SA is between A and B (inclusive). We
+ * assume that SA has the correct address family.
+ */
+static int sockaddr_in_range_p(const struct sockaddr *sa,
+ const ipaddr *a, const ipaddr *b)
+{
+ switch (sa->sa_family) {
+ case AF_INET: {
+ unsigned long addr = ntohl(SIN(sa)->sin_addr.s_addr);
+ 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();
+ }
+}
+
+/* Fill in SA with the appropriate wildcard address. */
+static void wildcard_address(int af, struct sockaddr *sa)
+{
+ switch (af) {
+ case AF_INET: {
+ struct sockaddr_in *sin = SIN(sa);
+ memset(sin, 0, sizeof(*sin));
+ sin->sin_family = AF_INET;
+ 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();
+ }
+}
+
+/* Mask the address A, forcing all but the top PLEN bits to zero or one
+ * according to HIGHP.
+ */
+static void mask_address(int af, ipaddr *a, int plen, int highp)
+{
+ switch (af) {
+ case AF_INET: {
+ unsigned long addr = ntohl(a->v4.s_addr);
+ unsigned long mask = plen ? ~0ul << (32 - plen) : 0;
+ addr &= mask;
+ 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();
+ }
+}
+
+/* Write a presentation form of SA to BUF, a buffer of length SZ. LEN is the
+ * address length; if it's zero, look it up based on the address family.
+ * Return a pointer to the string (which might, in an emergency, be a static
+ * string rather than your buffer).
+ */
+static char *present_sockaddr(const struct sockaddr *sa, socklen_t len,
+ char *buf, size_t sz)
+{
+#define WANT(n_) do { if (sz < (n_)) goto nospace; } while (0)
+#define PUTC(c_) do { *buf++ = (c_); sz--; } while (0)
+
+ if (!sa) return "<null-address>";
+ if (!sz) return "<no-space-in-buffer>";
+ if (!len) len = family_socklen(sa->sa_family);
+
+ switch (sa->sa_family) {
+ case AF_UNIX: {
+ struct sockaddr_un *sun = SUN(sa);
+ char *p = sun->sun_path;
+ size_t n = len - offsetof(struct sockaddr_un, sun_path);
+
+ assert(n);
+ if (*p == 0) {
+ WANT(1); PUTC('@');
+ p++; n--;
+ while (n) {
+ switch (*p) {
+ case 0: WANT(2); PUTC('\\'); PUTC('0'); break;
+ case '\a': WANT(2); PUTC('\\'); PUTC('a'); break;
+ case '\n': WANT(2); PUTC('\\'); PUTC('n'); break;
+ case '\r': WANT(2); PUTC('\\'); PUTC('r'); break;
+ case '\t': WANT(2); PUTC('\\'); PUTC('t'); break;
+ case '\v': WANT(2); PUTC('\\'); PUTC('v'); break;
+ case '\\': WANT(2); PUTC('\\'); PUTC('\\'); break;
+ default:
+ if (*p > ' ' && *p <= '~')
+ { WANT(1); PUTC(*p); }
+ else {
+ WANT(4); PUTC('\\'); PUTC('x');
+ PUTC((*p >> 4)&0xf); PUTC((*p >> 0)&0xf);
+ }
+ break;
+ }
+ p++; n--;
+ }
+ } else {
+ if (*p != '/') { WANT(2); PUTC('.'); PUTC('/'); }
+ while (n && *p) { WANT(1); PUTC(*p); p++; n--; }
+ }
+ WANT(1); PUTC(0);
+ } break;
+ case AF_INET: case AF_INET6: {
+ char addrbuf[NI_MAXHOST], portbuf[NI_MAXSERV];
+ int err = getnameinfo(sa, len,
+ addrbuf, sizeof(addrbuf),
+ portbuf, sizeof(portbuf),
+ NI_NUMERICHOST | NI_NUMERICSERV);
+ assert(!err);
+ snprintf(buf, sz, strchr(addrbuf, ':') ? "[%s]:%s" : "%s:%s",
+ addrbuf, portbuf);
+ } break;
+ default:
+ snprintf(buf, sz, "<unknown-address-family %d>", sa->sa_family);
+ break;
+ }
+ return (buf);
+
+nospace:
+ buf[sz - 1] = 0;
+ return (buf);
+}
+
+/* Guess the family of a textual socket address. */
+static int guess_address_family(const char *p)
+ { 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)
+{
+ char buf[ADDRBUFSZ];
+ char *q;
+ struct addrinfo *ai, ai_hint = { 0 };
+
+ if (strlen(p) >= sizeof(buf) - 1) return (-1);
+ strcpy(buf, p); p = buf;
+ if (*p != '[') {
+ if ((q = strchr(p, ':')) == 0) return (-1);
+ *q++ = 0;
+ } else {
+ p++;
+ if ((q = strchr(p, ']')) == 0) return (-1);
+ *q++ = 0;
+ if (*q != ':') return (-1);
+ q++;
+ }
+
+ ai_hint.ai_family = AF_UNSPEC;
+ ai_hint.ai_socktype = SOCK_DGRAM;
+ ai_hint.ai_flags = AI_NUMERICHOST | AI_NUMERICSERV;
+ if (getaddrinfo(p, q, &ai_hint, &ai)) return (-1);
+ memcpy(sa, ai->ai_addr, ai->ai_addrlen);
+ freeaddrinfo(ai);
+ return (0);
+}
+
/*----- Access control lists ----------------------------------------------*/
#ifdef DEBUG
-/* Write to standard error a description of the ACL node A. */
-static void dump_aclnode(aclnode *a)
+static void dump_addrrange(int af, const ipaddr *min, const ipaddr *max)
{
- char minbuf[16], maxbuf[16];
- struct in_addr amin, amax;
+ char buf[ADDRBUFSZ];
+ const char *p;
+ int plen;
+
+ plen = common_prefix_length(af, min, max);
+ p = inet_ntop(af, min, buf, sizeof(buf));
+ fprintf(stderr, strchr(p, ':') ? "[%s]" : "%s", p);
+ if (plen < 0) {
+ p = inet_ntop(af, &max, buf, sizeof(buf));
+ fprintf(stderr, strchr(p, ':') ? "-[%s]" : "-%s", p);
+ } else if (plen < address_width(af))
+ fprintf(stderr, "/%d", plen);
+}
- amin.s_addr = htonl(a->minaddr);
- amax.s_addr = htonl(a->maxaddr);
- fprintf(stderr, "noip: %c ", a->act ? '+' : '-');
- if (a->minaddr == 0 && a->maxaddr == 0xffffffff)
- fprintf(stderr, "any");
- else {
- fprintf(stderr, "%s",
- inet_ntop(AF_INET, &amin, minbuf, sizeof(minbuf)));
- if (a->maxaddr != a->minaddr) {
- fprintf(stderr, "-%s",
- inet_ntop(AF_INET, &amax, maxbuf, sizeof(maxbuf)));
- }
- }
+/* Write to standard error a description of the ACL node A. */
+static void dump_aclnode(const aclnode *a)
+{
+ fprintf(stderr, "noip(%d): %c ", getpid(), a->act ? '+' : '-');
+ dump_addrrange(a->af, &a->minaddr, &a->maxaddr);
if (a->minport != 0 || a->maxport != 0xffff) {
fprintf(stderr, ":%u", (unsigned)a->minport);
if (a->minport != a->maxport)
fputc('\n', stderr);
}
-static void dump_acl(aclnode *a)
+static void dump_acl(const aclnode *a)
{
int act = ALLOW;
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 IP socket SIN. */
-static int acl_allows_p(aclnode *a, const struct sockaddr_in *sin)
+/* Returns nonzero if the ACL A allows the socket address SA. */
+static int acl_allows_p(const aclnode *a, const struct sockaddr *sa)
{
- unsigned long addr = ntohl(sin->sin_addr.s_addr);
- unsigned short port = ntohs(sin->sin_port);
+ unsigned short port = port_from_sockaddr(sa);
int act = ALLOW;
+ Dpid;
- D( char buf[16];
- fprintf(stderr, "noip: check %s:%u\n",
- inet_ntop(AF_INET, &sin->sin_addr, buf, sizeof(buf)),
- ntohs((unsigned)sin->sin_port)); )
+ D({ char buf[ADDRBUFSZ];
+ 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 (a->minaddr <= addr && addr <= 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: 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);
}
unsigned mask, i;
/* It's so nice not to have to care about the quality of the generator
- much! */
+ * much!
+ */
max -= min;
for (mask = 1; mask < max; mask = (mask << 1) | 1)
;
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;
rc = STALE;
done:
if (fp) fclose(fp);
+
+ /* All done. */
return (rc);
}
-/* Encode the Internet address SIN as a Unix-domain address SUN. If WANT is
- * WANT_FRESH, and SIN->sin_port 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 INADDR_ANY. Returns zero on success; -1 on failure.
+/* 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.
+ */
+static int encode_unused_inet_addr(struct sockaddr *sa,
+ struct sockaddr_un *sun,
+ int desperatep)
+{
+ address waddr, maddr;
+ struct sockaddr_un wsun;
+ 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.)
+ */
+ 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);
+ 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 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_in *sin,
- int want)
+ const struct sockaddr *sa,
+ unsigned f)
{
int i;
int desperatep = 0;
- char buf[INET_ADDRSTRLEN];
- int rc;
+ address addr;
+ struct sockaddr_in6 sin6;
+ int port = port_from_sockaddr(sa);
+ char buf[ADDRBUFSZ];
+
+ D( fprintf(stderr, "noip(%d): encode %s (%s)", getpid(),
+ present_sockaddr(sa, 0, buf, sizeof(buf)),
+ (f&ENCF_FRESH) ? "FRESH" : "EXISTING"); )
- D( fprintf(stderr, "noip: encode %s:%u (%s)",
- inet_ntop(AF_INET, &sin->sin_addr, buf, sizeof(buf)),
- (unsigned)ntohs(sin->sin_port),
- want == WANT_EXISTING ? "EXISTING" : "FRESH"); )
+ /* Start making the Unix-domain address. */
sun->sun_family = AF_UNIX;
- if (sin->sin_port || want == WANT_EXISTING) {
- snprintf(sun->sun_path, sizeof(sun->sun_path), "%s/%s:%u", sockdir,
- inet_ntop(AF_INET, &sin->sin_addr, buf, sizeof(buf)),
- (unsigned)ntohs(sin->sin_port));
- rc = unix_socket_status(sun, 0);
- if (rc == STALE) unlink(sun->sun_path);
- if (rc != USED && want == WANT_EXISTING) {
- snprintf(sun->sun_path, sizeof(sun->sun_path), "%s/0.0.0.0:%u",
- sockdir, (unsigned)ntohs(sin->sin_port));
- 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.
+ */
+ if (encode_single_inet_addr(sa, sun, 0) == 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++) {
- snprintf(sun->sun_path, sizeof(sun->sun_path), "%s/%s:%u", sockdir,
- inet_ntop(AF_INET, &sin->sin_addr, buf, sizeof(buf)),
- randrange(minautoport, maxautoport));
- if (unix_socket_status(sun, 1) == UNUSED) goto found;
+ 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++) {
- snprintf(sun->sun_path, sizeof(sun->sun_path), "%s/%s:%u", sockdir,
- inet_ntop(AF_INET, &sin->sin_addr, buf, sizeof(buf)),
- (unsigned)i);
- rc = unix_socket_status(sun, !desperatep);
- switch (rc) {
- case STALE: unlink(sun->sun_path);
- case UNUSED: goto found;
- }
+ 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);
}
-/* Decode the Unix address SUN to an Internet address SIN. If
- * DECODE_UNBOUND_P is nonzero, an empty address (indicative of an unbound
- * Unix-domain socket) is translated to a wildcard Internet address. Returns
- * zero on success; -1 on failure (e.g., it wasn't one of our addresses).
+/* 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) 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_in *sin,
+static int decode_inet_addr(struct sockaddr *sa, int af_hint,
const struct sockaddr_un *sun,
- socklen_t len,
- int decode_unbound_p)
+ socklen_t len)
{
- char buf[INET_ADDRSTRLEN + 16];
- char *p;
+ char buf[ADDRBUFSZ];
size_t n = strlen(sockdir), nn;
- struct sockaddr_in sin_mine;
- unsigned long port;
+ address addr;
- if (!sin)
- sin = &sin_mine;
- if (sun->sun_family != AF_UNIX)
- return (-1);
+ if (!sa) sa = &addr.sa;
+ if (sun->sun_family != AF_UNIX) return (-1);
+ if (len > sizeof(*sun)) return (-1);
+ ((char *)sun)[len] = 0;
nn = strlen(sun->sun_path);
- if (len < sizeof(sun)) ((char *)sun)[len] = 0;
- D( fprintf(stderr, "noip: decode (%d) `%s'",
- *sun->sun_path, sun->sun_path); )
- if (decode_unbound_p && !sun->sun_path[0]) {
- sin->sin_family = AF_INET;
- sin->sin_addr.s_addr = INADDR_ANY;
- sin->sin_port = 0;
+ 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"); )
return (0);
}
D( fprintf(stderr, " -- not one of ours\n"); )
return (-1);
}
- memcpy(buf, sun->sun_path + n + 1, nn - n);
- if ((p = strchr(buf, ':')) == 0) {
- D( fprintf(stderr, " -- malformed (no port)\n"); )
- return (-1);
- }
- *p++ = 0;
- sin->sin_family = AF_INET;
- if (inet_pton(AF_INET, buf, &sin->sin_addr) <= 0) {
- D( fprintf(stderr, " -- malformed (bad address `%s')\n", buf); )
- return (-1);
- }
- port = strtoul(p, &p, 10);
- if (*p || port >= 65536) {
- D( fprintf(stderr, " -- malformed (port out of range)"); )
- return (-1);
- }
- sin->sin_port = htons(port);
- D( fprintf(stderr, " -> %s:%u\n",
- inet_ntop(AF_INET, &sin->sin_addr, buf, sizeof(buf)),
- (unsigned)port); )
+ if (parse_sockaddr(sa, sun->sun_path + n + 1)) return (-1);
+ D( fprintf(stderr, " -> %s\n",
+ present_sockaddr(sa, 0, buf, sizeof(buf))); )
return (0);
}
/* 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, 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)
+static int fixup_real_ip_socket(int sk, int af_hint, int *tmp)
{
int nsk;
int type;
int f, fd;
struct sockaddr_un sun;
- struct sockaddr_in sin;
+ address addr;
socklen_t len;
#define OPTS(_) \
len = sizeof(sun);
if (real_getsockname(sk, SA(&sun), &len))
return (-1);
- if (decode_inet_addr(&sin, &sun, len, 1))
+ if (decode_inet_addr(&addr.sa, af_hint, &sun, len))
return (0); /* Not one of ours */
len = sizeof(type);
if (real_getsockopt(sk, SOL_SOCKET, SO_TYPE, &type, &len) < 0 ||
- (nsk = real_socket(PF_INET, type, 0)) < 0)
+ (nsk = real_socket(addr.sa.sa_family, type, 0)) < 0)
return (-1);
#define FIX(opt, ty) do { \
ty ov_; \
} 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) {
- 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();
- }
- 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 does something useful.
- */
-static int do_implicit_bind(int sk, const struct sockaddr **sa,
- socklen_t *len, struct sockaddr_un *sun)
-{
- struct sockaddr_in sin;
- socklen_t mylen = sizeof(*sun);
-
- if (acl_allows_p(connect_real, SIN(*sa))) {
- if (fixup_real_ip_socket(sk))
- return (-1);
- } else {
- if (real_getsockname(sk, SA(sun), &mylen) < 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);
- if (sun->sun_family == AF_UNIX) {
- if (mylen < sizeof(*sun)) ((char *)sun)[mylen] = 0;
- if (!sun->sun_path[0]) {
- sin.sin_family = AF_INET;
- sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
- sin.sin_port = 0;
- encode_inet_addr(sun, &sin, WANT_FRESH);
- if (real_bind(sk, SA(sun), SUN_LEN(sun)))
- return (-1);
- }
- encode_inet_addr(sun, SIN(*sa), WANT_EXISTING);
- *sa = SA(sun);
- *len = SUN_LEN(sun);
+ }
+ unlink(sun.sun_path);
+ close(nsk);
+ if (fcntl(sk, F_SETFD, fd) < 0) {
+ perror("noip: fixup_real_ip_socket F_SETFD");
+ abort();
}
}
return (0);
* 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)
{
- struct sockaddr_in sin;
+ address addr;
+ struct sockaddr_in6 sin6;
socklen_t alen;
if (sa->sa_family == AF_UNIX &&
- !decode_inet_addr(&sin, SUN(sa), len, 0)) {
- sa = SA(&sin);
- len = sizeof(sin);
+ !decode_inet_addr(&addr.sa, 0, SUN(sa), len)) {
+ 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;
- if (len > 0)
- memcpy(fake, sa, len);
+ if (len > *fakelen) len = *fakelen;
+ if (len > 0) memcpy(fake, sa, 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;
+ 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:
+ 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. */
/* Set Q to point to the next dotted-quad address, store the ending delimiter
* in DEL, null-terminate it, and step P past it. */
-#define NEXTADDR(q, del) do { \
- SKIPSPC; \
- q = p; \
- while (*p && (*p == '.' || isdigit(UC(*p)))) p++; \
- del = *p; \
- if (*p) *p++ = 0; \
-} while (0)
+static void parse_nextaddr(char **pp, char **qq, int *del)
+{
+ char *p = *pp;
+
+ SKIPSPC;
+ if (*p == '[') {
+ p++; SKIPSPC;
+ *qq = p;
+ p += strcspn(p, "]");
+ if (*p) *p++ = 0;
+ *del = 0;
+ } else {
+ *qq = p;
+ while (*p && (*p == '.' || isdigit(UC(*p)))) p++;
+ *del = *p;
+ if (*p) *p++ = 0;
+ }
+ *pp = p;
+}
/* Set Q to point to the next decimal number, store the ending delimiter in
* DEL, null-terminate it, and step P past it. */
*pp = p;
}
-/* Make a new ACL node. ACT is the verdict; MINADDR and MAXADDR are the
- * ranges on IP addresses; MINPORT and MAXPORT are the ranges on port
- * numbers; TAIL is the list tail to attach the new node to.
+/* Parse an address range designator starting at PP and store a
+ * representation of it in R. An address range designator has the form:
+ *
+ * any | local | ADDR | ADDR - ADDR | ADDR/ADDR | ADDR/INT
*/
-#define ACLNODE(tail_, act_, \
- minaddr_, maxaddr_, minport_, maxport_) do { \
- aclnode *a_; \
- NEW(a_); \
- a_->act = act_; \
- a_->minaddr = minaddr_; a_->maxaddr = maxaddr_; \
- a_->minport = minport_; a_->maxport = maxport_; \
- *tail_ = a_; tail_ = &a_->next; \
-} while (0)
+static int parse_addrrange(char **pp, addrrange *r)
+{
+ char *p = *pp, *q;
+ int n;
+ int del;
+ int af;
+
+ SKIPSPC;
+ if (KWMATCHP("any")) r->type = ANY;
+ else if (KWMATCHP("local")) r->type = LOCAL;
+ else {
+ parse_nextaddr(&p, &q, &del);
+ af = guess_address_family(q);
+ if (inet_pton(af, q, &r->u.range.min) <= 0) goto bad;
+ RESCAN(del);
+ SKIPSPC;
+ if (*p == '-') {
+ p++;
+ parse_nextaddr(&p, &q, &del);
+ if (inet_pton(af, q, &r->u.range.max) <= 0) goto bad;
+ RESCAN(del);
+ } else if (*p == '/') {
+ p++;
+ NEXTNUMBER(q, del);
+ n = strtoul(q, 0, 0);
+ r->u.range.max = r->u.range.min;
+ mask_address(af, &r->u.range.min, n, 0);
+ mask_address(af, &r->u.range.max, n, 1);
+ RESCAN(del);
+ } else
+ r->u.range.max = r->u.range.min;
+ r->type = RANGE;
+ r->u.range.af = af;
+ }
+ *pp = p;
+ return (0);
+
+bad:
+ return (-1);
+}
+
+/* Call FUNC on each individual address range in R. */
+static void foreach_addrrange(const addrrange *r,
+ void (*func)(int af,
+ const ipaddr *min,
+ const ipaddr *max,
+ void *p),
+ void *p)
+{
+ ipaddr minaddr, maxaddr;
+ int i, af;
+
+ switch (r->type) {
+ case EMPTY:
+ break;
+ case ANY:
+ for (i = 0; address_families[i] >= 0; i++) {
+ af = address_families[i];
+ memset(&minaddr, 0, sizeof(minaddr));
+ maxaddr = minaddr; mask_address(af, &maxaddr, 0, 1);
+ func(af, &minaddr, &maxaddr, p);
+ }
+ break;
+ case LOCAL:
+ for (i = 0; address_families[i] >= 0; i++) {
+ af = address_families[i];
+ memset(&minaddr, 0, sizeof(minaddr));
+ maxaddr = minaddr; mask_address(af, &maxaddr, 0, 1);
+ func(af, &minaddr, &minaddr, p);
+ func(af, &maxaddr, &maxaddr, p);
+ }
+ for (i = 0; i < n_local_ipaddrs; i++) {
+ func(local_ipaddrs[i].af,
+ &local_ipaddrs[i].addr, &local_ipaddrs[i].addr,
+ p);
+ }
+ break;
+ case RANGE:
+ func(r->u.range.af, &r->u.range.min, &r->u.range.max, p);
+ break;
+ default:
+ abort();
+ }
+}
+
+struct add_aclnode_ctx {
+ int act;
+ unsigned short minport, maxport;
+ aclnode ***tail;
+};
+
+static void add_aclnode(int af, const ipaddr *min, const ipaddr *max,
+ void *p)
+{
+ struct add_aclnode_ctx *ctx = p;
+ aclnode *a;
+
+ NEW(a);
+ a->act = ctx->act;
+ a->af = af;
+ a->minaddr = *min; a->maxaddr = *max;
+ a->minport = ctx->minport; a->maxport = ctx->maxport;
+ **ctx->tail = a; *ctx->tail = &a->next;
+}
/* Parse an ACL line. *PP points to the end of the line; *TAIL points to
* the list tail (i.e., the final link in the list). An ACL entry has the
- * form +|- [any | local | ADDR | ADDR - ADDR | ADDR/ADDR | ADDR/INT] PORTS
+ * form +|- ADDR-RANGE PORTS
* where PORTS is parsed by parse_ports above; an ACL line consists of a
* comma-separated sequence of entries..
*/
static void parse_acl_line(char **pp, aclnode ***tail)
{
- struct in_addr addr;
- unsigned long minaddr, maxaddr, mask;
- unsigned short minport, maxport;
- int i, n;
- int act;
- int del;
+ struct add_aclnode_ctx ctx;
+ addrrange r;
char *p = *pp;
- char *q;
+ ctx.tail = tail;
for (;;) {
SKIPSPC;
- if (*p == '+') act = ALLOW;
- else if (*p == '-') act = DENY;
+ if (*p == '+') ctx.act = ALLOW;
+ else if (*p == '-') ctx.act = DENY;
else goto bad;
p++;
+ if (parse_addrrange(&p, &r)) goto bad;
+ parse_ports(&p, &ctx.minport, &ctx.maxport);
+ foreach_addrrange(&r, add_aclnode, &ctx);
SKIPSPC;
- if (KWMATCHP("any")) {
- minaddr = 0;
- maxaddr = 0xffffffff;
- goto justone;
- } else if (KWMATCHP("local")) {
- parse_ports(&p, &minport, &maxport);
- ACLNODE(*tail, act, 0, 0, minport, maxport);
- ACLNODE(*tail, act, 0xffffffff, 0xffffffff, minport, maxport);
- for (i = 0; i < n_local_ipaddrs; i++) {
- minaddr = ntohl(local_ipaddrs[i].s_addr);
- ACLNODE(*tail, act, minaddr, minaddr, minport, maxport);
- }
+ if (*p != ',') break;
+ if (*p) p++;
+ }
+ if (*p) goto bad;
+ *pp = p;
+ return;
+
+bad:
+ D( fprintf(stderr, "noip(%d): bad acl spec (ignored)\n", getpid()); )
+ return;
+}
+
+/* Parse an ACL from an environment variable VAR, attaching it to the list
+ * TAIL.
+ */
+static void parse_acl_env(const char *var, aclnode ***tail)
+{
+ char *p, *q;
+
+ if ((p = getenv(var)) != 0) {
+ p = q = xstrdup(p);
+ parse_acl_line(&q, tail);
+ free(p);
+ }
+}
+
+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 {
- if (*p == ':') {
- minaddr = 0;
- maxaddr = 0xffffffff;
- } else {
- NEXTADDR(q, del);
- if (inet_pton(AF_INET, q, &addr) <= 0) goto bad;
- minaddr = ntohl(addr.s_addr);
- RESCAN(del);
- SKIPSPC;
- if (*p == '-') {
- p++;
- NEXTADDR(q, del);
- if (inet_pton(AF_INET, q, &addr) <= 0) goto bad;
- RESCAN(del);
- maxaddr = ntohl(addr.s_addr);
- } else if (*p == '/') {
- p++;
- NEXTADDR(q, del);
- if (strchr(q, '.')) {
- if (inet_pton(AF_INET, q, &addr) <= 0) goto bad;
- mask = ntohl(addr.s_addr);
- } else {
- n = strtoul(q, 0, 0);
- mask = (~0ul << (32 - n)) & 0xffffffff;
- }
- RESCAN(del);
- minaddr &= mask;
- maxaddr = minaddr | (mask ^ 0xffffffff);
- } else
- maxaddr = minaddr;
- }
- justone:
- parse_ports(&p, &minport, &maxport);
- ACLNODE(*tail, act, minaddr, maxaddr, minport, maxport);
+ 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;
- 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 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)
{
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;
+ *pp = p;
return;
bad:
- D( fprintf(stderr, "bad port range (ignored)\n"); )
+ D( fprintf(stderr, "noip(%d): bad port range (ignored)\n", getpid()); )
return;
}
-/* Parse an ACL from an environment variable VAR, attaching it to the list
- * TAIL. */
-static void parse_acl_env(const char *var, aclnode ***tail)
-{
- char *p, *q;
-
- if ((p = getenv(var)) != 0) {
- p = q = xstrdup(p);
- parse_acl_line(&q, tail);
- free(p);
- }
-}
-
/* Read the configuration from the config file and environment. */
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);
+ parse_impbind_env("NOIP_IMPBIND_BEFORE");
if ((p = getenv("NOIP_AUTOPORTS")) != 0) {
p = q = xstrdup(p);
parse_autoports(&q);
}
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)) {
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());
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");
- dump_acl(connect_real); )
+ fprintf(stderr, "noip(%d): realconnect acl:\n", pid);
+ dump_acl(connect_real);
+ fprintf(stderr, "noip(%d): impbind list:\n", pid);
+ dump_impbind_list(); )
}
/*----- Overridden system calls -------------------------------------------*/
+static void dump_syserr(long rc)
+ { fprintf(stderr, " => %ld (E%d)\n", rc, errno); }
+
+static void dump_sysresult(long rc)
+{
+ if (rc < 0) dump_syserr(rc);
+ else fprintf(stderr, " => %ld\n", rc);
+}
+
+static void dump_addrresult(long rc, const struct sockaddr *sa,
+ socklen_t len)
+{
+ char addrbuf[ADDRBUFSZ];
+
+ if (rc < 0) dump_syserr(rc);
+ else {
+ fprintf(stderr, " => %ld [%s]\n", rc,
+ present_sockaddr(sa, len, addrbuf, sizeof(addrbuf)));
+ }
+}
+
int socket(int pf, int ty, int proto)
{
+ int sk;
+
+ D( fprintf(stderr, "noip(%d): SOCKET pf=%d, type=%d, proto=%d",
+ getpid(), pf, ty, proto); )
+
switch (pf) {
- case PF_INET:
+ default:
+ if (!family_known_p(pf)) {
+ D( fprintf(stderr, " -> unknown; refuse\n"); )
+ errno = EAFNOSUPPORT;
+ sk = -1;
+ }
+ D( fprintf(stderr, " -> inet; substitute"); )
pf = PF_UNIX;
proto = 0;
+ break;
case PF_UNIX:
- return real_socket(pf, ty, proto);
- default:
- errno = EAFNOSUPPORT;
- return -1;
+#ifdef PF_NETLINK
+ case PF_NETLINK:
+#endif
+ D( fprintf(stderr, " -> safe; permit"); )
+ break;
}
+ sk = real_socket(pf, ty, proto);
+ D( dump_sysresult(sk); )
+ return (sk);
}
int socketpair(int pf, int ty, int proto, int *sk)
{
- if (pf == PF_INET) {
+ int rc;
+
+ D( fprintf(stderr, "noip(%d): SOCKETPAIR pf=%d, type=%d, proto=%d",
+ getpid(), pf, ty, proto); )
+ if (!family_known_p(pf))
+ D( fprintf(stderr, " -> unknown; permit"); )
+ else {
+ D( fprintf(stderr, " -> inet; substitute"); )
pf = PF_UNIX;
proto = 0;
}
- return (real_socketpair(pf, ty, proto, sk));
+ rc = real_socketpair(pf, ty, proto, sk);
+ D( if (rc < 0) dump_syserr(rc);
+ else fprintf(stderr, " => %d (%d, %d)\n", rc, sk[0], sk[1]); )
+ return (rc);
}
int bind(int sk, const struct sockaddr *sa, socklen_t len)
{
struct sockaddr_un sun;
+ int rc;
+ Dpid;
- if (sa->sa_family == AF_INET) {
+ D({ char buf[ADDRBUFSZ];
+ fprintf(stderr, "noip(%d): BIND sk=%d, sa[%d]=%s", pid,
+ sk, len, present_sockaddr(sa, len, buf, sizeof(buf))); })
+
+ if (!family_known_p(sa->sa_family))
+ D( fprintf(stderr, " -> unknown af; pass through"); )
+ else {
+ D( fprintf(stderr, " -> checking...\n"); )
PRESERVING_ERRNO({
- if (acl_allows_p(bind_real, SIN(sa))) {
- if (fixup_real_ip_socket(sk))
+ if (acl_allows_p(bind_real, sa)) {
+ if (fixup_real_ip_socket(sk, sa->sa_family, 0))
return (-1);
} else {
- encode_inet_addr(&sun, SIN(sa), WANT_FRESH);
+ encode_inet_addr(&sun, sa, ENCF_FRESH);
sa = SA(&sun);
len = SUN_LEN(&sun);
}
});
+ D( fprintf(stderr, "noip(%d): BIND ...", pid); )
}
- return real_bind(sk, sa, len);
+ rc = real_bind(sk, sa, len);
+ D( dump_sysresult(rc); )
+ return (rc);
}
int connect(int sk, const struct sockaddr *sa, socklen_t len)
{
struct sockaddr_un sun;
- int fixup_p = 0;
int rc;
+ Dpid;
- switch (sa->sa_family) {
- case AF_INET:
- PRESERVING_ERRNO({
- do_implicit_bind(sk, &sa, &len, &sun);
- fixup_p = 1;
- });
- rc = real_connect(sk, sa, len);
- if (rc < 0) {
- switch (errno) {
- case ENOENT: errno = ECONNREFUSED; break;
- }
+ D({ char buf[ADDRBUFSZ];
+ fprintf(stderr, "noip(%d): CONNECT sk=%d, sa[%d]=%s", pid,
+ sk, len, present_sockaddr(sa, len, buf, sizeof(buf))); })
+
+ if (!family_known_p(sa->sa_family)) {
+ D( fprintf(stderr, " -> unknown af; pass through"); )
+ rc = real_connect(sk, sa, len);
+ } else {
+ D( fprintf(stderr, " -> checking...\n"); )
+ PRESERVING_ERRNO({
+ fixup_client_socket(sk, &sa, &len, &sun);
+ });
+ D( fprintf(stderr, "noip(%d): CONNECT ...", pid); )
+ rc = real_connect(sk, sa, len);
+ if (rc < 0) {
+ switch (errno) {
+ case ENOENT: errno = ECONNREFUSED; break;
}
- break;
- default:
- rc = real_connect(sk, sa, len);
- break;
+ }
}
- return rc;
+ D( dump_sysresult(rc); )
+ return (rc);
}
ssize_t sendto(int sk, const void *buf, size_t len, int flags,
const struct sockaddr *to, socklen_t tolen)
{
struct sockaddr_un sun;
+ ssize_t n;
+ Dpid;
- if (to && to->sa_family == AF_INET) {
+ D({ char addrbuf[ADDRBUFSZ];
+ fprintf(stderr, "noip(%d): SENDTO sk=%d, len=%lu, flags=%d, to[%d]=%s",
+ pid, sk, (unsigned long)len, flags, tolen,
+ present_sockaddr(to, tolen, addrbuf, sizeof(addrbuf))); })
+
+ if (!to)
+ D( fprintf(stderr, " -> null address; leaving"); )
+ else if (!family_known_p(to->sa_family))
+ D( fprintf(stderr, " -> unknown af; pass through"); )
+ 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); )
}
- return real_sendto(sk, buf, len, flags, to, tolen);
+ n = real_sendto(sk, buf, len, flags, to, tolen);
+ D( dump_sysresult(n); )
+ return (n);
}
ssize_t recvfrom(int sk, void *buf, size_t len, int flags,
char sabuf[1024];
socklen_t mylen = sizeof(sabuf);
ssize_t n;
+ Dpid;
- if (!from)
- return real_recvfrom(sk, buf, len, flags, 0, 0);
- PRESERVING_ERRNO({
+ D( fprintf(stderr, "noip(%d): RECVFROM sk=%d, len=%lu, flags=%d",
+ pid, sk, (unsigned long)len, flags); )
+
+ if (!from) {
+ D( fprintf(stderr, " -> null addr; pass through"); )
+ n = real_recvfrom(sk, buf, len, flags, 0, 0);
+ } else {
n = real_recvfrom(sk, buf, len, flags, SA(sabuf), &mylen);
- if (n < 0)
- return (-1);
- return_fake_name(SA(sabuf), mylen, from, fromlen);
- });
+ 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);
}
ssize_t sendmsg(int sk, const struct msghdr *msg, int flags)
{
struct sockaddr_un sun;
- const struct sockaddr *sa;
+ const struct sockaddr *sa = SA(msg->msg_name);
struct msghdr mymsg;
-
- if (msg->msg_name && SA(msg->msg_name)->sa_family == AF_INET) {
+ ssize_t n;
+ Dpid;
+
+ D({ char addrbuf[ADDRBUFSZ];
+ fprintf(stderr, "noip(%d): SENDMSG sk=%d, "
+ "msg_flags=%d, msg_name[%d]=%s, ...",
+ pid, sk, msg->msg_flags, msg->msg_namelen,
+ present_sockaddr(sa, msg->msg_namelen,
+ addrbuf, sizeof(addrbuf))); })
+
+ if (!sa)
+ D( fprintf(stderr, " -> null address; leaving"); )
+ else if (!family_known_p(sa->sa_family))
+ D( fprintf(stderr, " -> unknown af; pass through"); )
+ else {
+ D( fprintf(stderr, " -> checking...\n"); )
PRESERVING_ERRNO({
- sa = SA(msg->msg_name);
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;
});
+ D( fprintf(stderr, "noip(%d): SENDMSG ...", pid); )
}
- return real_sendmsg(sk, msg, flags);
+ n = real_sendmsg(sk, msg, flags);
+ D( dump_sysresult(n); )
+ return (n);
}
ssize_t recvmsg(int sk, struct msghdr *msg, int flags)
{
char sabuf[1024];
- struct sockaddr *sa;
- socklen_t len;
+ struct sockaddr *sa = SA(msg->msg_name);
+ socklen_t len = msg->msg_namelen;
ssize_t n;
+ Dpid;
- if (!msg->msg_name)
- return real_recvmsg(sk, msg, flags);
- PRESERVING_ERRNO({
- sa = SA(msg->msg_name);
- len = msg->msg_namelen;
+ D( fprintf(stderr, "noip(%d): RECVMSG sk=%d msg_flags=%d, ...",
+ pid, sk, msg->msg_flags); )
+
+ if (!msg->msg_name) {
+ D( fprintf(stderr, " -> null addr; pass through"); )
+ return (real_recvmsg(sk, msg, flags));
+ } else {
msg->msg_name = sabuf;
msg->msg_namelen = sizeof(sabuf);
n = real_recvmsg(sk, msg, flags);
- if (n < 0)
- return (-1);
- return_fake_name(SA(sabuf), msg->msg_namelen, sa, &len);
+ 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);
}
{
char sabuf[1024];
socklen_t mylen = sizeof(sabuf);
- int nsk = real_accept(sk, SA(sabuf), &mylen);
+ int nsk;
+ Dpid;
- if (nsk < 0)
- return (-1);
- return_fake_name(SA(sabuf), mylen, sa, len);
+ D( fprintf(stderr, "noip(%d): ACCEPT sk=%d", pid, sk); )
+
+ nsk = real_accept(sk, SA(sabuf), &mylen);
+ if (nsk < 0) /* failed */;
+ else if (!sa) D( fprintf(stderr, " -> address not wanted"); )
+ else {
+ D( fprintf(stderr, " -> converting...\n"); )
+ return_fake_peer(sk, SA(sabuf), mylen, sa, len);
+ D( fprintf(stderr, "noip(%d): ... ACCEPT", pid); )
+ }
+ D( dump_addrresult(nsk, sa, len ? *len : 0); )
return (nsk);
}
int getsockname(int sk, struct sockaddr *sa, socklen_t *len)
{
- PRESERVING_ERRNO({
- char sabuf[1024];
- socklen_t mylen = sizeof(sabuf);
- if (real_getsockname(sk, SA(sabuf), &mylen))
- return (-1);
- return_fake_name(SA(sabuf), mylen, sa, len);
- });
- return (0);
+ char sabuf[1024];
+ socklen_t mylen = sizeof(sabuf);
+ int rc;
+ Dpid;
+
+ D( fprintf(stderr, "noip(%d): GETSOCKNAME sk=%d", pid, sk); )
+ 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)
{
- PRESERVING_ERRNO({
- char sabuf[1024];
- socklen_t mylen = sizeof(sabuf);
- if (real_getpeername(sk, SA(sabuf), &mylen))
- return (-1);
- return_fake_name(SA(sabuf), mylen, sa, len);
- });
+ char sabuf[1024];
+ socklen_t mylen = sizeof(sabuf);
+ int rc;
+ Dpid;
+
+ D( fprintf(stderr, "noip(%d): GETPEERNAME sk=%d", pid, sk); )
+ 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);
}
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);
}
- return real_getsockopt(sk, lev, opt, p, len);
+ return (real_getsockopt(sk, lev, opt, p, 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) {
case SO_DETACH_FILTER:
return (0);
}
- return real_setsockopt(sk, lev, opt, p, 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 ----------------------------------------------------*/
{
DIR *dir;
struct dirent *d;
- struct sockaddr_in sin;
+ address addr;
struct sockaddr_un sun;
struct stat st;
+ Dpid;
- if ((dir = opendir(sockdir)) == 0)
- return;
+ if ((dir = opendir(sockdir)) == 0) return;
sun.sun_family = AF_UNIX;
while ((d = readdir(dir)) != 0) {
if (d->d_name[0] == '.') continue;
snprintf(sun.sun_path, sizeof(sun.sun_path),
"%s/%s", sockdir, d->d_name);
- if (decode_inet_addr(&sin, &sun, SUN_LEN(&sun), 0) ||
+ 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);
}
}
*/
static void get_local_ipaddrs(void)
{
- struct if_nameindex *ifn;
- struct ifreq ifr;
- int sk;
+ struct ifaddrs *ifa_head, *ifa;
+ ipaddr a;
int i;
-
- ifn = if_nameindex();
- if ((sk = real_socket(PF_INET, SOCK_STREAM, 00)) < 0)
- return;
- for (i = n_local_ipaddrs = 0;
- n_local_ipaddrs < MAX_LOCAL_IPADDRS &&
- ifn[i].if_name && *ifn[i].if_name;
- i++) {
- strcpy(ifr.ifr_name, ifn[i].if_name);
- if (ioctl(sk, SIOCGIFADDR, &ifr) || ifr.ifr_addr.sa_family != AF_INET)
+ 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;
+ ifa = ifa->ifa_next) {
+ if (!ifa->ifa_addr || !family_known_p(ifa->ifa_addr->sa_family))
continue;
- local_ipaddrs[n_local_ipaddrs++] =
- SIN(&ifr.ifr_addr)->sin_addr;
- D( fprintf(stderr, "noip: local addr %s = %s\n", ifn[i].if_name,
- inet_ntoa(local_ipaddrs[n_local_ipaddrs - 1])); )
+ ipaddr_from_sockaddr(&a, ifa->ifa_addr);
+ D({ char buf[ADDRBUFSZ];
+ 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++) {
+ if (ifa->ifa_addr->sa_family == local_ipaddrs[i].af &&
+ ipaddr_equal_p(local_ipaddrs[i].af, &a, &local_ipaddrs[i].addr)) {
+ D( fprintf(stderr, " (duplicate)\n"); )
+ goto skip;
+ }
+ }
+ D( fprintf(stderr, "\n"); )
+ local_ipaddrs[n_local_ipaddrs].af = ifa->ifa_addr->sa_family;
+ local_ipaddrs[n_local_ipaddrs].addr = a;
+ n_local_ipaddrs++;
+ skip:;
}
- close(sk);
+ freeifaddrs(ifa_head);
}
/* Print the given message to standard error. Avoids stdio. */
static void printerr(const char *p)
- { int hunoz; hunoz = write(STDERR_FILENO, p, strlen(p)); }
+ { if (write(STDERR_FILENO, p, strlen(p))) ; }
/* Create the socket directory, being careful about permissions. */
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");