3 * Make programs use Unix-domain sockets instead of IP
5 * (c) 2008 Straylight/Edgeware
8 /*----- Licensing notice --------------------------------------------------*
10 * This file is part of the preload-hacks package.
12 * Preload-hacks are free software; you can redistribute it and/or modify
13 * them under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or (at
15 * your option) any later version.
17 * Preload-hacks are distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
19 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
22 * You should have received a copy of the GNU General Public License along
23 * with preload-hacks; if not, write to the Free Software Foundation, Inc.,
24 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
32 /*----- Header files ------------------------------------------------------*/
47 #include <sys/ioctl.h>
48 #include <sys/socket.h>
52 #include <netinet/in.h>
53 #include <arpa/inet.h>
54 #include <netinet/tcp.h>
55 #include <netinet/udp.h>
59 /*----- Data structures ---------------------------------------------------*/
61 enum { UNUSED, STALE, USED }; /* Unix socket status values */
62 enum { WANT_FRESH, WANT_EXISTING }; /* Socket address dispositions */
63 enum { DENY, ALLOW }; /* ACL verdicts */
65 static int address_families[] = { AF_INET, AF_INET6, -1 };
69 /* Address representations. */
70 typedef union ipaddr {
75 /* Convenient socket address hacking. */
76 typedef union address {
78 struct sockaddr_in sin;
79 struct sockaddr_in6 sin6;
82 /* Access control list nodes */
83 typedef struct aclnode {
87 ipaddr minaddr, maxaddr;
88 unsigned short minport, maxport;
91 /* Local address records */
92 typedef struct full_ipaddr {
96 #define MAX_LOCAL_IPADDRS 64
97 static full_ipaddr local_ipaddrs[MAX_LOCAL_IPADDRS];
98 static int n_local_ipaddrs;
100 /* General configuration */
102 static char *sockdir = 0;
103 static int debug = 0;
104 static unsigned minautoport = 16384, maxautoport = 65536;
106 /* Access control lists */
107 static aclnode *bind_real, **bind_tail = &bind_real;
108 static aclnode *connect_real, **connect_tail = &connect_real;
110 /*----- Import the real versions of functions -----------------------------*/
112 /* The list of functions to immport. */
114 _(socket, int, (int, int, int)) \
115 _(socketpair, int, (int, int, int, int *)) \
116 _(connect, int, (int, const struct sockaddr *, socklen_t)) \
117 _(bind, int, (int, const struct sockaddr *, socklen_t)) \
118 _(accept, int, (int, struct sockaddr *, socklen_t *)) \
119 _(getsockname, int, (int, struct sockaddr *, socklen_t *)) \
120 _(getpeername, int, (int, struct sockaddr *, socklen_t *)) \
121 _(getsockopt, int, (int, int, int, void *, socklen_t *)) \
122 _(setsockopt, int, (int, int, int, const void *, socklen_t)) \
123 _(sendto, ssize_t, (int, const void *buf, size_t, int, \
124 const struct sockaddr *to, socklen_t tolen)) \
125 _(recvfrom, ssize_t, (int, void *buf, size_t, int, \
126 struct sockaddr *from, socklen_t *fromlen)) \
127 _(sendmsg, ssize_t, (int, const struct msghdr *, int)) \
128 _(recvmsg, ssize_t, (int, struct msghdr *, int))
130 /* Function pointers to set up. */
131 #define DECL(imp, ret, args) static ret (*real_##imp) args;
135 /* Import the system calls. */
136 static void import(void)
138 #define IMPORT(imp, ret, args) \
139 real_##imp = (ret (*)args)dlsym(RTLD_NEXT, #imp);
144 /*----- Utilities ---------------------------------------------------------*/
146 /* Socket address casts */
147 #define SA(sa) ((struct sockaddr *)(sa))
148 #define SIN(sa) ((struct sockaddr_in *)(sa))
149 #define SIN6(sa) ((struct sockaddr_in6 *)(sa))
150 #define SUN(sa) ((struct sockaddr_un *)(sa))
153 #define UC(ch) ((unsigned char)(ch))
155 /* Memory allocation */
156 #define NEW(x) ((x) = xmalloc(sizeof(*x)))
157 #define NEWV(x, n) ((x) = xmalloc(sizeof(*x) * (n)))
161 # define D(body) { if (debug) { body } }
166 /* Preservation of error status */
167 #define PRESERVING_ERRNO(body) do { \
168 int _err = errno; { body } errno = _err; \
171 /* Allocate N bytes of memory; abort on failure. */
172 static void *xmalloc(size_t n)
176 if ((p = malloc(n)) == 0) { perror("malloc"); exit(127); }
180 /* Allocate a copy of the null-terminated string P; abort on failure. */
181 static char *xstrdup(const char *p)
183 size_t n = strlen(p) + 1;
184 char *q = xmalloc(n);
189 /*----- Address-type hacking ----------------------------------------------*/
191 /* If M is a simple mask, i.e., consists of a sequence of zero bits followed
192 * by a sequence of one bits, then return the length of the latter sequence
193 * (which may be zero); otherwise return -1.
195 static int simple_mask_length(unsigned long m)
199 while (m & 1) { n++; m >>= 1; }
203 /* Answer whether AF is an interesting address family. */
204 static int family_known_p(int af)
215 /* Return the socket address length for address family AF. */
216 static socklen_t family_socklen(int af)
219 case AF_INET: return (sizeof(struct sockaddr_in));
220 case AF_INET6: return (sizeof(struct sockaddr_in6));
225 /* Return the width of addresses of kind AF. */
226 static int address_width(int af)
229 case AF_INET: return 32;
230 case AF_INET6: return 128;
235 /* If addresses A and B share a common prefix then return its length;
236 * otherwise return -1.
238 static int common_prefix_length(int af, const ipaddr *a, const ipaddr *b)
242 unsigned long aa = ntohl(a->v4.s_addr), bb = ntohl(b->v4.s_addr);
243 unsigned long m = aa^bb;
244 if ((aa&m) == 0 && (bb&m) == m) return (32 - simple_mask_length(m));
248 const uint8_t *aa = a->v6.s6_addr, *bb = b->v6.s6_addr;
253 for (i = 0; i < 16 && aa[i] == bb[i]; i++);
257 if ((aa[i]&m) != 0 || (bb[i]&m) != m) return (-1);
258 n += 8 - simple_mask_length(m);
259 for (i++; i < 16; i++)
260 if (aa[i] || bb[i] != 0xff) return (-1);
269 /* Extract the port number (in host byte-order) from SA. */
270 static int port_from_sockaddr(const struct sockaddr *sa)
272 switch (sa->sa_family) {
273 case AF_INET: return (ntohs(SIN(sa)->sin_port));
274 case AF_INET6: return (ntohs(SIN6(sa)->sin6_port));
279 /* Store the port number PORT (in host byte-order) in SA. */
280 static void port_to_sockaddr(struct sockaddr *sa, int port)
282 switch (sa->sa_family) {
283 case AF_INET: SIN(sa)->sin_port = htons(port); break;
284 case AF_INET6: SIN6(sa)->sin6_port = htons(port); break;
288 /* Extract the address part from SA and store it in A. */
289 static void ipaddr_from_sockaddr(ipaddr *a, const struct sockaddr *sa)
291 switch (sa->sa_family) {
292 case AF_INET: a->v4 = SIN(sa)->sin_addr; break;
293 case AF_INET6: a->v6 = SIN6(sa)->sin6_addr; break;
298 /* Copy a whole socket address about. */
299 static void copy_sockaddr(struct sockaddr *sa_dst,
300 const struct sockaddr *sa_src)
301 { memcpy(sa_dst, sa_src, family_socklen(sa_src->sa_family)); }
303 /* Answer whether two addresses are equal. */
304 static int ipaddr_equal_p(int af, const ipaddr *a, const ipaddr *b)
307 case AF_INET: return (a->v4.s_addr == b->v4.s_addr);
308 case AF_INET6: return (memcmp(a->v6.s6_addr, b->v6.s6_addr, 16) == 0);
313 /* Answer whether the address part of SA is between A and B (inclusive). We
314 * assume that SA has the correct address family.
316 static int sockaddr_in_range_p(const struct sockaddr *sa,
317 const ipaddr *a, const ipaddr *b)
319 switch (sa->sa_family) {
321 unsigned long addr = ntohl(SIN(sa)->sin_addr.s_addr);
322 return (ntohl(a->v4.s_addr) <= addr &&
323 addr <= ntohl(b->v4.s_addr));
326 const uint8_t *ss = SIN6(sa)->sin6_addr.s6_addr;
327 const uint8_t *aa = a->v6.s6_addr, *bb = b->v6.s6_addr;
331 for (i = 0; h && l && i < 16; i++, ss++, aa++, bb++) {
332 if (*ss < *aa || *bb < *ss) return (0);
333 if (*aa < *ss) l = 0;
334 if (*ss < *bb) h = 0;
343 /* Fill in SA with the appropriate wildcard address. */
344 static void wildcard_address(int af, struct sockaddr *sa)
348 struct sockaddr_in *sin = SIN(sa);
349 memset(sin, 0, sizeof(*sin));
350 sin->sin_family = AF_INET;
352 sin->sin_addr.s_addr = INADDR_ANY;
355 struct sockaddr_in6 *sin6 = SIN6(sa);
356 memset(sin6, 0, sizeof(sin6));
357 sin6->sin6_family = AF_INET6;
359 sin6->sin6_addr = in6addr_any;
360 sin6->sin6_scope_id = 0;
361 sin6->sin6_flowinfo = 0;
368 /* Mask the address A, forcing all but the top PLEN bits to zero or one
369 * according to HIGHP.
371 static void mask_address(int af, ipaddr *a, int plen, int highp)
375 unsigned long addr = ntohl(a->v4.s_addr);
376 unsigned long mask = plen ? ~0ul << (32 - plen) : 0;
378 if (highp) addr |= ~mask;
379 a->v4.s_addr = htonl(addr & 0xffffffff);
383 unsigned m = (0xff << (8 - plen%8)) & 0xff;
384 unsigned s = highp ? 0xff : 0;
386 a->v6.s6_addr[i] = (a->v6.s6_addr[i] & m) | (s & ~m);
389 for (; i < 16; i++) a->v6.s6_addr[i] = s;
396 /* Write a presentation form of SA to BUF, a buffer of length SZ. LEN is the
397 * address length; if it's zero, look it up based on the address family.
398 * Return a pointer to the string (which might, in an emergency, be a static
399 * string rather than your buffer).
401 static char *present_sockaddr(const struct sockaddr *sa, socklen_t len,
402 char *buf, size_t sz)
404 #define WANT(n_) do { if (sz < (n_)) goto nospace; } while (0)
405 #define PUTC(c_) do { *buf++ = (c_); sz--; } while (0)
407 if (!sz) return "<no-space-in-buffer>";
408 if (!len) len = family_socklen(sa->sa_family);
410 switch (sa->sa_family) {
412 struct sockaddr_un *sun = SUN(sa);
413 char *p = sun->sun_path;
414 size_t n = len - offsetof(struct sockaddr_un, sun_path);
422 case 0: WANT(2); PUTC('\\'); PUTC('0'); break;
423 case '\a': WANT(2); PUTC('\\'); PUTC('a'); break;
424 case '\n': WANT(2); PUTC('\\'); PUTC('n'); break;
425 case '\r': WANT(2); PUTC('\\'); PUTC('r'); break;
426 case '\t': WANT(2); PUTC('\\'); PUTC('t'); break;
427 case '\v': WANT(2); PUTC('\\'); PUTC('v'); break;
428 case '\\': WANT(2); PUTC('\\'); PUTC('\\'); break;
430 if (*p > ' ' && *p <= '~')
431 { WANT(1); PUTC(*p); }
433 WANT(4); PUTC('\\'); PUTC('x');
434 PUTC((*p >> 4)&0xf); PUTC((*p >> 0)&0xf);
441 if (*p != '/') { WANT(2); PUTC('.'); PUTC('/'); }
442 while (n && *p) { WANT(1); PUTC(*p); p++; n--; }
446 case AF_INET: case AF_INET6: {
447 char addrbuf[NI_MAXHOST], portbuf[NI_MAXSERV];
448 int err = getnameinfo(sa, len,
449 addrbuf, sizeof(addrbuf),
450 portbuf, sizeof(portbuf),
451 NI_NUMERICHOST | NI_NUMERICSERV);
453 snprintf(buf, sz, strchr(addrbuf, ':') ? "[%s]:%s" : "%s:%s",
457 snprintf(buf, sz, "<unknown-address-family %d>", sa->sa_family);
467 /* Guess the family of a textual socket address. */
468 static int guess_address_family(const char *p)
469 { return (strchr(p, ':') ? AF_INET6 : AF_INET); }
471 /* Parse a socket address P and write the result to SA. */
472 static int parse_sockaddr(struct sockaddr *sa, const char *p)
476 struct addrinfo *ai, ai_hint = { 0 };
478 if (strlen(p) >= sizeof(buf) - 1) return (-1);
479 strcpy(buf, p); p = buf;
481 if ((q = strchr(p, ':')) == 0) return (-1);
485 if ((q = strchr(p, ']')) == 0) return (-1);
487 if (*q != ':') return (-1);
491 ai_hint.ai_family = AF_UNSPEC;
492 ai_hint.ai_socktype = SOCK_DGRAM;
493 ai_hint.ai_flags = AI_NUMERICHOST | AI_NUMERICSERV;
494 if (getaddrinfo(p, q, &ai_hint, &ai)) return (-1);
495 memcpy(sa, ai->ai_addr, ai->ai_addrlen);
500 /*----- Access control lists ----------------------------------------------*/
504 /* Write to standard error a description of the ACL node A. */
505 static void dump_aclnode(aclnode *a)
511 fprintf(stderr, "noip: %c ", a->act ? '+' : '-');
512 plen = common_prefix_length(a->af, &a->minaddr, &a->maxaddr);
513 p = inet_ntop(a->af, &a->minaddr, buf, sizeof(buf));
514 fprintf(stderr, strchr(p, ':') ? "[%s]" : "%s", p);
516 p = inet_ntop(a->af, &a->maxaddr, buf, sizeof(buf));
517 fprintf(stderr, strchr(p, ':') ? "-[%s]" : "-%s", p);
518 } else if (plen < address_width(a->af))
519 fprintf(stderr, "/%d", plen);
520 if (a->minport != 0 || a->maxport != 0xffff) {
521 fprintf(stderr, ":%u", (unsigned)a->minport);
522 if (a->minport != a->maxport)
523 fprintf(stderr, "-%u", (unsigned)a->maxport);
528 static void dump_acl(aclnode *a)
532 for (; a; a = a->next) {
536 fprintf(stderr, "noip: [default policy: %s]\n",
537 act == ALLOW ? "DENY" : "ALLOW");
542 /* Returns nonzero if the ACL A allows the socket address SA. */
543 static int acl_allows_p(aclnode *a, const struct sockaddr *sa)
545 unsigned short port = port_from_sockaddr(sa);
548 D({ char buf[ADDRBUFSZ];
549 fprintf(stderr, "noip: check %s\n",
550 present_sockaddr(sa, 0, buf, sizeof(buf))); })
551 for (; a; a = a->next) {
552 D( dump_aclnode(a); )
553 if (sockaddr_in_range_p(sa, &a->minaddr, &a->maxaddr) &&
554 a->minport <= port && port <= a->maxport) {
555 D( fprintf(stderr, "noip: aha! %s\n", a->act ? "ALLOW" : "DENY"); )
560 D( fprintf(stderr, "noip: nothing found: %s\n", act ? "DENY" : "ALLOW"); )
564 /*----- Socket address conversion -----------------------------------------*/
566 /* Return a uniformly distributed integer between MIN and MAX inclusive. */
567 static unsigned randrange(unsigned min, unsigned max)
571 /* It's so nice not to have to care about the quality of the generator
575 for (mask = 1; mask < max; mask = (mask << 1) | 1)
577 do i = rand() & mask; while (i > max);
581 /* Return the status of Unix-domain socket address SUN. Returns: UNUSED if
582 * the socket doesn't exist; USED if the path refers to an active socket, or
583 * isn't really a socket at all, or we can't tell without a careful search
584 * and QUICKP is set; or STALE if the file refers to a socket which isn't
585 * being used any more.
587 static int unix_socket_status(struct sockaddr_un *sun, int quickp)
595 if (stat(sun->sun_path, &st))
596 return (errno == ENOENT ? UNUSED : USED);
597 if (!S_ISSOCK(st.st_mode) || quickp)
600 if ((fp = fopen("/proc/net/unix", "r")) == 0)
602 if (!fgets(buf, sizeof(buf), fp)) goto done; /* skip header */
603 len = strlen(sun->sun_path);
604 while (fgets(buf, sizeof(buf), fp)) {
606 if (n >= len + 2 && buf[n - len - 2] == ' ' && buf[n - 1] == '\n' &&
607 memcmp(buf + n - len - 1, sun->sun_path, len) == 0)
618 /* Encode the Internet address SA as a Unix-domain address SUN. If WANT is
619 * WANT_FRESH, and SA's port number is zero, then we pick an arbitrary local
620 * port. Otherwise we pick the port given. There's an unpleasant hack to
621 * find servers bound to local wildcard addresses. Returns zero on success;
624 static int encode_inet_addr(struct sockaddr_un *sun,
625 const struct sockaddr *sa,
634 D( fprintf(stderr, "noip: encode %s (%s)",
635 present_sockaddr(sa, 0, buf, sizeof(buf)),
636 want == WANT_EXISTING ? "EXISTING" : "FRESH"); )
637 sun->sun_family = AF_UNIX;
638 if (port_from_sockaddr(sa) || want == WANT_EXISTING) {
639 snprintf(sun->sun_path, sizeof(sun->sun_path), "%s/%s", sockdir,
640 present_sockaddr(sa, 0, buf, sizeof(buf)));
641 rc = unix_socket_status(sun, 0);
642 if (rc == STALE) unlink(sun->sun_path);
643 if (rc != USED && want == WANT_EXISTING) {
644 wildcard_address(sa->sa_family, &addr.sa);
645 port_to_sockaddr(&addr.sa, port_from_sockaddr(sa));
646 snprintf(sun->sun_path, sizeof(sun->sun_path), "%s/%s", sockdir,
647 present_sockaddr(&addr.sa, 0, buf, sizeof(buf)));
648 if (unix_socket_status(sun, 0) == STALE) unlink(sun->sun_path);
651 copy_sockaddr(&addr.sa, sa);
652 for (i = 0; i < 10; i++) {
653 port_to_sockaddr(&addr.sa, randrange(minautoport, maxautoport));
654 snprintf(sun->sun_path, sizeof(sun->sun_path), "%s/%s", sockdir,
655 present_sockaddr(&addr.sa, 0, buf, sizeof(buf)));
656 if (unix_socket_status(sun, 1) == UNUSED) goto found;
658 for (desperatep = 0; desperatep < 2; desperatep++) {
659 for (i = minautoport; i <= maxautoport; i++) {
660 port_to_sockaddr(&addr.sa, i);
661 snprintf(sun->sun_path, sizeof(sun->sun_path), "%s/%s", sockdir,
662 present_sockaddr(&addr.sa, 0, buf, sizeof(buf)));
663 rc = unix_socket_status(sun, !desperatep);
665 case STALE: unlink(sun->sun_path);
666 case UNUSED: goto found;
671 D( fprintf(stderr, " -- can't resolve\n"); )
675 D( fprintf(stderr, " -> `%s'\n", sun->sun_path); )
679 /* Decode the Unix address SUN to an Internet address SIN. If AF_HINT is
680 * nonzero, an empty address (indicative of an unbound Unix-domain socket) of
681 * the is translated to a wildcard Internet address of the appropriate
682 * family. Returns zero on success; -1 on failure (e.g., it wasn't one of
685 static int decode_inet_addr(struct sockaddr *sa, int af_hint,
686 const struct sockaddr_un *sun,
690 size_t n = strlen(sockdir), nn;
693 if (!sa) sa = &addr.sa;
694 if (sun->sun_family != AF_UNIX) return (-1);
695 if (len > sizeof(*sun)) return (-1);
696 ((char *)sun)[len] = 0;
697 nn = strlen(sun->sun_path);
698 D( fprintf(stderr, "noip: decode `%s'", sun->sun_path); )
699 if (af_hint && !sun->sun_path[0]) {
700 wildcard_address(af_hint, sa);
701 D( fprintf(stderr, " -- unbound socket\n"); )
704 if (nn < n + 1 || nn - n >= sizeof(buf) || sun->sun_path[n] != '/' ||
705 memcmp(sun->sun_path, sockdir, n) != 0) {
706 D( fprintf(stderr, " -- not one of ours\n"); )
709 if (parse_sockaddr(sa, sun->sun_path + n + 1)) return (-1);
710 D( fprintf(stderr, " -> %s\n",
711 present_sockaddr(sa, 0, buf, sizeof(buf))); )
715 /* SK is (or at least might be) a Unix-domain socket we created when an
716 * Internet socket was asked for. We've decided it should be an Internet
717 * socket after all, with family AF_HINT, so convert it.
719 static int fixup_real_ip_socket(int sk, int af_hint)
724 struct sockaddr_un sun;
737 _(LINGER, struct linger) \
740 _(RCVTIMEO, struct timeval) \
741 _(SNDTIMEO, struct timeval)
744 if (real_getsockname(sk, SA(&sun), &len))
746 if (decode_inet_addr(&addr.sa, af_hint, &sun, len))
747 return (0); /* Not one of ours */
749 if (real_getsockopt(sk, SOL_SOCKET, SO_TYPE, &type, &len) < 0 ||
750 (nsk = real_socket(addr.sa.sa_family, type, 0)) < 0)
752 #define FIX(opt, ty) do { \
755 if (real_getsockopt(sk, SOL_SOCKET, SO_##opt, &ov_, &len) < 0 || \
756 real_setsockopt(nsk, SOL_SOCKET, SO_##opt, &ov_, len)) { \
763 if ((f = fcntl(sk, F_GETFL)) < 0 ||
764 (fd = fcntl(sk, F_GETFD)) < 0 ||
765 fcntl(nsk, F_SETFL, f) < 0 ||
770 unlink(sun.sun_path);
772 if (fcntl(sk, F_SETFD, fd) < 0) {
773 perror("noip: fixup_real_ip_socket F_SETFD");
779 /* The socket SK is about to be used to communicate with the remote address
780 * SA. Assign it a local address so that getpeername(2) does something
783 static int do_implicit_bind(int sk, const struct sockaddr **sa,
784 socklen_t *len, struct sockaddr_un *sun)
787 socklen_t mylen = sizeof(*sun);
789 if (acl_allows_p(connect_real, *sa)) {
790 if (fixup_real_ip_socket(sk, (*sa)->sa_family)) return (-1);
792 if (real_getsockname(sk, SA(sun), &mylen) < 0) return (-1);
793 if (sun->sun_family == AF_UNIX) {
794 if (mylen < sizeof(*sun)) ((char *)sun)[mylen] = 0;
795 if (!sun->sun_path[0]) {
796 wildcard_address((*sa)->sa_family, &addr.sa);
797 encode_inet_addr(sun, &addr.sa, WANT_FRESH);
798 if (real_bind(sk, SA(sun), SUN_LEN(sun))) return (-1);
800 encode_inet_addr(sun, *sa, WANT_EXISTING);
808 /* We found the real address SA, with length LEN; if it's a Unix-domain
809 * address corresponding to a fake socket, convert it to cover up the
810 * deception. Whatever happens, put the result at FAKE and store its length
813 static void return_fake_name(struct sockaddr *sa, socklen_t len,
814 struct sockaddr *fake, socklen_t *fakelen)
819 if (sa->sa_family == AF_UNIX &&
820 !decode_inet_addr(&addr.sa, 0, SUN(sa), len)) {
822 len = family_socklen(addr.sa.sa_family);
825 if (len > *fakelen) len = *fakelen;
826 if (len > 0) memcpy(fake, sa, len);
830 /*----- Configuration -----------------------------------------------------*/
832 /* Return the process owner's home directory. */
833 static char *home(void)
838 if (getuid() == uid &&
839 (p = getenv("HOME")) != 0)
841 else if ((pw = getpwuid(uid)) != 0)
847 /* Return a good temporary directory to use. */
848 static char *tmpdir(void)
852 if ((p = getenv("TMPDIR")) != 0) return (p);
853 else if ((p = getenv("TMP")) != 0) return (p);
854 else return ("/tmp");
857 /* Return the user's name, or at least something distinctive. */
858 static char *user(void)
864 if ((p = getenv("USER")) != 0) return (p);
865 else if ((p = getenv("LOGNAME")) != 0) return (p);
866 else if ((pw = getpwuid(uid)) != 0) return (pw->pw_name);
868 snprintf(buf, sizeof(buf), "uid-%lu", (unsigned long)uid);
873 /* Skip P over space characters. */
874 #define SKIPSPC do { while (*p && isspace(UC(*p))) p++; } while (0)
876 /* Set Q to point to the next word following P, null-terminate it, and step P
878 #define NEXTWORD(q) do { \
881 while (*p && !isspace(UC(*p))) p++; \
885 /* Set Q to point to the next dotted-quad address, store the ending delimiter
886 * in DEL, null-terminate it, and step P past it. */
887 static void parse_nextaddr(char **pp, char **qq, int *del)
895 p += strcspn(p, "]");
900 while (*p && (*p == '.' || isdigit(UC(*p)))) p++;
907 /* Set Q to point to the next decimal number, store the ending delimiter in
908 * DEL, null-terminate it, and step P past it. */
909 #define NEXTNUMBER(q, del) do { \
912 while (*p && isdigit(UC(*p))) p++; \
917 /* Push the character DEL back so we scan it again, unless it's zero
919 #define RESCAN(del) do { if (del) *--p = del; } while (0)
921 /* Evaluate true if P is pointing to the word KW (and not some longer string
922 * of which KW is a prefix). */
924 #define KWMATCHP(kw) (strncmp(p, kw, sizeof(kw) - 1) == 0 && \
925 !isalnum(UC(p[sizeof(kw) - 1])) && \
926 (p += sizeof(kw) - 1))
928 /* Parse a port list, starting at *PP. Port lists have the form
929 * [:LOW[-HIGH]]: if omitted, all ports are included; if HIGH is omitted,
930 * it's as if HIGH = LOW. Store LOW in *MIN, HIGH in *MAX and set *PP to the
931 * rest of the string.
933 static void parse_ports(char **pp, unsigned short *min, unsigned short *max)
940 { *min = 0; *max = 0xffff; }
943 NEXTNUMBER(q, del); *min = strtoul(q, 0, 0); RESCAN(del);
946 { p++; NEXTNUMBER(q, del); *max = strtoul(q, 0, 0); RESCAN(del); }
953 /* Make a new ACL node. ACT is the verdict; AF is the address family;
954 * MINADDR and MAXADDR are the ranges on IP addresses; MINPORT and MAXPORT
955 * are the ranges on port numbers; TAIL is the list tail to attach the new
958 #define ACLNODE(tail_, act_, \
959 af_, minaddr_, maxaddr_, minport_, maxport_) do { \
964 a_->minaddr = (minaddr_); a_->maxaddr = (maxaddr_); \
965 a_->minport = (minport_); a_->maxport = (maxport_); \
966 *tail_ = a_; tail_ = &a_->next; \
969 /* Parse an ACL line. *PP points to the end of the line; *TAIL points to
970 * the list tail (i.e., the final link in the list). An ACL entry has the
971 * form +|- [any | local | ADDR | ADDR - ADDR | ADDR/ADDR | ADDR/INT] PORTS
972 * where PORTS is parsed by parse_ports above; an ACL line consists of a
973 * comma-separated sequence of entries..
975 static void parse_acl_line(char **pp, aclnode ***tail)
977 ipaddr minaddr, maxaddr;
978 unsigned short minport, maxport;
987 if (*p == '+') act = ALLOW;
988 else if (*p == '-') act = DENY;
993 if (KWMATCHP("any")) {
994 parse_ports(&p, &minport, &maxport);
995 for (i = 0; address_families[i] >= 0; i++) {
996 af = address_families[i];
997 memset(&minaddr, 0, sizeof(minaddr));
998 maxaddr = minaddr; mask_address(af, &maxaddr, 0, 1);
999 ACLNODE(*tail, act, af, minaddr, maxaddr, minport, maxport);
1001 } else if (KWMATCHP("local")) {
1002 parse_ports(&p, &minport, &maxport);
1003 for (i = 0; address_families[i] >= 0; i++) {
1004 af = address_families[i];
1005 memset(&minaddr, 0, sizeof(minaddr));
1006 maxaddr = minaddr; mask_address(af, &maxaddr, 0, 1);
1007 ACLNODE(*tail, act, af, minaddr, minaddr, minport, maxport);
1008 ACLNODE(*tail, act, af, maxaddr, maxaddr, minport, maxport);
1010 for (i = 0; i < n_local_ipaddrs; i++) {
1011 ACLNODE(*tail, act, local_ipaddrs[i].af,
1012 local_ipaddrs[i].addr, local_ipaddrs[i].addr,
1016 parse_nextaddr(&p, &q, &del);
1017 af = guess_address_family(q);
1018 if (inet_pton(af, q, &minaddr) <= 0) goto bad;
1023 parse_nextaddr(&p, &q, &del);
1024 if (inet_pton(af, q, &maxaddr) <= 0) goto bad;
1026 } else if (*p == '/') {
1029 n = strtoul(q, 0, 0);
1031 mask_address(af, &minaddr, n, 0);
1032 mask_address(af, &maxaddr, n, 1);
1035 parse_ports(&p, &minport, &maxport);
1036 ACLNODE(*tail, act, af, minaddr, maxaddr, minport, maxport);
1039 if (*p != ',') break;
1045 D( fprintf(stderr, "noip: bad acl spec (ignored)\n"); )
1049 /* Parse the autoports configuration directive. Syntax is MIN - MAX. */
1050 static void parse_autoports(char **pp)
1057 NEXTNUMBER(q, del); x = strtoul(q, 0, 0); RESCAN(del);
1059 if (*p != '-') goto bad; p++;
1060 NEXTNUMBER(q, del); y = strtoul(q, 0, 0); RESCAN(del);
1061 minautoport = x; maxautoport = y;
1065 D( fprintf(stderr, "bad port range (ignored)\n"); )
1069 /* Parse an ACL from an environment variable VAR, attaching it to the list
1071 static void parse_acl_env(const char *var, aclnode ***tail)
1075 if ((p = getenv(var)) != 0) {
1077 parse_acl_line(&q, tail);
1082 /* Read the configuration from the config file and environment. */
1083 static void readconfig(void)
1090 parse_acl_env("NOIP_REALBIND_BEFORE", &bind_tail);
1091 parse_acl_env("NOIP_REALCONNECT_BEFORE", &connect_tail);
1092 if ((p = getenv("NOIP_AUTOPORTS")) != 0) {
1094 parse_autoports(&q);
1097 if ((p = getenv("NOIP_CONFIG")) == 0)
1098 snprintf(p = buf, sizeof(buf), "%s/.noip", home());
1099 D( fprintf(stderr, "noip: config file: %s\n", p); )
1101 if ((fp = fopen(p, "r")) == 0) {
1102 D( fprintf(stderr, "noip: couldn't read config: %s\n",
1106 while (fgets(buf, sizeof(buf), fp)) {
1111 if (!*p || *p == '#') continue;
1112 while (n && isspace(UC(buf[n - 1]))) n--;
1117 if (strcmp(cmd, "socketdir") == 0)
1118 sockdir = xstrdup(p);
1119 else if (strcmp(cmd, "realbind") == 0)
1120 parse_acl_line(&p, &bind_tail);
1121 else if (strcmp(cmd, "realconnect") == 0)
1122 parse_acl_line(&p, &connect_tail);
1123 else if (strcmp(cmd, "autoports") == 0)
1124 parse_autoports(&p);
1125 else if (strcmp(cmd, "debug") == 0)
1126 debug = *p ? atoi(p) : 1;
1128 D( fprintf(stderr, "noip: bad config command %s\n", cmd); )
1133 parse_acl_env("NOIP_REALBIND", &bind_tail);
1134 parse_acl_env("NOIP_REALCONNECT", &connect_tail);
1135 parse_acl_env("NOIP_REALBIND_AFTER", &bind_tail);
1136 parse_acl_env("NOIP_REALCONNECT_AFTER", &connect_tail);
1139 if (!sockdir) sockdir = getenv("NOIP_SOCKETDIR");
1141 snprintf(buf, sizeof(buf), "%s/noip-%s", tmpdir(), user());
1142 sockdir = xstrdup(buf);
1144 D( fprintf(stderr, "noip: socketdir: %s\n", sockdir);
1145 fprintf(stderr, "noip: autoports: %u-%u\n",
1146 minautoport, maxautoport);
1147 fprintf(stderr, "noip: realbind acl:\n");
1148 dump_acl(bind_real);
1149 fprintf(stderr, "noip: realconnect acl:\n");
1150 dump_acl(connect_real); )
1153 /*----- Overridden system calls -------------------------------------------*/
1155 int socket(int pf, int ty, int proto)
1159 if (!family_known_p(pf)) {
1160 errno = EAFNOSUPPORT;
1169 return (real_socket(pf, ty, proto));
1173 int socketpair(int pf, int ty, int proto, int *sk)
1175 if (pf == PF_INET) {
1179 return (real_socketpair(pf, ty, proto, sk));
1182 int bind(int sk, const struct sockaddr *sa, socklen_t len)
1184 struct sockaddr_un sun;
1186 if (family_known_p(sa->sa_family)) {
1188 if (acl_allows_p(bind_real, sa)) {
1189 if (fixup_real_ip_socket(sk, sa->sa_family))
1192 encode_inet_addr(&sun, sa, WANT_FRESH);
1194 len = SUN_LEN(&sun);
1198 return (real_bind(sk, sa, len));
1201 int connect(int sk, const struct sockaddr *sa, socklen_t len)
1203 struct sockaddr_un sun;
1206 if (!family_known_p(sa->sa_family))
1207 rc = real_connect(sk, sa, len);
1210 do_implicit_bind(sk, &sa, &len, &sun);
1212 rc = real_connect(sk, sa, len);
1215 case ENOENT: errno = ECONNREFUSED; break;
1222 ssize_t sendto(int sk, const void *buf, size_t len, int flags,
1223 const struct sockaddr *to, socklen_t tolen)
1225 struct sockaddr_un sun;
1227 if (to && to->sa_family == AF_INET) {
1229 do_implicit_bind(sk, &to, &tolen, &sun);
1232 return (real_sendto(sk, buf, len, flags, to, tolen));
1235 ssize_t recvfrom(int sk, void *buf, size_t len, int flags,
1236 struct sockaddr *from, socklen_t *fromlen)
1239 socklen_t mylen = sizeof(sabuf);
1243 return real_recvfrom(sk, buf, len, flags, 0, 0);
1245 n = real_recvfrom(sk, buf, len, flags, SA(sabuf), &mylen);
1248 return_fake_name(SA(sabuf), mylen, from, fromlen);
1253 ssize_t sendmsg(int sk, const struct msghdr *msg, int flags)
1255 struct sockaddr_un sun;
1256 const struct sockaddr *sa;
1257 struct msghdr mymsg;
1259 if (msg->msg_name && SA(msg->msg_name)->sa_family == AF_INET) {
1261 sa = SA(msg->msg_name);
1263 do_implicit_bind(sk, &sa, &mymsg.msg_namelen, &sun);
1264 mymsg.msg_name = SA(sa);
1268 return (real_sendmsg(sk, msg, flags));
1271 ssize_t recvmsg(int sk, struct msghdr *msg, int flags)
1274 struct sockaddr *sa;
1279 return (real_recvmsg(sk, msg, flags));
1281 sa = SA(msg->msg_name);
1282 len = msg->msg_namelen;
1283 msg->msg_name = sabuf;
1284 msg->msg_namelen = sizeof(sabuf);
1285 n = real_recvmsg(sk, msg, flags);
1288 return_fake_name(SA(sabuf), msg->msg_namelen, sa, &len);
1290 msg->msg_namelen = len;
1295 int accept(int sk, struct sockaddr *sa, socklen_t *len)
1298 socklen_t mylen = sizeof(sabuf);
1299 int nsk = real_accept(sk, SA(sabuf), &mylen);
1303 return_fake_name(SA(sabuf), mylen, sa, len);
1307 int getsockname(int sk, struct sockaddr *sa, socklen_t *len)
1311 socklen_t mylen = sizeof(sabuf);
1312 if (real_getsockname(sk, SA(sabuf), &mylen))
1314 return_fake_name(SA(sabuf), mylen, sa, len);
1319 int getpeername(int sk, struct sockaddr *sa, socklen_t *len)
1323 socklen_t mylen = sizeof(sabuf);
1324 if (real_getpeername(sk, SA(sabuf), &mylen))
1326 return_fake_name(SA(sabuf), mylen, sa, len);
1331 int getsockopt(int sk, int lev, int opt, void *p, socklen_t *len)
1341 return (real_getsockopt(sk, lev, opt, p, len));
1344 int setsockopt(int sk, int lev, int opt, const void *p, socklen_t len)
1353 case SO_BINDTODEVICE:
1354 case SO_ATTACH_FILTER:
1355 case SO_DETACH_FILTER:
1358 return (real_setsockopt(sk, lev, opt, p, len));
1361 /*----- Initialization ----------------------------------------------------*/
1363 /* Clean up the socket directory, deleting stale sockets. */
1364 static void cleanup_sockdir(void)
1369 struct sockaddr_un sun;
1372 if ((dir = opendir(sockdir)) == 0) return;
1373 sun.sun_family = AF_UNIX;
1374 while ((d = readdir(dir)) != 0) {
1375 if (d->d_name[0] == '.') continue;
1376 snprintf(sun.sun_path, sizeof(sun.sun_path),
1377 "%s/%s", sockdir, d->d_name);
1378 if (decode_inet_addr(&addr.sa, 0, &sun, SUN_LEN(&sun)) ||
1379 stat(sun.sun_path, &st) ||
1380 !S_ISSOCK(st.st_mode)) {
1381 D( fprintf(stderr, "noip: ignoring unknown socketdir entry `%s'\n",
1385 if (unix_socket_status(&sun, 0) == STALE) {
1386 D( fprintf(stderr, "noip: clearing away stale socket %s\n",
1388 unlink(sun.sun_path);
1394 /* Find the addresses attached to local network interfaces, and remember them
1397 static void get_local_ipaddrs(void)
1399 struct ifaddrs *ifa_head, *ifa;
1403 if (getifaddrs(&ifa_head)) { perror("getifaddrs"); return; }
1404 for (n_local_ipaddrs = 0, ifa = ifa_head;
1405 n_local_ipaddrs < MAX_LOCAL_IPADDRS && ifa;
1406 ifa = ifa->ifa_next) {
1407 if (!ifa->ifa_addr || !family_known_p(ifa->ifa_addr->sa_family))
1409 ipaddr_from_sockaddr(&a, ifa->ifa_addr);
1410 D({ char buf[ADDRBUFSZ];
1411 fprintf(stderr, "noip: local addr %s = %s", ifa->ifa_name,
1412 inet_ntop(ifa->ifa_addr->sa_family, &a,
1413 buf, sizeof(buf))); })
1414 for (i = 0; i < n_local_ipaddrs; i++) {
1415 if (ifa->ifa_addr->sa_family == local_ipaddrs[i].af &&
1416 ipaddr_equal_p(local_ipaddrs[i].af, &a, &local_ipaddrs[i].addr)) {
1417 D( fprintf(stderr, " (duplicate)\n"); )
1421 D( fprintf(stderr, "\n"); )
1422 local_ipaddrs[n_local_ipaddrs].af = ifa->ifa_addr->sa_family;
1423 local_ipaddrs[n_local_ipaddrs].addr = a;
1427 freeifaddrs(ifa_head);
1430 /* Print the given message to standard error. Avoids stdio. */
1431 static void printerr(const char *p)
1432 { if (write(STDERR_FILENO, p, strlen(p))) ; }
1434 /* Create the socket directory, being careful about permissions. */
1435 static void create_sockdir(void)
1439 if (lstat(sockdir, &st)) {
1440 if (errno == ENOENT) {
1441 if (mkdir(sockdir, 0700)) {
1442 perror("noip: creating socketdir");
1445 if (!lstat(sockdir, &st))
1448 perror("noip: checking socketdir");
1452 if (!S_ISDIR(st.st_mode)) {
1453 printerr("noip: bad socketdir: not a directory\n");
1456 if (st.st_uid != uid) {
1457 printerr("noip: bad socketdir: not owner\n");
1460 if (st.st_mode & 077) {
1461 printerr("noip: bad socketdir: not private\n");
1466 /* Initialization function. */
1467 static void setup(void) __attribute__((constructor));
1468 static void setup(void)
1475 if ((p = getenv("NOIP_DEBUG")) && atoi(p))
1477 get_local_ipaddrs();
1484 /*----- That's all, folks -------------------------------------------------*/