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 ------------------------------------------------------*/
48 #include <sys/ioctl.h>
49 #include <sys/socket.h>
53 #include <netinet/in.h>
54 #include <arpa/inet.h>
55 #include <netinet/tcp.h>
56 #include <netinet/udp.h>
60 /*----- Data structures ---------------------------------------------------*/
62 enum { UNUSED, STALE, USED }; /* Unix socket status values */
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 /* Implicit bind records */
92 typedef struct impbind {
95 ipaddr minaddr, maxaddr, bindaddr;
97 enum { EXPLICIT, SAME };
99 /* A type for an address range */
100 typedef struct addrrange {
103 struct { int af; ipaddr min, max; } range;
106 enum { EMPTY, ANY, LOCAL, RANGE };
108 /* Local address records */
109 typedef struct full_ipaddr {
113 #define MAX_LOCAL_IPADDRS 64
114 static full_ipaddr local_ipaddrs[MAX_LOCAL_IPADDRS];
115 static int n_local_ipaddrs;
117 /* General configuration */
119 static char *sockdir = 0;
120 static int debug = 0;
121 static unsigned minautoport = 16384, maxautoport = 65536;
123 /* Access control lists */
124 static aclnode *bind_real, **bind_tail = &bind_real;
125 static aclnode *connect_real, **connect_tail = &connect_real;
126 static impbind *impbinds, **impbind_tail = &impbinds;
128 /*----- Import the real versions of functions -----------------------------*/
130 /* The list of functions to immport. */
132 _(socket, int, (int, int, int)) \
133 _(socketpair, int, (int, int, int, int *)) \
134 _(connect, int, (int, const struct sockaddr *, socklen_t)) \
135 _(bind, int, (int, const struct sockaddr *, socklen_t)) \
136 _(accept, int, (int, struct sockaddr *, socklen_t *)) \
137 _(getsockname, int, (int, struct sockaddr *, socklen_t *)) \
138 _(getpeername, int, (int, struct sockaddr *, socklen_t *)) \
139 _(getsockopt, int, (int, int, int, void *, socklen_t *)) \
140 _(setsockopt, int, (int, int, int, const void *, socklen_t)) \
141 _(sendto, ssize_t, (int, const void *buf, size_t, int, \
142 const struct sockaddr *to, socklen_t tolen)) \
143 _(recvfrom, ssize_t, (int, void *buf, size_t, int, \
144 struct sockaddr *from, socklen_t *fromlen)) \
145 _(sendmsg, ssize_t, (int, const struct msghdr *, int)) \
146 _(recvmsg, ssize_t, (int, struct msghdr *, int)) \
147 _(ioctl, int, (int, unsigned long, ...))
149 /* Function pointers to set up. */
150 #define DECL(imp, ret, args) static ret (*real_##imp) args;
154 /* Import the system calls. */
155 static void import(void)
157 #define IMPORT(imp, ret, args) \
158 real_##imp = (ret (*)args)dlsym(RTLD_NEXT, #imp);
163 /*----- Utilities ---------------------------------------------------------*/
165 /* Socket address casts */
166 #define SA(sa) ((struct sockaddr *)(sa))
167 #define SIN(sa) ((struct sockaddr_in *)(sa))
168 #define SIN6(sa) ((struct sockaddr_in6 *)(sa))
169 #define SUN(sa) ((struct sockaddr_un *)(sa))
172 #define UC(ch) ((unsigned char)(ch))
174 /* Memory allocation */
175 #define NEW(x) ((x) = xmalloc(sizeof(*x)))
176 #define NEWV(x, n) ((x) = xmalloc(sizeof(*x) * (n)))
180 # define D(body) { if (debug) { body } }
181 # define Dpid pid_t pid = debug ? getpid() : -1
187 /* Preservation of error status */
188 #define PRESERVING_ERRNO(body) do { \
189 int _err = errno; { body } errno = _err; \
192 /* Allocate N bytes of memory; abort on failure. */
193 static void *xmalloc(size_t n)
197 if ((p = malloc(n)) == 0) { perror("malloc"); exit(127); }
201 /* Allocate a copy of the null-terminated string P; abort on failure. */
202 static char *xstrdup(const char *p)
204 size_t n = strlen(p) + 1;
205 char *q = xmalloc(n);
210 /*----- Address-type hacking ----------------------------------------------*/
212 /* If M is a simple mask, i.e., consists of a sequence of zero bits followed
213 * by a sequence of one bits, then return the length of the latter sequence
214 * (which may be zero); otherwise return -1.
216 static int simple_mask_length(unsigned long m)
220 while (m & 1) { n++; m >>= 1; }
224 /* Answer whether AF is an interesting address family. */
225 static int family_known_p(int af)
236 /* Return the socket address length for address family AF. */
237 static socklen_t family_socklen(int af)
240 case AF_INET: return (sizeof(struct sockaddr_in));
241 case AF_INET6: return (sizeof(struct sockaddr_in6));
246 /* Return the width of addresses of kind AF. */
247 static int address_width(int af)
250 case AF_INET: return 32;
251 case AF_INET6: return 128;
256 /* If addresses A and B share a common prefix then return its length;
257 * otherwise return -1.
259 static int common_prefix_length(int af, const ipaddr *a, const ipaddr *b)
263 unsigned long aa = ntohl(a->v4.s_addr), bb = ntohl(b->v4.s_addr);
264 unsigned long m = aa^bb;
265 if ((aa&m) == 0 && (bb&m) == m) return (32 - simple_mask_length(m));
269 const uint8_t *aa = a->v6.s6_addr, *bb = b->v6.s6_addr;
274 for (i = 0; i < 16 && aa[i] == bb[i]; i++);
278 if ((aa[i]&m) != 0 || (bb[i]&m) != m) return (-1);
279 n += 8 - simple_mask_length(m);
280 for (i++; i < 16; i++)
281 if (aa[i] || bb[i] != 0xff) return (-1);
290 /* Extract the port number (in host byte-order) from SA. */
291 static int port_from_sockaddr(const struct sockaddr *sa)
293 switch (sa->sa_family) {
294 case AF_INET: return (ntohs(SIN(sa)->sin_port));
295 case AF_INET6: return (ntohs(SIN6(sa)->sin6_port));
300 /* Store the port number PORT (in host byte-order) in SA. */
301 static void port_to_sockaddr(struct sockaddr *sa, int port)
303 switch (sa->sa_family) {
304 case AF_INET: SIN(sa)->sin_port = htons(port); break;
305 case AF_INET6: SIN6(sa)->sin6_port = htons(port); break;
310 /* Extract the address part from SA and store it in A. */
311 static void ipaddr_from_sockaddr(ipaddr *a, const struct sockaddr *sa)
313 switch (sa->sa_family) {
314 case AF_INET: a->v4 = SIN(sa)->sin_addr; break;
315 case AF_INET6: a->v6 = SIN6(sa)->sin6_addr; break;
320 /* Store the address A in SA. */
321 static void ipaddr_to_sockaddr(struct sockaddr *sa, const ipaddr *a)
323 switch (sa->sa_family) {
325 SIN(sa)->sin_addr = a->v4;
328 SIN6(sa)->sin6_addr = a->v6;
329 SIN6(sa)->sin6_scope_id = 0;
330 SIN6(sa)->sin6_flowinfo = 0;
337 /* Copy a whole socket address about. */
338 static void copy_sockaddr(struct sockaddr *sa_dst,
339 const struct sockaddr *sa_src)
340 { memcpy(sa_dst, sa_src, family_socklen(sa_src->sa_family)); }
342 /* Answer whether two addresses are equal. */
343 static int ipaddr_equal_p(int af, const ipaddr *a, const ipaddr *b)
346 case AF_INET: return (a->v4.s_addr == b->v4.s_addr);
347 case AF_INET6: return (memcmp(a->v6.s6_addr, b->v6.s6_addr, 16) == 0);
352 /* Answer whether the address part of SA is between A and B (inclusive). We
353 * assume that SA has the correct address family.
355 static int sockaddr_in_range_p(const struct sockaddr *sa,
356 const ipaddr *a, const ipaddr *b)
358 switch (sa->sa_family) {
360 unsigned long addr = ntohl(SIN(sa)->sin_addr.s_addr);
361 return (ntohl(a->v4.s_addr) <= addr &&
362 addr <= ntohl(b->v4.s_addr));
365 const uint8_t *ss = SIN6(sa)->sin6_addr.s6_addr;
366 const uint8_t *aa = a->v6.s6_addr, *bb = b->v6.s6_addr;
370 for (i = 0; h && l && i < 16; i++, ss++, aa++, bb++) {
371 if (*ss < *aa || *bb < *ss) return (0);
372 if (*aa < *ss) l = 0;
373 if (*ss < *bb) h = 0;
382 /* Fill in SA with the appropriate wildcard address. */
383 static void wildcard_address(int af, struct sockaddr *sa)
387 struct sockaddr_in *sin = SIN(sa);
388 memset(sin, 0, sizeof(*sin));
389 sin->sin_family = AF_INET;
391 sin->sin_addr.s_addr = INADDR_ANY;
394 struct sockaddr_in6 *sin6 = SIN6(sa);
395 memset(sin6, 0, sizeof(*sin6));
396 sin6->sin6_family = AF_INET6;
398 sin6->sin6_addr = in6addr_any;
399 sin6->sin6_scope_id = 0;
400 sin6->sin6_flowinfo = 0;
407 /* Mask the address A, forcing all but the top PLEN bits to zero or one
408 * according to HIGHP.
410 static void mask_address(int af, ipaddr *a, int plen, int highp)
414 unsigned long addr = ntohl(a->v4.s_addr);
415 unsigned long mask = plen ? ~0ul << (32 - plen) : 0;
417 if (highp) addr |= ~mask;
418 a->v4.s_addr = htonl(addr & 0xffffffff);
422 unsigned m = (0xff << (8 - plen%8)) & 0xff;
423 unsigned s = highp ? 0xff : 0;
425 a->v6.s6_addr[i] = (a->v6.s6_addr[i] & m) | (s & ~m);
428 for (; i < 16; i++) a->v6.s6_addr[i] = s;
435 /* Write a presentation form of SA to BUF, a buffer of length SZ. LEN is the
436 * address length; if it's zero, look it up based on the address family.
437 * Return a pointer to the string (which might, in an emergency, be a static
438 * string rather than your buffer).
440 static char *present_sockaddr(const struct sockaddr *sa, socklen_t len,
441 char *buf, size_t sz)
443 #define WANT(n_) do { if (sz < (n_)) goto nospace; } while (0)
444 #define PUTC(c_) do { *buf++ = (c_); sz--; } while (0)
446 if (!sa) return "<null-address>";
447 if (!sz) return "<no-space-in-buffer>";
448 if (!len) len = family_socklen(sa->sa_family);
450 switch (sa->sa_family) {
452 struct sockaddr_un *sun = SUN(sa);
453 char *p = sun->sun_path;
454 size_t n = len - offsetof(struct sockaddr_un, sun_path);
462 case 0: WANT(2); PUTC('\\'); PUTC('0'); break;
463 case '\a': WANT(2); PUTC('\\'); PUTC('a'); break;
464 case '\n': WANT(2); PUTC('\\'); PUTC('n'); break;
465 case '\r': WANT(2); PUTC('\\'); PUTC('r'); break;
466 case '\t': WANT(2); PUTC('\\'); PUTC('t'); break;
467 case '\v': WANT(2); PUTC('\\'); PUTC('v'); break;
468 case '\\': WANT(2); PUTC('\\'); PUTC('\\'); break;
470 if (*p > ' ' && *p <= '~')
471 { WANT(1); PUTC(*p); }
473 WANT(4); PUTC('\\'); PUTC('x');
474 PUTC((*p >> 4)&0xf); PUTC((*p >> 0)&0xf);
481 if (*p != '/') { WANT(2); PUTC('.'); PUTC('/'); }
482 while (n && *p) { WANT(1); PUTC(*p); p++; n--; }
486 case AF_INET: case AF_INET6: {
487 char addrbuf[NI_MAXHOST], portbuf[NI_MAXSERV];
488 int err = getnameinfo(sa, len,
489 addrbuf, sizeof(addrbuf),
490 portbuf, sizeof(portbuf),
491 NI_NUMERICHOST | NI_NUMERICSERV);
493 snprintf(buf, sz, strchr(addrbuf, ':') ? "[%s]:%s" : "%s:%s",
497 snprintf(buf, sz, "<unknown-address-family %d>", sa->sa_family);
507 /* Guess the family of a textual socket address. */
508 static int guess_address_family(const char *p)
509 { return (strchr(p, ':') ? AF_INET6 : AF_INET); }
511 /* Parse a socket address P and write the result to SA. */
512 static int parse_sockaddr(struct sockaddr *sa, const char *p)
516 struct addrinfo *ai, ai_hint = { 0 };
518 if (strlen(p) >= sizeof(buf) - 1) return (-1);
519 strcpy(buf, p); p = buf;
521 if ((q = strchr(p, ':')) == 0) return (-1);
525 if ((q = strchr(p, ']')) == 0) return (-1);
527 if (*q != ':') return (-1);
531 ai_hint.ai_family = AF_UNSPEC;
532 ai_hint.ai_socktype = SOCK_DGRAM;
533 ai_hint.ai_flags = AI_NUMERICHOST | AI_NUMERICSERV;
534 if (getaddrinfo(p, q, &ai_hint, &ai)) return (-1);
535 memcpy(sa, ai->ai_addr, ai->ai_addrlen);
540 /*----- Access control lists ----------------------------------------------*/
544 static void dump_addrrange(int af, const ipaddr *min, const ipaddr *max)
550 plen = common_prefix_length(af, min, max);
551 p = inet_ntop(af, min, buf, sizeof(buf));
552 fprintf(stderr, strchr(p, ':') ? "[%s]" : "%s", p);
554 p = inet_ntop(af, &max, buf, sizeof(buf));
555 fprintf(stderr, strchr(p, ':') ? "-[%s]" : "-%s", p);
556 } else if (plen < address_width(af))
557 fprintf(stderr, "/%d", plen);
560 /* Write to standard error a description of the ACL node A. */
561 static void dump_aclnode(const aclnode *a)
563 fprintf(stderr, "noip(%d): %c ", getpid(), a->act ? '+' : '-');
564 dump_addrrange(a->af, &a->minaddr, &a->maxaddr);
565 if (a->minport != 0 || a->maxport != 0xffff) {
566 fprintf(stderr, ":%u", (unsigned)a->minport);
567 if (a->minport != a->maxport)
568 fprintf(stderr, "-%u", (unsigned)a->maxport);
573 static void dump_acl(const aclnode *a)
577 for (; a; a = a->next) {
581 fprintf(stderr, "noip(%d): [default policy: %s]\n", getpid(),
582 act == ALLOW ? "DENY" : "ALLOW");
587 /* Returns nonzero if the ACL A allows the socket address SA. */
588 static int acl_allows_p(const aclnode *a, const struct sockaddr *sa)
590 unsigned short port = port_from_sockaddr(sa);
594 D({ char buf[ADDRBUFSZ];
595 fprintf(stderr, "noip(%d): check %s\n", pid,
596 present_sockaddr(sa, 0, buf, sizeof(buf))); })
597 for (; a; a = a->next) {
598 D( dump_aclnode(a); )
599 if (a->af == sa->sa_family &&
600 sockaddr_in_range_p(sa, &a->minaddr, &a->maxaddr) &&
601 a->minport <= port && port <= a->maxport) {
602 D( fprintf(stderr, "noip(%d): aha! %s\n", pid,
603 a->act ? "ALLOW" : "DENY"); )
608 D( fprintf(stderr, "noip(%d): nothing found: %s\n", pid,
609 act ? "DENY" : "ALLOW"); )
613 /*----- Socket address conversion -----------------------------------------*/
615 /* Return a uniformly distributed integer between MIN and MAX inclusive. */
616 static unsigned randrange(unsigned min, unsigned max)
620 /* It's so nice not to have to care about the quality of the generator
624 for (mask = 1; mask < max; mask = (mask << 1) | 1)
626 do i = rand() & mask; while (i > max);
630 /* Return the status of Unix-domain socket address SUN. Returns: UNUSED if
631 * the socket doesn't exist; USED if the path refers to an active socket, or
632 * isn't really a socket at all, or we can't tell without a careful search
633 * and QUICKP is set; or STALE if the file refers to a socket which isn't
634 * being used any more.
636 static int unix_socket_status(struct sockaddr_un *sun, int quickp)
644 /* If we can't find the socket node, then it's definitely not in use. If
645 * we get some other error, then this socket is weird.
647 if (stat(sun->sun_path, &st))
648 return (errno == ENOENT ? UNUSED : USED);
650 /* If it's not a socket, then something weird is going on. If we're just
651 * probing quickly to find a spare port, then existence is sufficient to
654 if (!S_ISSOCK(st.st_mode) || quickp)
657 /* The socket's definitely there, but is anyone actually still holding it
658 * open? The only way I know to discover this is to trundle through
659 * `/proc/net/unix'. If there's no entry, then the socket must be stale.
662 if ((fp = fopen("/proc/net/unix", "r")) == 0)
664 if (!fgets(buf, sizeof(buf), fp)) goto done; /* skip header */
665 len = strlen(sun->sun_path);
666 while (fgets(buf, sizeof(buf), fp)) {
668 if (n >= len + 2 && buf[n - len - 2] == ' ' && buf[n - 1] == '\n' &&
669 memcmp(buf + n - len - 1, sun->sun_path, len) == 0)
682 /* Encode SA as a Unix-domain address SUN, and return whether it's currently
685 static int encode_single_inet_addr(const struct sockaddr *sa,
686 struct sockaddr_un *sun,
692 snprintf(sun->sun_path, sizeof(sun->sun_path), "%s/%s", sockdir,
693 present_sockaddr(sa, 0, buf, sizeof(buf)));
694 if ((rc = unix_socket_status(sun, quickp)) == USED) return (USED);
695 else if (rc == STALE) unlink(sun->sun_path);
699 /* Convert the IP address SA to a Unix-domain address SUN. Fail if the
700 * address seems already taken. If DESPARATEP then try cleaning up stale old
703 static int encode_unused_inet_addr(struct sockaddr *sa,
704 struct sockaddr_un *sun,
708 struct sockaddr_un wsun;
709 int port = port_from_sockaddr(sa);
711 /* First, look for an exact match. Only look quickly unless we're
712 * desperate. If the socket is in use, we fail here. (This could get
713 * racy. Let's not worry about that for now.)
715 if (encode_single_inet_addr(sa, sun, !desperatep) == USED)
718 /* Next, check the corresponding wildcard address, so as to avoid
719 * inadvertant collisions with listeners. Do this in the same way.
721 wildcard_address(sa->sa_family, &waddr.sa);
722 port_to_sockaddr(&waddr.sa, port);
723 if (encode_single_inet_addr(&waddr.sa, &wsun, !desperatep) == USED)
730 /* Encode the Internet address SA as a Unix-domain address SUN. If the flag
731 * `ENCF_FRESH' is set, and SA's port number is zero, then we pick an
732 * arbitrary local port. Otherwise we pick the port given. There's an
733 * unpleasant hack to find servers bound to local wildcard addresses.
734 * Returns zero on success; -1 on failure.
736 #define ENCF_FRESH 1u
737 static int encode_inet_addr(struct sockaddr_un *sun,
738 const struct sockaddr *sa,
744 int port = port_from_sockaddr(sa);
747 D( fprintf(stderr, "noip(%d): encode %s (%s)", getpid(),
748 present_sockaddr(sa, 0, buf, sizeof(buf)),
749 (f&ENCF_FRESH) ? "FRESH" : "EXISTING"); )
751 /* Start making the Unix-domain address. */
752 sun->sun_family = AF_UNIX;
754 if (port || !(f&ENCF_FRESH)) {
756 /* Try the address as given. If it's in use, or we don't necessarily
757 * want an existing socket, then we're done.
759 if (encode_single_inet_addr(sa, sun, 0) == USED || (f&ENCF_FRESH))
762 /* We're looking for a socket which already exists. Try the
763 * corresponding wildcard address.
765 wildcard_address(sa->sa_family, &addr.sa);
766 port_to_sockaddr(&addr.sa, port);
767 encode_single_inet_addr(&addr.sa, sun, 0);
770 /* We want a fresh new socket. */
772 /* Make a copy of the given address, because we're going to mangle it. */
773 copy_sockaddr(&addr.sa, sa);
775 /* Try a few random-ish port numbers to see if any of them is spare. */
776 for (i = 0; i < 10; i++) {
777 port_to_sockaddr(&addr.sa, randrange(minautoport, maxautoport));
778 if (!encode_unused_inet_addr(&addr.sa, sun, 0)) goto found;
781 /* Things must be getting tight. Work through all of the autoport range
782 * to see if we can find a spare one. The first time, just do it the
783 * quick way; if that doesn't work, then check harder for stale sockets.
785 for (desperatep = 0; desperatep < 2; desperatep++) {
786 for (i = minautoport; i <= maxautoport; i++) {
787 port_to_sockaddr(&addr.sa, i);
788 if (!encode_unused_inet_addr(&addr.sa, sun, 0)) goto found;
792 /* We failed to find any free ports. */
794 D( fprintf(stderr, " -- can't resolve\n"); )
800 D( fprintf(stderr, " -> `%s'\n", sun->sun_path); )
804 /* Decode the Unix address SUN to an Internet address SIN. If AF_HINT is
805 * nonzero, an empty address (indicative of an unbound Unix-domain socket) is
806 * translated to a wildcard Internet address of the appropriate family.
807 * Returns zero on success; -1 on failure (e.g., it wasn't one of our
810 static int decode_inet_addr(struct sockaddr *sa, int af_hint,
811 const struct sockaddr_un *sun,
815 size_t n = strlen(sockdir), nn;
818 if (!sa) sa = &addr.sa;
819 if (sun->sun_family != AF_UNIX) return (-1);
820 if (len > sizeof(*sun)) return (-1);
821 ((char *)sun)[len] = 0;
822 nn = strlen(sun->sun_path);
823 D( fprintf(stderr, "noip(%d): decode `%s'", getpid(), sun->sun_path); )
824 if (af_hint && !sun->sun_path[0]) {
825 wildcard_address(af_hint, sa);
826 D( fprintf(stderr, " -- unbound socket\n"); )
829 if (nn < n + 1 || nn - n >= sizeof(buf) || sun->sun_path[n] != '/' ||
830 memcmp(sun->sun_path, sockdir, n) != 0) {
831 D( fprintf(stderr, " -- not one of ours\n"); )
834 if (parse_sockaddr(sa, sun->sun_path + n + 1)) return (-1);
835 D( fprintf(stderr, " -> %s\n",
836 present_sockaddr(sa, 0, buf, sizeof(buf))); )
840 /* SK is (or at least might be) a Unix-domain socket we created when an
841 * Internet socket was asked for. We've decided it should be an Internet
842 * socket after all, with family AF_HINT, so convert it. If TMP is not null,
843 * then don't replace the existing descriptor: store the new socket in *TMP
846 static int fixup_real_ip_socket(int sk, int af_hint, int *tmp)
851 struct sockaddr_un sun;
864 _(LINGER, struct linger) \
867 _(RCVTIMEO, struct timeval) \
868 _(SNDTIMEO, struct timeval)
871 if (real_getsockname(sk, SA(&sun), &len))
873 if (decode_inet_addr(&addr.sa, af_hint, &sun, len))
874 return (0); /* Not one of ours */
876 if (real_getsockopt(sk, SOL_SOCKET, SO_TYPE, &type, &len) < 0 ||
877 (nsk = real_socket(addr.sa.sa_family, type, 0)) < 0)
879 #define FIX(opt, ty) do { \
882 if (real_getsockopt(sk, SOL_SOCKET, SO_##opt, &ov_, &len) < 0 || \
883 real_setsockopt(nsk, SOL_SOCKET, SO_##opt, &ov_, len)) { \
893 if ((f = fcntl(sk, F_GETFL)) < 0 ||
894 (fd = fcntl(sk, F_GETFD)) < 0 ||
895 fcntl(nsk, F_SETFL, f) < 0 ||
900 unlink(sun.sun_path);
902 if (fcntl(sk, F_SETFD, fd) < 0) {
903 perror("noip: fixup_real_ip_socket F_SETFD");
910 /* We found the real address SA, with length LEN; if it's a Unix-domain
911 * address corresponding to a fake socket, convert it to cover up the
912 * deception. Whatever happens, put the result at FAKE and store its length
915 static void return_fake_name(struct sockaddr *sa, socklen_t len,
916 struct sockaddr *fake, socklen_t *fakelen)
921 if (sa->sa_family == AF_UNIX &&
922 !decode_inet_addr(&addr.sa, 0, SUN(sa), len)) {
924 len = family_socklen(addr.sa.sa_family);
927 if (len > *fakelen) len = *fakelen;
928 if (len > 0) memcpy(fake, sa, len);
932 /*----- Implicit binding --------------------------------------------------*/
936 static void dump_impbind(const impbind *i)
940 fprintf(stderr, "noip(%d): ", getpid());
941 dump_addrrange(i->af, &i->minaddr, &i->maxaddr);
943 case SAME: fprintf(stderr, " <self>"); break;
945 fprintf(stderr, " %s", inet_ntop(i->af, &i->bindaddr,
953 static void dump_impbind_list(void)
957 for (i = impbinds; i; i = i->next) dump_impbind(i);
962 /* The socket SK is about to be used to communicate with the remote address
963 * SA. Assign it a local address so that getpeername(2) does something
966 static int do_implicit_bind(int sk, const struct sockaddr **sa,
967 socklen_t *len, struct sockaddr_un *sun)
970 socklen_t mylen = sizeof(*sun);
974 if (acl_allows_p(connect_real, *sa)) {
975 if (fixup_real_ip_socket(sk, (*sa)->sa_family, 0)) return (-1);
977 if (real_getsockname(sk, SA(sun), &mylen) < 0) return (-1);
978 if (sun->sun_family == AF_UNIX) {
979 if (mylen < sizeof(*sun)) ((char *)sun)[mylen] = 0;
980 if (!sun->sun_path[0]) {
981 D( fprintf(stderr, "noip(%d): checking impbind list...\n", pid); )
982 for (i = impbinds; i; i = i->next) {
983 D( dump_impbind(i); )
984 if ((*sa)->sa_family == i->af &&
985 sockaddr_in_range_p(*sa, &i->minaddr, &i->maxaddr)) {
986 D( fprintf(stderr, "noip(%d): match!\n", pid); )
987 addr.sa.sa_family = (*sa)->sa_family;
988 ipaddr_to_sockaddr(&addr.sa, &i->bindaddr);
992 D( fprintf(stderr, "noip(%d): no match; using wildcard\n", pid); )
993 wildcard_address((*sa)->sa_family, &addr.sa);
995 encode_inet_addr(sun, &addr.sa, ENCF_FRESH);
996 if (real_bind(sk, SA(sun), SUN_LEN(sun))) return (-1);
998 encode_inet_addr(sun, *sa, 0);
1000 *len = SUN_LEN(sun);
1006 /*----- Configuration -----------------------------------------------------*/
1008 /* Return the process owner's home directory. */
1009 static char *home(void)
1014 if (getuid() == uid &&
1015 (p = getenv("HOME")) != 0)
1017 else if ((pw = getpwuid(uid)) != 0)
1018 return (pw->pw_dir);
1023 /* Return a good temporary directory to use. */
1024 static char *tmpdir(void)
1028 if ((p = getenv("TMPDIR")) != 0) return (p);
1029 else if ((p = getenv("TMP")) != 0) return (p);
1030 else return ("/tmp");
1033 /* Return the user's name, or at least something distinctive. */
1034 static char *user(void)
1036 static char buf[16];
1040 if ((p = getenv("USER")) != 0) return (p);
1041 else if ((p = getenv("LOGNAME")) != 0) return (p);
1042 else if ((pw = getpwuid(uid)) != 0) return (pw->pw_name);
1044 snprintf(buf, sizeof(buf), "uid-%lu", (unsigned long)uid);
1049 /* Skip P over space characters. */
1050 #define SKIPSPC do { while (*p && isspace(UC(*p))) p++; } while (0)
1052 /* Set Q to point to the next word following P, null-terminate it, and step P
1054 #define NEXTWORD(q) do { \
1057 while (*p && !isspace(UC(*p))) p++; \
1061 /* Set Q to point to the next dotted-quad address, store the ending delimiter
1062 * in DEL, null-terminate it, and step P past it. */
1063 static void parse_nextaddr(char **pp, char **qq, int *del)
1071 p += strcspn(p, "]");
1076 while (*p && (*p == '.' || isdigit(UC(*p)))) p++;
1083 /* Set Q to point to the next decimal number, store the ending delimiter in
1084 * DEL, null-terminate it, and step P past it. */
1085 #define NEXTNUMBER(q, del) do { \
1088 while (*p && isdigit(UC(*p))) p++; \
1093 /* Push the character DEL back so we scan it again, unless it's zero
1095 #define RESCAN(del) do { if (del) *--p = del; } while (0)
1097 /* Evaluate true if P is pointing to the word KW (and not some longer string
1098 * of which KW is a prefix). */
1100 #define KWMATCHP(kw) (strncmp(p, kw, sizeof(kw) - 1) == 0 && \
1101 !isalnum(UC(p[sizeof(kw) - 1])) && \
1102 (p += sizeof(kw) - 1))
1104 /* Parse a port list, starting at *PP. Port lists have the form
1105 * [:LOW[-HIGH]]: if omitted, all ports are included; if HIGH is omitted,
1106 * it's as if HIGH = LOW. Store LOW in *MIN, HIGH in *MAX and set *PP to the
1107 * rest of the string.
1109 static void parse_ports(char **pp, unsigned short *min, unsigned short *max)
1116 { *min = 0; *max = 0xffff; }
1119 NEXTNUMBER(q, del); *min = strtoul(q, 0, 0); RESCAN(del);
1122 { p++; NEXTNUMBER(q, del); *max = strtoul(q, 0, 0); RESCAN(del); }
1129 /* Parse an address range designator starting at PP and store a
1130 * representation of it in R. An address range designator has the form:
1132 * any | local | ADDR | ADDR - ADDR | ADDR/ADDR | ADDR/INT
1134 static int parse_addrrange(char **pp, addrrange *r)
1142 if (KWMATCHP("any")) r->type = ANY;
1143 else if (KWMATCHP("local")) r->type = LOCAL;
1145 parse_nextaddr(&p, &q, &del);
1146 af = guess_address_family(q);
1147 if (inet_pton(af, q, &r->u.range.min) <= 0) goto bad;
1152 parse_nextaddr(&p, &q, &del);
1153 if (inet_pton(af, q, &r->u.range.max) <= 0) goto bad;
1155 } else if (*p == '/') {
1158 n = strtoul(q, 0, 0);
1159 r->u.range.max = r->u.range.min;
1160 mask_address(af, &r->u.range.min, n, 0);
1161 mask_address(af, &r->u.range.max, n, 1);
1164 r->u.range.max = r->u.range.min;
1175 /* Call FUNC on each individual address range in R. */
1176 static void foreach_addrrange(const addrrange *r,
1177 void (*func)(int af,
1183 ipaddr minaddr, maxaddr;
1190 for (i = 0; address_families[i] >= 0; i++) {
1191 af = address_families[i];
1192 memset(&minaddr, 0, sizeof(minaddr));
1193 maxaddr = minaddr; mask_address(af, &maxaddr, 0, 1);
1194 func(af, &minaddr, &maxaddr, p);
1198 for (i = 0; address_families[i] >= 0; i++) {
1199 af = address_families[i];
1200 memset(&minaddr, 0, sizeof(minaddr));
1201 maxaddr = minaddr; mask_address(af, &maxaddr, 0, 1);
1202 func(af, &minaddr, &minaddr, p);
1203 func(af, &maxaddr, &maxaddr, p);
1205 for (i = 0; i < n_local_ipaddrs; i++) {
1206 func(local_ipaddrs[i].af,
1207 &local_ipaddrs[i].addr, &local_ipaddrs[i].addr,
1212 func(r->u.range.af, &r->u.range.min, &r->u.range.max, p);
1219 struct add_aclnode_ctx {
1221 unsigned short minport, maxport;
1225 static void add_aclnode(int af, const ipaddr *min, const ipaddr *max,
1228 struct add_aclnode_ctx *ctx = p;
1234 a->minaddr = *min; a->maxaddr = *max;
1235 a->minport = ctx->minport; a->maxport = ctx->maxport;
1236 **ctx->tail = a; *ctx->tail = &a->next;
1239 /* Parse an ACL line. *PP points to the end of the line; *TAIL points to
1240 * the list tail (i.e., the final link in the list). An ACL entry has the
1241 * form +|- ADDR-RANGE PORTS
1242 * where PORTS is parsed by parse_ports above; an ACL line consists of a
1243 * comma-separated sequence of entries..
1245 static void parse_acl_line(char **pp, aclnode ***tail)
1247 struct add_aclnode_ctx ctx;
1254 if (*p == '+') ctx.act = ALLOW;
1255 else if (*p == '-') ctx.act = DENY;
1259 if (parse_addrrange(&p, &r)) goto bad;
1260 parse_ports(&p, &ctx.minport, &ctx.maxport);
1261 foreach_addrrange(&r, add_aclnode, &ctx);
1263 if (*p != ',') break;
1271 D( fprintf(stderr, "noip(%d): bad acl spec (ignored)\n", getpid()); )
1275 /* Parse an ACL from an environment variable VAR, attaching it to the list
1278 static void parse_acl_env(const char *var, aclnode ***tail)
1282 if ((p = getenv(var)) != 0) {
1284 parse_acl_line(&q, tail);
1289 struct add_impbind_ctx {
1294 static void add_impbind(int af, const ipaddr *min, const ipaddr *max,
1297 struct add_impbind_ctx *ctx = p;
1300 if (ctx->af && af != ctx->af) return;
1304 i->minaddr = *min; i->maxaddr = *max;
1306 case EXPLICIT: i->bindaddr = ctx->addr;
1310 *impbind_tail = i; impbind_tail = &i->next;
1313 /* Parse an implicit-bind line. An implicit-bind entry has the form
1314 * ADDR-RANGE {ADDR | same}
1316 static void parse_impbind_line(char **pp)
1318 struct add_impbind_ctx ctx;
1324 if (parse_addrrange(&p, &r)) goto bad;
1326 if (KWMATCHP("same")) {
1331 parse_nextaddr(&p, &q, &del);
1332 ctx.af = guess_address_family(q);
1333 if (inet_pton(ctx.af, q, &ctx.addr) < 0) goto bad;
1336 foreach_addrrange(&r, add_impbind, &ctx);
1338 if (*p != ',') break;
1346 D( fprintf(stderr, "noip(%d): bad implicit-bind spec (ignored)\n",
1351 /* Parse implicit-bind instructions from an environment variable VAR,
1352 * attaching it to the list.
1354 static void parse_impbind_env(const char *var)
1358 if ((p = getenv(var)) != 0) {
1360 parse_impbind_line(&q);
1365 /* Parse the autoports configuration directive. Syntax is MIN - MAX. */
1366 static void parse_autoports(char **pp)
1373 NEXTNUMBER(q, del); x = strtoul(q, 0, 0); RESCAN(del);
1375 if (*p != '-') goto bad;
1377 NEXTNUMBER(q, del); y = strtoul(q, 0, 0); RESCAN(del);
1378 minautoport = x; maxautoport = y;
1379 SKIPSPC; if (*p) goto bad;
1384 D( fprintf(stderr, "noip(%d): bad port range (ignored)\n", getpid()); )
1388 /* Read the configuration from the config file and environment. */
1389 static void readconfig(void)
1397 parse_acl_env("NOIP_REALBIND_BEFORE", &bind_tail);
1398 parse_acl_env("NOIP_REALCONNECT_BEFORE", &connect_tail);
1399 parse_impbind_env("NOIP_IMPBIND_BEFORE");
1400 if ((p = getenv("NOIP_AUTOPORTS")) != 0) {
1402 parse_autoports(&q);
1405 if ((p = getenv("NOIP_CONFIG")) == 0)
1406 snprintf(p = buf, sizeof(buf), "%s/.noip", home());
1407 D( fprintf(stderr, "noip(%d): config file: %s\n", pid, p); )
1409 if ((fp = fopen(p, "r")) == 0) {
1410 D( fprintf(stderr, "noip(%d): couldn't read config: %s\n",
1411 pid, strerror(errno)); )
1414 while (fgets(buf, sizeof(buf), fp)) {
1419 if (!*p || *p == '#') continue;
1420 while (n && isspace(UC(buf[n - 1]))) n--;
1425 if (strcmp(cmd, "socketdir") == 0)
1426 sockdir = xstrdup(p);
1427 else if (strcmp(cmd, "realbind") == 0)
1428 parse_acl_line(&p, &bind_tail);
1429 else if (strcmp(cmd, "realconnect") == 0)
1430 parse_acl_line(&p, &connect_tail);
1431 else if (strcmp(cmd, "impbind") == 0)
1432 parse_impbind_line(&p);
1433 else if (strcmp(cmd, "autoports") == 0)
1434 parse_autoports(&p);
1435 else if (strcmp(cmd, "debug") == 0)
1436 debug = *p ? atoi(p) : 1;
1438 D( fprintf(stderr, "noip(%d): bad config command %s\n", pid, cmd); )
1443 parse_acl_env("NOIP_REALBIND", &bind_tail);
1444 parse_acl_env("NOIP_REALCONNECT", &connect_tail);
1445 parse_impbind_env("NOIP_IMPBIND");
1446 parse_acl_env("NOIP_REALBIND_AFTER", &bind_tail);
1447 parse_acl_env("NOIP_REALCONNECT_AFTER", &connect_tail);
1448 parse_impbind_env("NOIP_IMPBIND_AFTER");
1452 if (!sockdir) sockdir = getenv("NOIP_SOCKETDIR");
1454 snprintf(buf, sizeof(buf), "%s/noip-%s", tmpdir(), user());
1455 sockdir = xstrdup(buf);
1457 D( fprintf(stderr, "noip(%d): socketdir: %s\n", pid, sockdir);
1458 fprintf(stderr, "noip(%d): autoports: %u-%u\n",
1459 pid, minautoport, maxautoport);
1460 fprintf(stderr, "noip(%d): realbind acl:\n", pid);
1461 dump_acl(bind_real);
1462 fprintf(stderr, "noip(%d): realconnect acl:\n", pid);
1463 dump_acl(connect_real);
1464 fprintf(stderr, "noip(%d): impbind list:\n", pid);
1465 dump_impbind_list(); )
1468 /*----- Overridden system calls -------------------------------------------*/
1470 static void dump_syserr(long rc)
1471 { fprintf(stderr, " => %ld (E%d)\n", rc, errno); }
1473 static void dump_sysresult(long rc)
1475 if (rc < 0) dump_syserr(rc);
1476 else fprintf(stderr, " => %ld\n", rc);
1479 static void dump_addrresult(long rc, const struct sockaddr *sa,
1482 char addrbuf[ADDRBUFSZ];
1484 if (rc < 0) dump_syserr(rc);
1486 fprintf(stderr, " => %ld [%s]\n", rc,
1487 present_sockaddr(sa, len, addrbuf, sizeof(addrbuf)));
1491 int socket(int pf, int ty, int proto)
1495 D( fprintf(stderr, "noip(%d): SOCKET pf=%d, type=%d, proto=%d",
1496 getpid(), pf, ty, proto); )
1500 if (!family_known_p(pf)) {
1501 D( fprintf(stderr, " -> unknown; refuse\n"); )
1502 errno = EAFNOSUPPORT;
1505 D( fprintf(stderr, " -> inet; substitute"); )
1513 D( fprintf(stderr, " -> safe; permit"); )
1516 sk = real_socket(pf, ty, proto);
1517 D( dump_sysresult(sk); )
1521 int socketpair(int pf, int ty, int proto, int *sk)
1525 D( fprintf(stderr, "noip(%d): SOCKETPAIR pf=%d, type=%d, proto=%d",
1526 getpid(), pf, ty, proto); )
1527 if (!family_known_p(pf))
1528 D( fprintf(stderr, " -> unknown; permit"); )
1530 D( fprintf(stderr, " -> inet; substitute"); )
1534 rc = real_socketpair(pf, ty, proto, sk);
1535 D( if (rc < 0) dump_syserr(rc);
1536 else fprintf(stderr, " => %d (%d, %d)\n", rc, sk[0], sk[1]); )
1540 int bind(int sk, const struct sockaddr *sa, socklen_t len)
1542 struct sockaddr_un sun;
1546 D({ char buf[ADDRBUFSZ];
1547 fprintf(stderr, "noip(%d): BIND sk=%d, sa[%d]=%s", pid,
1548 sk, len, present_sockaddr(sa, len, buf, sizeof(buf))); })
1550 if (!family_known_p(sa->sa_family))
1551 D( fprintf(stderr, " -> unknown af; pass through"); )
1553 D( fprintf(stderr, " -> checking...\n"); )
1555 if (acl_allows_p(bind_real, sa)) {
1556 if (fixup_real_ip_socket(sk, sa->sa_family, 0))
1559 encode_inet_addr(&sun, sa, ENCF_FRESH);
1561 len = SUN_LEN(&sun);
1564 D( fprintf(stderr, "noip(%d): BIND ...", pid); )
1566 rc = real_bind(sk, sa, len);
1567 D( dump_sysresult(rc); )
1571 int connect(int sk, const struct sockaddr *sa, socklen_t len)
1573 struct sockaddr_un sun;
1577 D({ char buf[ADDRBUFSZ];
1578 fprintf(stderr, "noip(%d): CONNECT sk=%d, sa[%d]=%s", pid,
1579 sk, len, present_sockaddr(sa, len, buf, sizeof(buf))); })
1581 if (!family_known_p(sa->sa_family)) {
1582 D( fprintf(stderr, " -> unknown af; pass through"); )
1583 rc = real_connect(sk, sa, len);
1585 D( fprintf(stderr, " -> checking...\n"); )
1587 do_implicit_bind(sk, &sa, &len, &sun);
1589 D( fprintf(stderr, "noip(%d): CONNECT ...", pid); )
1590 rc = real_connect(sk, sa, len);
1593 case ENOENT: errno = ECONNREFUSED; break;
1597 D( dump_sysresult(rc); )
1601 ssize_t sendto(int sk, const void *buf, size_t len, int flags,
1602 const struct sockaddr *to, socklen_t tolen)
1604 struct sockaddr_un sun;
1608 D({ char addrbuf[ADDRBUFSZ];
1609 fprintf(stderr, "noip(%d): SENDTO sk=%d, len=%lu, flags=%d, to[%d]=%s",
1610 pid, sk, (unsigned long)len, flags, tolen,
1611 present_sockaddr(to, tolen, addrbuf, sizeof(addrbuf))); })
1614 D( fprintf(stderr, " -> null address; leaving"); )
1615 else if (!family_known_p(to->sa_family))
1616 D( fprintf(stderr, " -> unknown af; pass through"); )
1618 D( fprintf(stderr, " -> checking...\n"); )
1620 do_implicit_bind(sk, &to, &tolen, &sun);
1622 D( fprintf(stderr, "noip(%d): SENDTO ...", pid); )
1624 n = real_sendto(sk, buf, len, flags, to, tolen);
1625 D( dump_sysresult(n); )
1629 ssize_t recvfrom(int sk, void *buf, size_t len, int flags,
1630 struct sockaddr *from, socklen_t *fromlen)
1633 socklen_t mylen = sizeof(sabuf);
1637 D( fprintf(stderr, "noip(%d): RECVFROM sk=%d, len=%lu, flags=%d",
1638 pid, sk, (unsigned long)len, flags); )
1641 D( fprintf(stderr, " -> null addr; pass through"); )
1642 n = real_recvfrom(sk, buf, len, flags, 0, 0);
1645 n = real_recvfrom(sk, buf, len, flags, SA(sabuf), &mylen);
1647 D( fprintf(stderr, " -> converting...\n"); )
1648 return_fake_name(SA(sabuf), mylen, from, fromlen);
1649 D( fprintf(stderr, "noip(%d): ... RECVFROM", pid); )
1653 D( dump_addrresult(n, from, fromlen ? *fromlen : 0); )
1657 ssize_t sendmsg(int sk, const struct msghdr *msg, int flags)
1659 struct sockaddr_un sun;
1660 const struct sockaddr *sa = SA(msg->msg_name);
1661 struct msghdr mymsg;
1665 D({ char addrbuf[ADDRBUFSZ];
1666 fprintf(stderr, "noip(%d): SENDMSG sk=%d, "
1667 "msg_flags=%d, msg_name[%d]=%s, ...",
1668 pid, sk, msg->msg_flags, msg->msg_namelen,
1669 present_sockaddr(sa, msg->msg_namelen,
1670 addrbuf, sizeof(addrbuf))); })
1673 D( fprintf(stderr, " -> null address; leaving"); )
1674 else if (!family_known_p(sa->sa_family))
1675 D( fprintf(stderr, " -> unknown af; pass through"); )
1677 D( fprintf(stderr, " -> checking...\n"); )
1680 do_implicit_bind(sk, &sa, &mymsg.msg_namelen, &sun);
1681 mymsg.msg_name = SA(sa);
1684 D( fprintf(stderr, "noip(%d): SENDMSG ...", pid); )
1686 n = real_sendmsg(sk, msg, flags);
1687 D( dump_sysresult(n); )
1691 ssize_t recvmsg(int sk, struct msghdr *msg, int flags)
1694 struct sockaddr *sa = SA(msg->msg_name);
1695 socklen_t len = msg->msg_namelen;
1699 D( fprintf(stderr, "noip(%d): RECVMSG sk=%d msg_flags=%d, ...",
1700 pid, sk, msg->msg_flags); )
1702 if (!msg->msg_name) {
1703 D( fprintf(stderr, " -> null addr; pass through"); )
1704 return (real_recvmsg(sk, msg, flags));
1707 msg->msg_name = sabuf;
1708 msg->msg_namelen = sizeof(sabuf);
1709 n = real_recvmsg(sk, msg, flags);
1711 D( fprintf(stderr, " -> converting...\n"); )
1712 return_fake_name(SA(sabuf), msg->msg_namelen, sa, &len);
1713 D( fprintf(stderr, "noip(%d): ... RECVMSG", pid); )
1716 msg->msg_namelen = len;
1719 D( dump_addrresult(n, sa, len); )
1723 int accept(int sk, struct sockaddr *sa, socklen_t *len)
1726 socklen_t mylen = sizeof(sabuf);
1730 D( fprintf(stderr, "noip(%d): ACCEPT sk=%d", pid, sk); )
1732 nsk = real_accept(sk, SA(sabuf), &mylen);
1733 if (nsk < 0) /* failed */;
1734 else if (!sa) D( fprintf(stderr, " -> address not wanted"); )
1736 D( fprintf(stderr, " -> converting...\n"); )
1737 return_fake_name(SA(sabuf), mylen, sa, len);
1738 D( fprintf(stderr, "noip(%d): ... ACCEPT", pid); )
1740 D( dump_addrresult(nsk, sa, len ? *len : 0); )
1744 int getsockname(int sk, struct sockaddr *sa, socklen_t *len)
1747 socklen_t mylen = sizeof(sabuf);
1751 D( fprintf(stderr, "noip(%d): GETSOCKNAME sk=%d", pid, sk); )
1752 rc = real_getsockname(sk, SA(sabuf), &mylen);
1754 D( fprintf(stderr, " -> converting...\n"); )
1755 return_fake_name(SA(sabuf), mylen, sa, len);
1756 D( fprintf(stderr, "noip(%d): ... GETSOCKNAME", pid); )
1758 D( dump_addrresult(rc, sa, *len); )
1762 int getpeername(int sk, struct sockaddr *sa, socklen_t *len)
1765 socklen_t mylen = sizeof(sabuf);
1769 D( fprintf(stderr, "noip(%d): GETPEERNAME sk=%d", pid, sk); )
1770 rc = real_getpeername(sk, SA(sabuf), &mylen);
1772 D( fprintf(stderr, " -> converting...\n"); )
1773 return_fake_name(SA(sabuf), mylen, sa, len);
1774 D( fprintf(stderr, "noip(%d): ... GETPEERNAME", pid); )
1776 D( dump_addrresult(rc, sa, *len); )
1780 int getsockopt(int sk, int lev, int opt, void *p, socklen_t *len)
1791 return (real_getsockopt(sk, lev, opt, p, len));
1794 int setsockopt(int sk, int lev, int opt, const void *p, socklen_t len)
1804 case SO_BINDTODEVICE:
1805 case SO_ATTACH_FILTER:
1806 case SO_DETACH_FILTER:
1809 return (real_setsockopt(sk, lev, opt, p, len));
1812 int ioctl(int fd, unsigned long op, ...)
1820 arg = va_arg(ap, void *);
1824 case SIOCGIFBRDADDR:
1825 case SIOCGIFDSTADDR:
1826 case SIOCGIFNETMASK:
1828 if (fixup_real_ip_socket(fd, AF_INET, &sk)) goto real;
1830 rc = real_ioctl(sk, op, arg);
1831 PRESERVING_ERRNO({ close(sk); });
1835 rc = real_ioctl(fd, op, arg);
1842 /*----- Initialization ----------------------------------------------------*/
1844 /* Clean up the socket directory, deleting stale sockets. */
1845 static void cleanup_sockdir(void)
1850 struct sockaddr_un sun;
1854 if ((dir = opendir(sockdir)) == 0) return;
1855 sun.sun_family = AF_UNIX;
1856 while ((d = readdir(dir)) != 0) {
1857 if (d->d_name[0] == '.') continue;
1858 snprintf(sun.sun_path, sizeof(sun.sun_path),
1859 "%s/%s", sockdir, d->d_name);
1860 if (decode_inet_addr(&addr.sa, 0, &sun, SUN_LEN(&sun)) ||
1861 stat(sun.sun_path, &st) ||
1862 !S_ISSOCK(st.st_mode)) {
1863 D( fprintf(stderr, "noip(%d): ignoring unknown socketdir entry `%s'\n",
1864 pid, sun.sun_path); )
1867 if (unix_socket_status(&sun, 0) == STALE) {
1868 D( fprintf(stderr, "noip(%d): clearing away stale socket %s\n",
1870 unlink(sun.sun_path);
1876 /* Find the addresses attached to local network interfaces, and remember them
1879 static void get_local_ipaddrs(void)
1881 struct ifaddrs *ifa_head, *ifa;
1886 D( fprintf(stderr, "noip(%d): fetching local addresses...\n", pid); )
1887 if (getifaddrs(&ifa_head)) { perror("getifaddrs"); return; }
1888 for (n_local_ipaddrs = 0, ifa = ifa_head;
1889 n_local_ipaddrs < MAX_LOCAL_IPADDRS && ifa;
1890 ifa = ifa->ifa_next) {
1891 if (!ifa->ifa_addr || !family_known_p(ifa->ifa_addr->sa_family))
1893 ipaddr_from_sockaddr(&a, ifa->ifa_addr);
1894 D({ char buf[ADDRBUFSZ];
1895 fprintf(stderr, "noip(%d): local addr %s = %s", pid,
1897 inet_ntop(ifa->ifa_addr->sa_family, &a,
1898 buf, sizeof(buf))); })
1899 for (i = 0; i < n_local_ipaddrs; i++) {
1900 if (ifa->ifa_addr->sa_family == local_ipaddrs[i].af &&
1901 ipaddr_equal_p(local_ipaddrs[i].af, &a, &local_ipaddrs[i].addr)) {
1902 D( fprintf(stderr, " (duplicate)\n"); )
1906 D( fprintf(stderr, "\n"); )
1907 local_ipaddrs[n_local_ipaddrs].af = ifa->ifa_addr->sa_family;
1908 local_ipaddrs[n_local_ipaddrs].addr = a;
1912 freeifaddrs(ifa_head);
1915 /* Print the given message to standard error. Avoids stdio. */
1916 static void printerr(const char *p)
1917 { if (write(STDERR_FILENO, p, strlen(p))) ; }
1919 /* Create the socket directory, being careful about permissions. */
1920 static void create_sockdir(void)
1924 if (lstat(sockdir, &st)) {
1925 if (errno == ENOENT) {
1926 if (mkdir(sockdir, 0700)) {
1927 perror("noip: creating socketdir");
1930 if (!lstat(sockdir, &st))
1933 perror("noip: checking socketdir");
1937 if (!S_ISDIR(st.st_mode)) {
1938 printerr("noip: bad socketdir: not a directory\n");
1941 if (st.st_uid != uid) {
1942 printerr("noip: bad socketdir: not owner\n");
1945 if (st.st_mode & 077) {
1946 printerr("noip: bad socketdir: not private\n");
1951 /* Initialization function. */
1952 static void setup(void) __attribute__((constructor));
1953 static void setup(void)
1960 if ((p = getenv("NOIP_DEBUG")) && atoi(p))
1962 get_local_ipaddrs();
1969 /*----- That's all, folks -------------------------------------------------*/