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 { WANT_FRESH
, WANT_EXISTING
}; /* Socket address dispositions */
64 enum { DENY
, ALLOW
}; /* ACL verdicts */
66 static int address_families
[] = { AF_INET
, AF_INET6
, -1 };
70 /* Address representations. */
71 typedef union ipaddr
{
76 /* Convenient socket address hacking. */
77 typedef union address
{
79 struct sockaddr_in sin
;
80 struct sockaddr_in6 sin6
;
83 /* Access control list nodes */
84 typedef struct aclnode
{
88 ipaddr minaddr
, maxaddr
;
89 unsigned short minport
, maxport
;
92 /* Local address records */
93 typedef struct full_ipaddr
{
97 #define MAX_LOCAL_IPADDRS 64
98 static full_ipaddr local_ipaddrs
[MAX_LOCAL_IPADDRS
];
99 static int n_local_ipaddrs
;
101 /* General configuration */
103 static char *sockdir
= 0;
104 static int debug
= 0;
105 static unsigned minautoport
= 16384, maxautoport
= 65536;
107 /* Access control lists */
108 static aclnode
*bind_real
, **bind_tail
= &bind_real
;
109 static aclnode
*connect_real
, **connect_tail
= &connect_real
;
111 /*----- Import the real versions of functions -----------------------------*/
113 /* The list of functions to immport. */
115 _(socket, int, (int, int, int)) \
116 _(socketpair, int, (int, int, int, int *)) \
117 _(connect, int, (int, const struct sockaddr *, socklen_t)) \
118 _(bind, int, (int, const struct sockaddr *, socklen_t)) \
119 _(accept, int, (int, struct sockaddr *, socklen_t *)) \
120 _(getsockname, int, (int, struct sockaddr *, socklen_t *)) \
121 _(getpeername, int, (int, struct sockaddr *, socklen_t *)) \
122 _(getsockopt, int, (int, int, int, void *, socklen_t *)) \
123 _(setsockopt, int, (int, int, int, const void *, socklen_t)) \
124 _(sendto, ssize_t, (int, const void *buf, size_t, int, \
125 const struct sockaddr *to, socklen_t tolen)) \
126 _(recvfrom, ssize_t, (int, void *buf, size_t, int, \
127 struct sockaddr *from, socklen_t *fromlen)) \
128 _(sendmsg, ssize_t, (int, const struct msghdr *, int)) \
129 _(recvmsg, ssize_t, (int, struct msghdr *, int)) \
130 _(ioctl, int, (int, unsigned long, ...))
132 /* Function pointers to set up. */
133 #define DECL(imp, ret, args) static ret (*real_##imp) args;
137 /* Import the system calls. */
138 static void import(void)
140 #define IMPORT(imp, ret, args) \
141 real_##imp = (ret (*)args)dlsym(RTLD_NEXT, #imp);
146 /*----- Utilities ---------------------------------------------------------*/
148 /* Socket address casts */
149 #define SA(sa) ((struct sockaddr *)(sa))
150 #define SIN(sa) ((struct sockaddr_in *)(sa))
151 #define SIN6(sa) ((struct sockaddr_in6 *)(sa))
152 #define SUN(sa) ((struct sockaddr_un *)(sa))
155 #define UC(ch) ((unsigned char)(ch))
157 /* Memory allocation */
158 #define NEW(x) ((x) = xmalloc(sizeof(*x)))
159 #define NEWV(x, n) ((x) = xmalloc(sizeof(*x) * (n)))
163 # define D(body) { if (debug) { body } }
168 /* Preservation of error status */
169 #define PRESERVING_ERRNO(body) do { \
170 int _err = errno; { body } errno = _err; \
173 /* Allocate N bytes of memory; abort on failure. */
174 static void *xmalloc(size_t n
)
178 if ((p
= malloc(n
)) == 0) { perror("malloc"); exit(127); }
182 /* Allocate a copy of the null-terminated string P; abort on failure. */
183 static char *xstrdup(const char *p
)
185 size_t n
= strlen(p
) + 1;
186 char *q
= xmalloc(n
);
191 /*----- Address-type hacking ----------------------------------------------*/
193 /* If M is a simple mask, i.e., consists of a sequence of zero bits followed
194 * by a sequence of one bits, then return the length of the latter sequence
195 * (which may be zero); otherwise return -1.
197 static int simple_mask_length(unsigned long m
)
201 while (m
& 1) { n
++; m
>>= 1; }
205 /* Answer whether AF is an interesting address family. */
206 static int family_known_p(int af
)
217 /* Return the socket address length for address family AF. */
218 static socklen_t
family_socklen(int af
)
221 case AF_INET
: return (sizeof(struct sockaddr_in
));
222 case AF_INET6
: return (sizeof(struct sockaddr_in6
));
227 /* Return the width of addresses of kind AF. */
228 static int address_width(int af
)
231 case AF_INET
: return 32;
232 case AF_INET6
: return 128;
237 /* If addresses A and B share a common prefix then return its length;
238 * otherwise return -1.
240 static int common_prefix_length(int af
, const ipaddr
*a
, const ipaddr
*b
)
244 unsigned long aa
= ntohl(a
->v4
.s_addr
), bb
= ntohl(b
->v4
.s_addr
);
245 unsigned long m
= aa
^bb
;
246 if ((aa
&m
) == 0 && (bb
&m
) == m
) return (32 - simple_mask_length(m
));
250 const uint8_t *aa
= a
->v6
.s6_addr
, *bb
= b
->v6
.s6_addr
;
255 for (i
= 0; i
< 16 && aa
[i
] == bb
[i
]; i
++);
259 if ((aa
[i
]&m
) != 0 || (bb
[i
]&m
) != m
) return (-1);
260 n
+= 8 - simple_mask_length(m
);
261 for (i
++; i
< 16; i
++)
262 if (aa
[i
] || bb
[i
] != 0xff) return (-1);
271 /* Extract the port number (in host byte-order) from SA. */
272 static int port_from_sockaddr(const struct sockaddr
*sa
)
274 switch (sa
->sa_family
) {
275 case AF_INET
: return (ntohs(SIN(sa
)->sin_port
));
276 case AF_INET6
: return (ntohs(SIN6(sa
)->sin6_port
));
281 /* Store the port number PORT (in host byte-order) in SA. */
282 static void port_to_sockaddr(struct sockaddr
*sa
, int port
)
284 switch (sa
->sa_family
) {
285 case AF_INET
: SIN(sa
)->sin_port
= htons(port
); break;
286 case AF_INET6
: SIN6(sa
)->sin6_port
= htons(port
); break;
291 /* Extract the address part from SA and store it in A. */
292 static void ipaddr_from_sockaddr(ipaddr
*a
, const struct sockaddr
*sa
)
294 switch (sa
->sa_family
) {
295 case AF_INET
: a
->v4
= SIN(sa
)->sin_addr
; break;
296 case AF_INET6
: a
->v6
= SIN6(sa
)->sin6_addr
; break;
301 /* Copy a whole socket address about. */
302 static void copy_sockaddr(struct sockaddr
*sa_dst
,
303 const struct sockaddr
*sa_src
)
304 { memcpy(sa_dst
, sa_src
, family_socklen(sa_src
->sa_family
)); }
306 /* Answer whether two addresses are equal. */
307 static int ipaddr_equal_p(int af
, const ipaddr
*a
, const ipaddr
*b
)
310 case AF_INET
: return (a
->v4
.s_addr
== b
->v4
.s_addr
);
311 case AF_INET6
: return (memcmp(a
->v6
.s6_addr
, b
->v6
.s6_addr
, 16) == 0);
316 /* Answer whether the address part of SA is between A and B (inclusive). We
317 * assume that SA has the correct address family.
319 static int sockaddr_in_range_p(const struct sockaddr
*sa
,
320 const ipaddr
*a
, const ipaddr
*b
)
322 switch (sa
->sa_family
) {
324 unsigned long addr
= ntohl(SIN(sa
)->sin_addr
.s_addr
);
325 return (ntohl(a
->v4
.s_addr
) <= addr
&&
326 addr
<= ntohl(b
->v4
.s_addr
));
329 const uint8_t *ss
= SIN6(sa
)->sin6_addr
.s6_addr
;
330 const uint8_t *aa
= a
->v6
.s6_addr
, *bb
= b
->v6
.s6_addr
;
334 for (i
= 0; h
&& l
&& i
< 16; i
++, ss
++, aa
++, bb
++) {
335 if (*ss
< *aa
|| *bb
< *ss
) return (0);
336 if (*aa
< *ss
) l
= 0;
337 if (*ss
< *bb
) h
= 0;
346 /* Fill in SA with the appropriate wildcard address. */
347 static void wildcard_address(int af
, struct sockaddr
*sa
)
351 struct sockaddr_in
*sin
= SIN(sa
);
352 memset(sin
, 0, sizeof(*sin
));
353 sin
->sin_family
= AF_INET
;
355 sin
->sin_addr
.s_addr
= INADDR_ANY
;
358 struct sockaddr_in6
*sin6
= SIN6(sa
);
359 memset(sin6
, 0, sizeof(*sin6
));
360 sin6
->sin6_family
= AF_INET6
;
362 sin6
->sin6_addr
= in6addr_any
;
363 sin6
->sin6_scope_id
= 0;
364 sin6
->sin6_flowinfo
= 0;
371 /* Mask the address A, forcing all but the top PLEN bits to zero or one
372 * according to HIGHP.
374 static void mask_address(int af
, ipaddr
*a
, int plen
, int highp
)
378 unsigned long addr
= ntohl(a
->v4
.s_addr
);
379 unsigned long mask
= plen ?
~0ul << (32 - plen
) : 0;
381 if (highp
) addr
|= ~mask
;
382 a
->v4
.s_addr
= htonl(addr
& 0xffffffff);
386 unsigned m
= (0xff << (8 - plen
%8)) & 0xff;
387 unsigned s
= highp ?
0xff : 0;
389 a
->v6
.s6_addr
[i
] = (a
->v6
.s6_addr
[i
] & m
) | (s
& ~m
);
392 for (; i
< 16; i
++) a
->v6
.s6_addr
[i
] = s
;
399 /* Write a presentation form of SA to BUF, a buffer of length SZ. LEN is the
400 * address length; if it's zero, look it up based on the address family.
401 * Return a pointer to the string (which might, in an emergency, be a static
402 * string rather than your buffer).
404 static char *present_sockaddr(const struct sockaddr
*sa
, socklen_t len
,
405 char *buf
, size_t sz
)
407 #define WANT(n_) do { if (sz < (n_)) goto nospace; } while (0)
408 #define PUTC(c_) do { *buf++ = (c_); sz--; } while (0)
410 if (!sz
) return "<no-space-in-buffer>";
411 if (!len
) len
= family_socklen(sa
->sa_family
);
413 switch (sa
->sa_family
) {
415 struct sockaddr_un
*sun
= SUN(sa
);
416 char *p
= sun
->sun_path
;
417 size_t n
= len
- offsetof(struct sockaddr_un
, sun_path
);
425 case 0: WANT(2); PUTC('\\'); PUTC('0'); break;
426 case '\a': WANT(2); PUTC('\\'); PUTC('a'); break;
427 case '\n': WANT(2); PUTC('\\'); PUTC('n'); break;
428 case '\r': WANT(2); PUTC('\\'); PUTC('r'); break;
429 case '\t': WANT(2); PUTC('\\'); PUTC('t'); break;
430 case '\v': WANT(2); PUTC('\\'); PUTC('v'); break;
431 case '\\': WANT(2); PUTC('\\'); PUTC('\\'); break;
433 if (*p
> ' ' && *p
<= '~')
434 { WANT(1); PUTC(*p
); }
436 WANT(4); PUTC('\\'); PUTC('x');
437 PUTC((*p
>> 4)&0xf); PUTC((*p
>> 0)&0xf);
444 if (*p
!= '/') { WANT(2); PUTC('.'); PUTC('/'); }
445 while (n
&& *p
) { WANT(1); PUTC(*p
); p
++; n
--; }
449 case AF_INET
: case AF_INET6
: {
450 char addrbuf
[NI_MAXHOST
], portbuf
[NI_MAXSERV
];
451 int err
= getnameinfo(sa
, len
,
452 addrbuf
, sizeof(addrbuf
),
453 portbuf
, sizeof(portbuf
),
454 NI_NUMERICHOST
| NI_NUMERICSERV
);
456 snprintf(buf
, sz
, strchr(addrbuf
, ':') ?
"[%s]:%s" : "%s:%s",
460 snprintf(buf
, sz
, "<unknown-address-family %d>", sa
->sa_family
);
470 /* Guess the family of a textual socket address. */
471 static int guess_address_family(const char *p
)
472 { return (strchr(p
, ':') ? AF_INET6
: AF_INET
); }
474 /* Parse a socket address P and write the result to SA. */
475 static int parse_sockaddr(struct sockaddr
*sa
, const char *p
)
479 struct addrinfo
*ai
, ai_hint
= { 0 };
481 if (strlen(p
) >= sizeof(buf
) - 1) return (-1);
482 strcpy(buf
, p
); p
= buf
;
484 if ((q
= strchr(p
, ':')) == 0) return (-1);
488 if ((q
= strchr(p
, ']')) == 0) return (-1);
490 if (*q
!= ':') return (-1);
494 ai_hint
.ai_family
= AF_UNSPEC
;
495 ai_hint
.ai_socktype
= SOCK_DGRAM
;
496 ai_hint
.ai_flags
= AI_NUMERICHOST
| AI_NUMERICSERV
;
497 if (getaddrinfo(p
, q
, &ai_hint
, &ai
)) return (-1);
498 memcpy(sa
, ai
->ai_addr
, ai
->ai_addrlen
);
503 /*----- Access control lists ----------------------------------------------*/
507 /* Write to standard error a description of the ACL node A. */
508 static void dump_aclnode(const aclnode
*a
)
514 fprintf(stderr
, "noip: %c ", a
->act ?
'+' : '-');
515 plen
= common_prefix_length(a
->af
, &a
->minaddr
, &a
->maxaddr
);
516 p
= inet_ntop(a
->af
, &a
->minaddr
, buf
, sizeof(buf
));
517 fprintf(stderr
, strchr(p
, ':') ?
"[%s]" : "%s", p
);
519 p
= inet_ntop(a
->af
, &a
->maxaddr
, buf
, sizeof(buf
));
520 fprintf(stderr
, strchr(p
, ':') ?
"-[%s]" : "-%s", p
);
521 } else if (plen
< address_width(a
->af
))
522 fprintf(stderr
, "/%d", plen
);
523 if (a
->minport
!= 0 || a
->maxport
!= 0xffff) {
524 fprintf(stderr
, ":%u", (unsigned)a
->minport
);
525 if (a
->minport
!= a
->maxport
)
526 fprintf(stderr
, "-%u", (unsigned)a
->maxport
);
531 static void dump_acl(const aclnode
*a
)
535 for (; a
; a
= a
->next
) {
539 fprintf(stderr
, "noip: [default policy: %s]\n",
540 act
== ALLOW ?
"DENY" : "ALLOW");
545 /* Returns nonzero if the ACL A allows the socket address SA. */
546 static int acl_allows_p(const aclnode
*a
, const struct sockaddr
*sa
)
548 unsigned short port
= port_from_sockaddr(sa
);
551 D({ char buf
[ADDRBUFSZ
];
552 fprintf(stderr
, "noip: check %s\n",
553 present_sockaddr(sa
, 0, buf
, sizeof(buf
))); })
554 for (; a
; a
= a
->next
) {
555 D( dump_aclnode(a
); )
556 if (sockaddr_in_range_p(sa
, &a
->minaddr
, &a
->maxaddr
) &&
557 a
->minport
<= port
&& port
<= a
->maxport
) {
558 D( fprintf(stderr
, "noip: aha! %s\n", a
->act ?
"ALLOW" : "DENY"); )
563 D( fprintf(stderr
, "noip: nothing found: %s\n", act ?
"DENY" : "ALLOW"); )
567 /*----- Socket address conversion -----------------------------------------*/
569 /* Return a uniformly distributed integer between MIN and MAX inclusive. */
570 static unsigned randrange(unsigned min
, unsigned max
)
574 /* It's so nice not to have to care about the quality of the generator
578 for (mask
= 1; mask
< max
; mask
= (mask
<< 1) | 1)
580 do i
= rand() & mask
; while (i
> max
);
584 /* Return the status of Unix-domain socket address SUN. Returns: UNUSED if
585 * the socket doesn't exist; USED if the path refers to an active socket, or
586 * isn't really a socket at all, or we can't tell without a careful search
587 * and QUICKP is set; or STALE if the file refers to a socket which isn't
588 * being used any more.
590 static int unix_socket_status(struct sockaddr_un
*sun
, int quickp
)
598 if (stat(sun
->sun_path
, &st
))
599 return (errno
== ENOENT ? UNUSED
: USED
);
600 if (!S_ISSOCK(st
.st_mode
) || quickp
)
603 if ((fp
= fopen("/proc/net/unix", "r")) == 0)
605 if (!fgets(buf
, sizeof(buf
), fp
)) goto done
; /* skip header */
606 len
= strlen(sun
->sun_path
);
607 while (fgets(buf
, sizeof(buf
), fp
)) {
609 if (n
>= len
+ 2 && buf
[n
- len
- 2] == ' ' && buf
[n
- 1] == '\n' &&
610 memcmp(buf
+ n
- len
- 1, sun
->sun_path
, len
) == 0)
621 /* Encode the Internet address SA as a Unix-domain address SUN. If WANT is
622 * WANT_FRESH, and SA's port number is zero, then we pick an arbitrary local
623 * port. Otherwise we pick the port given. There's an unpleasant hack to
624 * find servers bound to local wildcard addresses. Returns zero on success;
627 static int encode_inet_addr(struct sockaddr_un
*sun
,
628 const struct sockaddr
*sa
,
637 D( fprintf(stderr
, "noip: encode %s (%s)",
638 present_sockaddr(sa
, 0, buf
, sizeof(buf
)),
639 want
== WANT_EXISTING ?
"EXISTING" : "FRESH"); )
640 sun
->sun_family
= AF_UNIX
;
641 if (port_from_sockaddr(sa
) || want
== WANT_EXISTING
) {
642 snprintf(sun
->sun_path
, sizeof(sun
->sun_path
), "%s/%s", sockdir
,
643 present_sockaddr(sa
, 0, buf
, sizeof(buf
)));
644 rc
= unix_socket_status(sun
, 0);
645 if (rc
== STALE
) unlink(sun
->sun_path
);
646 if (rc
!= USED
&& want
== WANT_EXISTING
) {
647 wildcard_address(sa
->sa_family
, &addr
.sa
);
648 port_to_sockaddr(&addr
.sa
, port_from_sockaddr(sa
));
649 snprintf(sun
->sun_path
, sizeof(sun
->sun_path
), "%s/%s", sockdir
,
650 present_sockaddr(&addr
.sa
, 0, buf
, sizeof(buf
)));
651 if (unix_socket_status(sun
, 0) == STALE
) unlink(sun
->sun_path
);
654 copy_sockaddr(&addr
.sa
, sa
);
655 for (i
= 0; i
< 10; i
++) {
656 port_to_sockaddr(&addr
.sa
, randrange(minautoport
, maxautoport
));
657 snprintf(sun
->sun_path
, sizeof(sun
->sun_path
), "%s/%s", sockdir
,
658 present_sockaddr(&addr
.sa
, 0, buf
, sizeof(buf
)));
659 if (unix_socket_status(sun
, 1) == UNUSED
) goto found
;
661 for (desperatep
= 0; desperatep
< 2; desperatep
++) {
662 for (i
= minautoport
; i
<= maxautoport
; i
++) {
663 port_to_sockaddr(&addr
.sa
, i
);
664 snprintf(sun
->sun_path
, sizeof(sun
->sun_path
), "%s/%s", sockdir
,
665 present_sockaddr(&addr
.sa
, 0, buf
, sizeof(buf
)));
666 rc
= unix_socket_status(sun
, !desperatep
);
668 case STALE
: unlink(sun
->sun_path
);
669 case UNUSED
: goto found
;
674 D( fprintf(stderr
, " -- can't resolve\n"); )
678 D( fprintf(stderr
, " -> `%s'\n", sun
->sun_path
); )
682 /* Decode the Unix address SUN to an Internet address SIN. If AF_HINT is
683 * nonzero, an empty address (indicative of an unbound Unix-domain socket) is
684 * translated to a wildcard Internet address of the appropriate family.
685 * Returns zero on success; -1 on failure (e.g., it wasn't one of our
688 static int decode_inet_addr(struct sockaddr
*sa
, int af_hint
,
689 const struct sockaddr_un
*sun
,
693 size_t n
= strlen(sockdir
), nn
;
696 if (!sa
) sa
= &addr
.sa
;
697 if (sun
->sun_family
!= AF_UNIX
) return (-1);
698 if (len
> sizeof(*sun
)) return (-1);
699 ((char *)sun
)[len
] = 0;
700 nn
= strlen(sun
->sun_path
);
701 D( fprintf(stderr
, "noip: decode `%s'", sun
->sun_path
); )
702 if (af_hint
&& !sun
->sun_path
[0]) {
703 wildcard_address(af_hint
, sa
);
704 D( fprintf(stderr
, " -- unbound socket\n"); )
707 if (nn
< n
+ 1 || nn
- n
>= sizeof(buf
) || sun
->sun_path
[n
] != '/' ||
708 memcmp(sun
->sun_path
, sockdir
, n
) != 0) {
709 D( fprintf(stderr
, " -- not one of ours\n"); )
712 if (parse_sockaddr(sa
, sun
->sun_path
+ n
+ 1)) return (-1);
713 D( fprintf(stderr
, " -> %s\n",
714 present_sockaddr(sa
, 0, buf
, sizeof(buf
))); )
718 /* SK is (or at least might be) a Unix-domain socket we created when an
719 * Internet socket was asked for. We've decided it should be an Internet
720 * socket after all, with family AF_HINT, so convert it. If TMP is not null,
721 * then don't replace the existing descriptor: store the new socket in *TMP
724 static int fixup_real_ip_socket(int sk
, int af_hint
, int *tmp
)
729 struct sockaddr_un sun
;
742 _(LINGER, struct linger) \
745 _(RCVTIMEO, struct timeval) \
746 _(SNDTIMEO, struct timeval)
749 if (real_getsockname(sk
, SA(&sun
), &len
))
751 if (decode_inet_addr(&addr
.sa
, af_hint
, &sun
, len
))
752 return (0); /* Not one of ours */
754 if (real_getsockopt(sk
, SOL_SOCKET
, SO_TYPE
, &type
, &len
) < 0 ||
755 (nsk
= real_socket(addr
.sa
.sa_family
, type
, 0)) < 0)
757 #define FIX(opt, ty) do { \
760 if (real_getsockopt(sk, SOL_SOCKET, SO_##opt, &ov_, &len) < 0 || \
761 real_setsockopt(nsk, SOL_SOCKET, SO_##opt, &ov_, len)) { \
771 if ((f
= fcntl(sk
, F_GETFL
)) < 0 ||
772 (fd
= fcntl(sk
, F_GETFD
)) < 0 ||
773 fcntl(nsk
, F_SETFL
, f
) < 0 ||
778 unlink(sun
.sun_path
);
780 if (fcntl(sk
, F_SETFD
, fd
) < 0) {
781 perror("noip: fixup_real_ip_socket F_SETFD");
788 /* The socket SK is about to be used to communicate with the remote address
789 * SA. Assign it a local address so that getpeername(2) does something
792 static int do_implicit_bind(int sk
, const struct sockaddr
**sa
,
793 socklen_t
*len
, struct sockaddr_un
*sun
)
796 socklen_t mylen
= sizeof(*sun
);
798 if (acl_allows_p(connect_real
, *sa
)) {
799 if (fixup_real_ip_socket(sk
, (*sa
)->sa_family
, 0)) return (-1);
801 if (real_getsockname(sk
, SA(sun
), &mylen
) < 0) return (-1);
802 if (sun
->sun_family
== AF_UNIX
) {
803 if (mylen
< sizeof(*sun
)) ((char *)sun
)[mylen
] = 0;
804 if (!sun
->sun_path
[0]) {
805 wildcard_address((*sa
)->sa_family
, &addr
.sa
);
806 encode_inet_addr(sun
, &addr
.sa
, WANT_FRESH
);
807 if (real_bind(sk
, SA(sun
), SUN_LEN(sun
))) return (-1);
809 encode_inet_addr(sun
, *sa
, WANT_EXISTING
);
817 /* We found the real address SA, with length LEN; if it's a Unix-domain
818 * address corresponding to a fake socket, convert it to cover up the
819 * deception. Whatever happens, put the result at FAKE and store its length
822 static void return_fake_name(struct sockaddr
*sa
, socklen_t len
,
823 struct sockaddr
*fake
, socklen_t
*fakelen
)
828 if (sa
->sa_family
== AF_UNIX
&&
829 !decode_inet_addr(&addr
.sa
, 0, SUN(sa
), len
)) {
831 len
= family_socklen(addr
.sa
.sa_family
);
834 if (len
> *fakelen
) len
= *fakelen
;
835 if (len
> 0) memcpy(fake
, sa
, len
);
839 /*----- Configuration -----------------------------------------------------*/
841 /* Return the process owner's home directory. */
842 static char *home(void)
847 if (getuid() == uid
&&
848 (p
= getenv("HOME")) != 0)
850 else if ((pw
= getpwuid(uid
)) != 0)
856 /* Return a good temporary directory to use. */
857 static char *tmpdir(void)
861 if ((p
= getenv("TMPDIR")) != 0) return (p
);
862 else if ((p
= getenv("TMP")) != 0) return (p
);
863 else return ("/tmp");
866 /* Return the user's name, or at least something distinctive. */
867 static char *user(void)
873 if ((p
= getenv("USER")) != 0) return (p
);
874 else if ((p
= getenv("LOGNAME")) != 0) return (p
);
875 else if ((pw
= getpwuid(uid
)) != 0) return (pw
->pw_name
);
877 snprintf(buf
, sizeof(buf
), "uid-%lu", (unsigned long)uid
);
882 /* Skip P over space characters. */
883 #define SKIPSPC do { while (*p && isspace(UC(*p))) p++; } while (0)
885 /* Set Q to point to the next word following P, null-terminate it, and step P
887 #define NEXTWORD(q) do { \
890 while (*p && !isspace(UC(*p))) p++; \
894 /* Set Q to point to the next dotted-quad address, store the ending delimiter
895 * in DEL, null-terminate it, and step P past it. */
896 static void parse_nextaddr(char **pp
, char **qq
, int *del
)
904 p
+= strcspn(p
, "]");
909 while (*p
&& (*p
== '.' || isdigit(UC(*p
)))) p
++;
916 /* Set Q to point to the next decimal number, store the ending delimiter in
917 * DEL, null-terminate it, and step P past it. */
918 #define NEXTNUMBER(q, del) do { \
921 while (*p && isdigit(UC(*p))) p++; \
926 /* Push the character DEL back so we scan it again, unless it's zero
928 #define RESCAN(del) do { if (del) *--p = del; } while (0)
930 /* Evaluate true if P is pointing to the word KW (and not some longer string
931 * of which KW is a prefix). */
933 #define KWMATCHP(kw) (strncmp(p, kw, sizeof(kw) - 1) == 0 && \
934 !isalnum(UC(p[sizeof(kw) - 1])) && \
935 (p += sizeof(kw) - 1))
937 /* Parse a port list, starting at *PP. Port lists have the form
938 * [:LOW[-HIGH]]: if omitted, all ports are included; if HIGH is omitted,
939 * it's as if HIGH = LOW. Store LOW in *MIN, HIGH in *MAX and set *PP to the
940 * rest of the string.
942 static void parse_ports(char **pp
, unsigned short *min
, unsigned short *max
)
949 { *min
= 0; *max
= 0xffff; }
952 NEXTNUMBER(q
, del
); *min
= strtoul(q
, 0, 0); RESCAN(del
);
955 { p
++; NEXTNUMBER(q
, del
); *max
= strtoul(q
, 0, 0); RESCAN(del
); }
962 /* Make a new ACL node. ACT is the verdict; AF is the address family;
963 * MINADDR and MAXADDR are the ranges on IP addresses; MINPORT and MAXPORT
964 * are the ranges on port numbers; TAIL is the list tail to attach the new
967 #define ACLNODE(tail_, act_, \
968 af_, minaddr_, maxaddr_, minport_, maxport_) do { \
973 a_->minaddr = (minaddr_); a_->maxaddr = (maxaddr_); \
974 a_->minport = (minport_); a_->maxport = (maxport_); \
975 *tail_ = a_; tail_ = &a_->next; \
978 /* Parse an ACL line. *PP points to the end of the line; *TAIL points to
979 * the list tail (i.e., the final link in the list). An ACL entry has the
980 * form +|- [any | local | ADDR | ADDR - ADDR | ADDR/ADDR | ADDR/INT] PORTS
981 * where PORTS is parsed by parse_ports above; an ACL line consists of a
982 * comma-separated sequence of entries..
984 static void parse_acl_line(char **pp
, aclnode
***tail
)
986 ipaddr minaddr
, maxaddr
;
987 unsigned short minport
, maxport
;
996 if (*p
== '+') act
= ALLOW
;
997 else if (*p
== '-') act
= DENY
;
1002 if (KWMATCHP("any")) {
1003 parse_ports(&p
, &minport
, &maxport
);
1004 for (i
= 0; address_families
[i
] >= 0; i
++) {
1005 af
= address_families
[i
];
1006 memset(&minaddr
, 0, sizeof(minaddr
));
1007 maxaddr
= minaddr
; mask_address(af
, &maxaddr
, 0, 1);
1008 ACLNODE(*tail
, act
, af
, minaddr
, maxaddr
, minport
, maxport
);
1010 } else if (KWMATCHP("local")) {
1011 parse_ports(&p
, &minport
, &maxport
);
1012 for (i
= 0; address_families
[i
] >= 0; i
++) {
1013 af
= address_families
[i
];
1014 memset(&minaddr
, 0, sizeof(minaddr
));
1015 maxaddr
= minaddr
; mask_address(af
, &maxaddr
, 0, 1);
1016 ACLNODE(*tail
, act
, af
, minaddr
, minaddr
, minport
, maxport
);
1017 ACLNODE(*tail
, act
, af
, maxaddr
, maxaddr
, minport
, maxport
);
1019 for (i
= 0; i
< n_local_ipaddrs
; i
++) {
1020 ACLNODE(*tail
, act
, local_ipaddrs
[i
].af
,
1021 local_ipaddrs
[i
].addr
, local_ipaddrs
[i
].addr
,
1025 parse_nextaddr(&p
, &q
, &del
);
1026 af
= guess_address_family(q
);
1027 if (inet_pton(af
, q
, &minaddr
) <= 0) goto bad
;
1032 parse_nextaddr(&p
, &q
, &del
);
1033 if (inet_pton(af
, q
, &maxaddr
) <= 0) goto bad
;
1035 } else if (*p
== '/') {
1038 n
= strtoul(q
, 0, 0);
1040 mask_address(af
, &minaddr
, n
, 0);
1041 mask_address(af
, &maxaddr
, n
, 1);
1045 parse_ports(&p
, &minport
, &maxport
);
1046 ACLNODE(*tail
, act
, af
, minaddr
, maxaddr
, minport
, maxport
);
1049 if (*p
!= ',') break;
1056 D( fprintf(stderr
, "noip: bad acl spec (ignored)\n"); )
1060 /* Parse the autoports configuration directive. Syntax is MIN - MAX. */
1061 static void parse_autoports(char **pp
)
1068 NEXTNUMBER(q
, del
); x
= strtoul(q
, 0, 0); RESCAN(del
);
1070 if (*p
!= '-') goto bad
; p
++;
1071 NEXTNUMBER(q
, del
); y
= strtoul(q
, 0, 0); RESCAN(del
);
1072 minautoport
= x
; maxautoport
= y
;
1077 D( fprintf(stderr
, "bad port range (ignored)\n"); )
1081 /* Parse an ACL from an environment variable VAR, attaching it to the list
1083 static void parse_acl_env(const char *var
, aclnode
***tail
)
1087 if ((p
= getenv(var
)) != 0) {
1089 parse_acl_line(&q
, tail
);
1094 /* Read the configuration from the config file and environment. */
1095 static void readconfig(void)
1102 parse_acl_env("NOIP_REALBIND_BEFORE", &bind_tail
);
1103 parse_acl_env("NOIP_REALCONNECT_BEFORE", &connect_tail
);
1104 if ((p
= getenv("NOIP_AUTOPORTS")) != 0) {
1106 parse_autoports(&q
);
1109 if ((p
= getenv("NOIP_CONFIG")) == 0)
1110 snprintf(p
= buf
, sizeof(buf
), "%s/.noip", home());
1111 D( fprintf(stderr
, "noip: config file: %s\n", p
); )
1113 if ((fp
= fopen(p
, "r")) == 0) {
1114 D( fprintf(stderr
, "noip: couldn't read config: %s\n",
1118 while (fgets(buf
, sizeof(buf
), fp
)) {
1123 if (!*p
|| *p
== '#') continue;
1124 while (n
&& isspace(UC(buf
[n
- 1]))) n
--;
1129 if (strcmp(cmd
, "socketdir") == 0)
1130 sockdir
= xstrdup(p
);
1131 else if (strcmp(cmd
, "realbind") == 0)
1132 parse_acl_line(&p
, &bind_tail
);
1133 else if (strcmp(cmd
, "realconnect") == 0)
1134 parse_acl_line(&p
, &connect_tail
);
1135 else if (strcmp(cmd
, "autoports") == 0)
1136 parse_autoports(&p
);
1137 else if (strcmp(cmd
, "debug") == 0)
1138 debug
= *p ?
atoi(p
) : 1;
1140 D( fprintf(stderr
, "noip: bad config command %s\n", cmd
); )
1145 parse_acl_env("NOIP_REALBIND", &bind_tail
);
1146 parse_acl_env("NOIP_REALCONNECT", &connect_tail
);
1147 parse_acl_env("NOIP_REALBIND_AFTER", &bind_tail
);
1148 parse_acl_env("NOIP_REALCONNECT_AFTER", &connect_tail
);
1151 if (!sockdir
) sockdir
= getenv("NOIP_SOCKETDIR");
1153 snprintf(buf
, sizeof(buf
), "%s/noip-%s", tmpdir(), user());
1154 sockdir
= xstrdup(buf
);
1156 D( fprintf(stderr
, "noip: socketdir: %s\n", sockdir
);
1157 fprintf(stderr
, "noip: autoports: %u-%u\n",
1158 minautoport
, maxautoport
);
1159 fprintf(stderr
, "noip: realbind acl:\n");
1160 dump_acl(bind_real
);
1161 fprintf(stderr
, "noip: realconnect acl:\n");
1162 dump_acl(connect_real
); )
1165 /*----- Overridden system calls -------------------------------------------*/
1167 int socket(int pf
, int ty
, int proto
)
1171 if (!family_known_p(pf
)) {
1172 errno
= EAFNOSUPPORT
;
1181 return (real_socket(pf
, ty
, proto
));
1185 int socketpair(int pf
, int ty
, int proto
, int *sk
)
1187 if (family_known_p(pf
)) {
1191 return (real_socketpair(pf
, ty
, proto
, sk
));
1194 int bind(int sk
, const struct sockaddr
*sa
, socklen_t len
)
1196 struct sockaddr_un sun
;
1198 if (family_known_p(sa
->sa_family
)) {
1200 if (acl_allows_p(bind_real
, sa
)) {
1201 if (fixup_real_ip_socket(sk
, sa
->sa_family
, 0))
1204 encode_inet_addr(&sun
, sa
, WANT_FRESH
);
1206 len
= SUN_LEN(&sun
);
1210 return (real_bind(sk
, sa
, len
));
1213 int connect(int sk
, const struct sockaddr
*sa
, socklen_t len
)
1215 struct sockaddr_un sun
;
1218 if (!family_known_p(sa
->sa_family
))
1219 rc
= real_connect(sk
, sa
, len
);
1222 do_implicit_bind(sk
, &sa
, &len
, &sun
);
1224 rc
= real_connect(sk
, sa
, len
);
1227 case ENOENT
: errno
= ECONNREFUSED
; break;
1234 ssize_t
sendto(int sk
, const void *buf
, size_t len
, int flags
,
1235 const struct sockaddr
*to
, socklen_t tolen
)
1237 struct sockaddr_un sun
;
1239 if (to
&& family_known_p(to
->sa_family
)) {
1241 do_implicit_bind(sk
, &to
, &tolen
, &sun
);
1244 return (real_sendto(sk
, buf
, len
, flags
, to
, tolen
));
1247 ssize_t
recvfrom(int sk
, void *buf
, size_t len
, int flags
,
1248 struct sockaddr
*from
, socklen_t
*fromlen
)
1251 socklen_t mylen
= sizeof(sabuf
);
1255 return real_recvfrom(sk
, buf
, len
, flags
, 0, 0);
1257 n
= real_recvfrom(sk
, buf
, len
, flags
, SA(sabuf
), &mylen
);
1260 return_fake_name(SA(sabuf
), mylen
, from
, fromlen
);
1265 ssize_t
sendmsg(int sk
, const struct msghdr
*msg
, int flags
)
1267 struct sockaddr_un sun
;
1268 const struct sockaddr
*sa
;
1269 struct msghdr mymsg
;
1271 if (msg
->msg_name
&& family_known_p(SA(msg
->msg_name
)->sa_family
)) {
1273 sa
= SA(msg
->msg_name
);
1275 do_implicit_bind(sk
, &sa
, &mymsg
.msg_namelen
, &sun
);
1276 mymsg
.msg_name
= SA(sa
);
1280 return (real_sendmsg(sk
, msg
, flags
));
1283 ssize_t
recvmsg(int sk
, struct msghdr
*msg
, int flags
)
1286 struct sockaddr
*sa
;
1291 return (real_recvmsg(sk
, msg
, flags
));
1293 sa
= SA(msg
->msg_name
);
1294 len
= msg
->msg_namelen
;
1295 msg
->msg_name
= sabuf
;
1296 msg
->msg_namelen
= sizeof(sabuf
);
1297 n
= real_recvmsg(sk
, msg
, flags
);
1300 return_fake_name(SA(sabuf
), msg
->msg_namelen
, sa
, &len
);
1302 msg
->msg_namelen
= len
;
1307 int accept(int sk
, struct sockaddr
*sa
, socklen_t
*len
)
1310 socklen_t mylen
= sizeof(sabuf
);
1311 int nsk
= real_accept(sk
, SA(sabuf
), &mylen
);
1315 return_fake_name(SA(sabuf
), mylen
, sa
, len
);
1319 int getsockname(int sk
, struct sockaddr
*sa
, socklen_t
*len
)
1323 socklen_t mylen
= sizeof(sabuf
);
1324 if (real_getsockname(sk
, SA(sabuf
), &mylen
))
1326 return_fake_name(SA(sabuf
), mylen
, sa
, len
);
1331 int getpeername(int sk
, struct sockaddr
*sa
, socklen_t
*len
)
1335 socklen_t mylen
= sizeof(sabuf
);
1336 if (real_getpeername(sk
, SA(sabuf
), &mylen
))
1338 return_fake_name(SA(sabuf
), mylen
, sa
, len
);
1343 int getsockopt(int sk
, int lev
, int opt
, void *p
, socklen_t
*len
)
1353 return (real_getsockopt(sk
, lev
, opt
, p
, len
));
1356 int setsockopt(int sk
, int lev
, int opt
, const void *p
, socklen_t len
)
1365 case SO_BINDTODEVICE
:
1366 case SO_ATTACH_FILTER
:
1367 case SO_DETACH_FILTER
:
1370 return (real_setsockopt(sk
, lev
, opt
, p
, len
));
1373 int ioctl(int fd
, unsigned long op
, ...)
1381 arg
= va_arg(ap
, void *);
1385 case SIOCGIFBRDADDR
:
1386 case SIOCGIFDSTADDR
:
1387 case SIOCGIFNETMASK
:
1389 if (fixup_real_ip_socket(fd
, AF_INET
, &sk
)) goto real
;
1391 rc
= real_ioctl(sk
, op
, arg
);
1392 PRESERVING_ERRNO({ close(sk
); });
1396 rc
= real_ioctl(fd
, op
, arg
);
1403 /*----- Initialization ----------------------------------------------------*/
1405 /* Clean up the socket directory, deleting stale sockets. */
1406 static void cleanup_sockdir(void)
1411 struct sockaddr_un sun
;
1414 if ((dir
= opendir(sockdir
)) == 0) return;
1415 sun
.sun_family
= AF_UNIX
;
1416 while ((d
= readdir(dir
)) != 0) {
1417 if (d
->d_name
[0] == '.') continue;
1418 snprintf(sun
.sun_path
, sizeof(sun
.sun_path
),
1419 "%s/%s", sockdir
, d
->d_name
);
1420 if (decode_inet_addr(&addr
.sa
, 0, &sun
, SUN_LEN(&sun
)) ||
1421 stat(sun
.sun_path
, &st
) ||
1422 !S_ISSOCK(st
.st_mode
)) {
1423 D( fprintf(stderr
, "noip: ignoring unknown socketdir entry `%s'\n",
1427 if (unix_socket_status(&sun
, 0) == STALE
) {
1428 D( fprintf(stderr
, "noip: clearing away stale socket %s\n",
1430 unlink(sun
.sun_path
);
1436 /* Find the addresses attached to local network interfaces, and remember them
1439 static void get_local_ipaddrs(void)
1441 struct ifaddrs
*ifa_head
, *ifa
;
1445 if (getifaddrs(&ifa_head
)) { perror("getifaddrs"); return; }
1446 for (n_local_ipaddrs
= 0, ifa
= ifa_head
;
1447 n_local_ipaddrs
< MAX_LOCAL_IPADDRS
&& ifa
;
1448 ifa
= ifa
->ifa_next
) {
1449 if (!ifa
->ifa_addr
|| !family_known_p(ifa
->ifa_addr
->sa_family
))
1451 ipaddr_from_sockaddr(&a
, ifa
->ifa_addr
);
1452 D({ char buf
[ADDRBUFSZ
];
1453 fprintf(stderr
, "noip: local addr %s = %s", ifa
->ifa_name
,
1454 inet_ntop(ifa
->ifa_addr
->sa_family
, &a
,
1455 buf
, sizeof(buf
))); })
1456 for (i
= 0; i
< n_local_ipaddrs
; i
++) {
1457 if (ifa
->ifa_addr
->sa_family
== local_ipaddrs
[i
].af
&&
1458 ipaddr_equal_p(local_ipaddrs
[i
].af
, &a
, &local_ipaddrs
[i
].addr
)) {
1459 D( fprintf(stderr
, " (duplicate)\n"); )
1463 D( fprintf(stderr
, "\n"); )
1464 local_ipaddrs
[n_local_ipaddrs
].af
= ifa
->ifa_addr
->sa_family
;
1465 local_ipaddrs
[n_local_ipaddrs
].addr
= a
;
1469 freeifaddrs(ifa_head
);
1472 /* Print the given message to standard error. Avoids stdio. */
1473 static void printerr(const char *p
)
1474 { if (write(STDERR_FILENO
, p
, strlen(p
))) ; }
1476 /* Create the socket directory, being careful about permissions. */
1477 static void create_sockdir(void)
1481 if (lstat(sockdir
, &st
)) {
1482 if (errno
== ENOENT
) {
1483 if (mkdir(sockdir
, 0700)) {
1484 perror("noip: creating socketdir");
1487 if (!lstat(sockdir
, &st
))
1490 perror("noip: checking socketdir");
1494 if (!S_ISDIR(st
.st_mode
)) {
1495 printerr("noip: bad socketdir: not a directory\n");
1498 if (st
.st_uid
!= uid
) {
1499 printerr("noip: bad socketdir: not owner\n");
1502 if (st
.st_mode
& 077) {
1503 printerr("noip: bad socketdir: not private\n");
1508 /* Initialization function. */
1509 static void setup(void) __attribute__((constructor
));
1510 static void setup(void)
1517 if ((p
= getenv("NOIP_DEBUG")) && atoi(p
))
1519 get_local_ipaddrs();
1526 /*----- That's all, folks -------------------------------------------------*/