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 } }
164 # define Dpid pid_t pid = debug ? getpid() : -1
170 /* Preservation of error status */
171 #define PRESERVING_ERRNO(body) do { \
172 int _err = errno; { body } errno = _err; \
175 /* Allocate N bytes of memory; abort on failure. */
176 static void *xmalloc(size_t n
)
180 if ((p
= malloc(n
)) == 0) { perror("malloc"); exit(127); }
184 /* Allocate a copy of the null-terminated string P; abort on failure. */
185 static char *xstrdup(const char *p
)
187 size_t n
= strlen(p
) + 1;
188 char *q
= xmalloc(n
);
193 /*----- Address-type hacking ----------------------------------------------*/
195 /* If M is a simple mask, i.e., consists of a sequence of zero bits followed
196 * by a sequence of one bits, then return the length of the latter sequence
197 * (which may be zero); otherwise return -1.
199 static int simple_mask_length(unsigned long m
)
203 while (m
& 1) { n
++; m
>>= 1; }
207 /* Answer whether AF is an interesting address family. */
208 static int family_known_p(int af
)
219 /* Return the socket address length for address family AF. */
220 static socklen_t
family_socklen(int af
)
223 case AF_INET
: return (sizeof(struct sockaddr_in
));
224 case AF_INET6
: return (sizeof(struct sockaddr_in6
));
229 /* Return the width of addresses of kind AF. */
230 static int address_width(int af
)
233 case AF_INET
: return 32;
234 case AF_INET6
: return 128;
239 /* If addresses A and B share a common prefix then return its length;
240 * otherwise return -1.
242 static int common_prefix_length(int af
, const ipaddr
*a
, const ipaddr
*b
)
246 unsigned long aa
= ntohl(a
->v4
.s_addr
), bb
= ntohl(b
->v4
.s_addr
);
247 unsigned long m
= aa
^bb
;
248 if ((aa
&m
) == 0 && (bb
&m
) == m
) return (32 - simple_mask_length(m
));
252 const uint8_t *aa
= a
->v6
.s6_addr
, *bb
= b
->v6
.s6_addr
;
257 for (i
= 0; i
< 16 && aa
[i
] == bb
[i
]; i
++);
261 if ((aa
[i
]&m
) != 0 || (bb
[i
]&m
) != m
) return (-1);
262 n
+= 8 - simple_mask_length(m
);
263 for (i
++; i
< 16; i
++)
264 if (aa
[i
] || bb
[i
] != 0xff) return (-1);
273 /* Extract the port number (in host byte-order) from SA. */
274 static int port_from_sockaddr(const struct sockaddr
*sa
)
276 switch (sa
->sa_family
) {
277 case AF_INET
: return (ntohs(SIN(sa
)->sin_port
));
278 case AF_INET6
: return (ntohs(SIN6(sa
)->sin6_port
));
283 /* Store the port number PORT (in host byte-order) in SA. */
284 static void port_to_sockaddr(struct sockaddr
*sa
, int port
)
286 switch (sa
->sa_family
) {
287 case AF_INET
: SIN(sa
)->sin_port
= htons(port
); break;
288 case AF_INET6
: SIN6(sa
)->sin6_port
= htons(port
); break;
293 /* Extract the address part from SA and store it in A. */
294 static void ipaddr_from_sockaddr(ipaddr
*a
, const struct sockaddr
*sa
)
296 switch (sa
->sa_family
) {
297 case AF_INET
: a
->v4
= SIN(sa
)->sin_addr
; break;
298 case AF_INET6
: a
->v6
= SIN6(sa
)->sin6_addr
; break;
303 /* Copy a whole socket address about. */
304 static void copy_sockaddr(struct sockaddr
*sa_dst
,
305 const struct sockaddr
*sa_src
)
306 { memcpy(sa_dst
, sa_src
, family_socklen(sa_src
->sa_family
)); }
308 /* Answer whether two addresses are equal. */
309 static int ipaddr_equal_p(int af
, const ipaddr
*a
, const ipaddr
*b
)
312 case AF_INET
: return (a
->v4
.s_addr
== b
->v4
.s_addr
);
313 case AF_INET6
: return (memcmp(a
->v6
.s6_addr
, b
->v6
.s6_addr
, 16) == 0);
318 /* Answer whether the address part of SA is between A and B (inclusive). We
319 * assume that SA has the correct address family.
321 static int sockaddr_in_range_p(const struct sockaddr
*sa
,
322 const ipaddr
*a
, const ipaddr
*b
)
324 switch (sa
->sa_family
) {
326 unsigned long addr
= ntohl(SIN(sa
)->sin_addr
.s_addr
);
327 return (ntohl(a
->v4
.s_addr
) <= addr
&&
328 addr
<= ntohl(b
->v4
.s_addr
));
331 const uint8_t *ss
= SIN6(sa
)->sin6_addr
.s6_addr
;
332 const uint8_t *aa
= a
->v6
.s6_addr
, *bb
= b
->v6
.s6_addr
;
336 for (i
= 0; h
&& l
&& i
< 16; i
++, ss
++, aa
++, bb
++) {
337 if (*ss
< *aa
|| *bb
< *ss
) return (0);
338 if (*aa
< *ss
) l
= 0;
339 if (*ss
< *bb
) h
= 0;
348 /* Fill in SA with the appropriate wildcard address. */
349 static void wildcard_address(int af
, struct sockaddr
*sa
)
353 struct sockaddr_in
*sin
= SIN(sa
);
354 memset(sin
, 0, sizeof(*sin
));
355 sin
->sin_family
= AF_INET
;
357 sin
->sin_addr
.s_addr
= INADDR_ANY
;
360 struct sockaddr_in6
*sin6
= SIN6(sa
);
361 memset(sin6
, 0, sizeof(*sin6
));
362 sin6
->sin6_family
= AF_INET6
;
364 sin6
->sin6_addr
= in6addr_any
;
365 sin6
->sin6_scope_id
= 0;
366 sin6
->sin6_flowinfo
= 0;
373 /* Mask the address A, forcing all but the top PLEN bits to zero or one
374 * according to HIGHP.
376 static void mask_address(int af
, ipaddr
*a
, int plen
, int highp
)
380 unsigned long addr
= ntohl(a
->v4
.s_addr
);
381 unsigned long mask
= plen ?
~0ul << (32 - plen
) : 0;
383 if (highp
) addr
|= ~mask
;
384 a
->v4
.s_addr
= htonl(addr
& 0xffffffff);
388 unsigned m
= (0xff << (8 - plen
%8)) & 0xff;
389 unsigned s
= highp ?
0xff : 0;
391 a
->v6
.s6_addr
[i
] = (a
->v6
.s6_addr
[i
] & m
) | (s
& ~m
);
394 for (; i
< 16; i
++) a
->v6
.s6_addr
[i
] = s
;
401 /* Write a presentation form of SA to BUF, a buffer of length SZ. LEN is the
402 * address length; if it's zero, look it up based on the address family.
403 * Return a pointer to the string (which might, in an emergency, be a static
404 * string rather than your buffer).
406 static char *present_sockaddr(const struct sockaddr
*sa
, socklen_t len
,
407 char *buf
, size_t sz
)
409 #define WANT(n_) do { if (sz < (n_)) goto nospace; } while (0)
410 #define PUTC(c_) do { *buf++ = (c_); sz--; } while (0)
412 if (!sa
) return "<null-address>";
413 if (!sz
) return "<no-space-in-buffer>";
414 if (!len
) len
= family_socklen(sa
->sa_family
);
416 switch (sa
->sa_family
) {
418 struct sockaddr_un
*sun
= SUN(sa
);
419 char *p
= sun
->sun_path
;
420 size_t n
= len
- offsetof(struct sockaddr_un
, sun_path
);
428 case 0: WANT(2); PUTC('\\'); PUTC('0'); break;
429 case '\a': WANT(2); PUTC('\\'); PUTC('a'); break;
430 case '\n': WANT(2); PUTC('\\'); PUTC('n'); break;
431 case '\r': WANT(2); PUTC('\\'); PUTC('r'); break;
432 case '\t': WANT(2); PUTC('\\'); PUTC('t'); break;
433 case '\v': WANT(2); PUTC('\\'); PUTC('v'); break;
434 case '\\': WANT(2); PUTC('\\'); PUTC('\\'); break;
436 if (*p
> ' ' && *p
<= '~')
437 { WANT(1); PUTC(*p
); }
439 WANT(4); PUTC('\\'); PUTC('x');
440 PUTC((*p
>> 4)&0xf); PUTC((*p
>> 0)&0xf);
447 if (*p
!= '/') { WANT(2); PUTC('.'); PUTC('/'); }
448 while (n
&& *p
) { WANT(1); PUTC(*p
); p
++; n
--; }
452 case AF_INET
: case AF_INET6
: {
453 char addrbuf
[NI_MAXHOST
], portbuf
[NI_MAXSERV
];
454 int err
= getnameinfo(sa
, len
,
455 addrbuf
, sizeof(addrbuf
),
456 portbuf
, sizeof(portbuf
),
457 NI_NUMERICHOST
| NI_NUMERICSERV
);
459 snprintf(buf
, sz
, strchr(addrbuf
, ':') ?
"[%s]:%s" : "%s:%s",
463 snprintf(buf
, sz
, "<unknown-address-family %d>", sa
->sa_family
);
473 /* Guess the family of a textual socket address. */
474 static int guess_address_family(const char *p
)
475 { return (strchr(p
, ':') ? AF_INET6
: AF_INET
); }
477 /* Parse a socket address P and write the result to SA. */
478 static int parse_sockaddr(struct sockaddr
*sa
, const char *p
)
482 struct addrinfo
*ai
, ai_hint
= { 0 };
484 if (strlen(p
) >= sizeof(buf
) - 1) return (-1);
485 strcpy(buf
, p
); p
= buf
;
487 if ((q
= strchr(p
, ':')) == 0) return (-1);
491 if ((q
= strchr(p
, ']')) == 0) return (-1);
493 if (*q
!= ':') return (-1);
497 ai_hint
.ai_family
= AF_UNSPEC
;
498 ai_hint
.ai_socktype
= SOCK_DGRAM
;
499 ai_hint
.ai_flags
= AI_NUMERICHOST
| AI_NUMERICSERV
;
500 if (getaddrinfo(p
, q
, &ai_hint
, &ai
)) return (-1);
501 memcpy(sa
, ai
->ai_addr
, ai
->ai_addrlen
);
506 /*----- Access control lists ----------------------------------------------*/
510 /* Write to standard error a description of the ACL node A. */
511 static void dump_aclnode(const aclnode
*a
)
517 fprintf(stderr
, "noip(%d): %c ", getpid(), a
->act ?
'+' : '-');
518 plen
= common_prefix_length(a
->af
, &a
->minaddr
, &a
->maxaddr
);
519 p
= inet_ntop(a
->af
, &a
->minaddr
, buf
, sizeof(buf
));
520 fprintf(stderr
, strchr(p
, ':') ?
"[%s]" : "%s", p
);
522 p
= inet_ntop(a
->af
, &a
->maxaddr
, buf
, sizeof(buf
));
523 fprintf(stderr
, strchr(p
, ':') ?
"-[%s]" : "-%s", p
);
524 } else if (plen
< address_width(a
->af
))
525 fprintf(stderr
, "/%d", plen
);
526 if (a
->minport
!= 0 || a
->maxport
!= 0xffff) {
527 fprintf(stderr
, ":%u", (unsigned)a
->minport
);
528 if (a
->minport
!= a
->maxport
)
529 fprintf(stderr
, "-%u", (unsigned)a
->maxport
);
534 static void dump_acl(const aclnode
*a
)
538 for (; a
; a
= a
->next
) {
542 fprintf(stderr
, "noip(%d): [default policy: %s]\n", getpid(),
543 act
== ALLOW ?
"DENY" : "ALLOW");
548 /* Returns nonzero if the ACL A allows the socket address SA. */
549 static int acl_allows_p(const aclnode
*a
, const struct sockaddr
*sa
)
551 unsigned short port
= port_from_sockaddr(sa
);
555 D({ char buf
[ADDRBUFSZ
];
556 fprintf(stderr
, "noip(%d): check %s\n", pid
,
557 present_sockaddr(sa
, 0, buf
, sizeof(buf
))); })
558 for (; a
; a
= a
->next
) {
559 D( dump_aclnode(a
); )
560 if (sockaddr_in_range_p(sa
, &a
->minaddr
, &a
->maxaddr
) &&
561 a
->minport
<= port
&& port
<= a
->maxport
) {
562 D( fprintf(stderr
, "noip(%d): aha! %s\n", pid
,
563 a
->act ?
"ALLOW" : "DENY"); )
568 D( fprintf(stderr
, "noip(%d): nothing found: %s\n", pid
,
569 act ?
"DENY" : "ALLOW"); )
573 /*----- Socket address conversion -----------------------------------------*/
575 /* Return a uniformly distributed integer between MIN and MAX inclusive. */
576 static unsigned randrange(unsigned min
, unsigned max
)
580 /* It's so nice not to have to care about the quality of the generator
584 for (mask
= 1; mask
< max
; mask
= (mask
<< 1) | 1)
586 do i
= rand() & mask
; while (i
> max
);
590 /* Return the status of Unix-domain socket address SUN. Returns: UNUSED if
591 * the socket doesn't exist; USED if the path refers to an active socket, or
592 * isn't really a socket at all, or we can't tell without a careful search
593 * and QUICKP is set; or STALE if the file refers to a socket which isn't
594 * being used any more.
596 static int unix_socket_status(struct sockaddr_un
*sun
, int quickp
)
604 if (stat(sun
->sun_path
, &st
))
605 return (errno
== ENOENT ? UNUSED
: USED
);
606 if (!S_ISSOCK(st
.st_mode
) || quickp
)
609 if ((fp
= fopen("/proc/net/unix", "r")) == 0)
611 if (!fgets(buf
, sizeof(buf
), fp
)) goto done
; /* skip header */
612 len
= strlen(sun
->sun_path
);
613 while (fgets(buf
, sizeof(buf
), fp
)) {
615 if (n
>= len
+ 2 && buf
[n
- len
- 2] == ' ' && buf
[n
- 1] == '\n' &&
616 memcmp(buf
+ n
- len
- 1, sun
->sun_path
, len
) == 0)
627 /* Encode the Internet address SA as a Unix-domain address SUN. If WANT is
628 * WANT_FRESH, and SA's port number is zero, then we pick an arbitrary local
629 * port. Otherwise we pick the port given. There's an unpleasant hack to
630 * find servers bound to local wildcard addresses. Returns zero on success;
633 static int encode_inet_addr(struct sockaddr_un
*sun
,
634 const struct sockaddr
*sa
,
643 D( fprintf(stderr
, "noip(%d): encode %s (%s)", getpid(),
644 present_sockaddr(sa
, 0, buf
, sizeof(buf
)),
645 want
== WANT_EXISTING ?
"EXISTING" : "FRESH"); )
646 sun
->sun_family
= AF_UNIX
;
647 if (port_from_sockaddr(sa
) || want
== WANT_EXISTING
) {
648 snprintf(sun
->sun_path
, sizeof(sun
->sun_path
), "%s/%s", sockdir
,
649 present_sockaddr(sa
, 0, buf
, sizeof(buf
)));
650 rc
= unix_socket_status(sun
, 0);
651 if (rc
== STALE
) unlink(sun
->sun_path
);
652 if (rc
!= USED
&& want
== WANT_EXISTING
) {
653 wildcard_address(sa
->sa_family
, &addr
.sa
);
654 port_to_sockaddr(&addr
.sa
, port_from_sockaddr(sa
));
655 snprintf(sun
->sun_path
, sizeof(sun
->sun_path
), "%s/%s", sockdir
,
656 present_sockaddr(&addr
.sa
, 0, buf
, sizeof(buf
)));
657 if (unix_socket_status(sun
, 0) == STALE
) unlink(sun
->sun_path
);
660 copy_sockaddr(&addr
.sa
, sa
);
661 for (i
= 0; i
< 10; i
++) {
662 port_to_sockaddr(&addr
.sa
, randrange(minautoport
, maxautoport
));
663 snprintf(sun
->sun_path
, sizeof(sun
->sun_path
), "%s/%s", sockdir
,
664 present_sockaddr(&addr
.sa
, 0, buf
, sizeof(buf
)));
665 if (unix_socket_status(sun
, 1) == UNUSED
) goto found
;
667 for (desperatep
= 0; desperatep
< 2; desperatep
++) {
668 for (i
= minautoport
; i
<= maxautoport
; i
++) {
669 port_to_sockaddr(&addr
.sa
, i
);
670 snprintf(sun
->sun_path
, sizeof(sun
->sun_path
), "%s/%s", sockdir
,
671 present_sockaddr(&addr
.sa
, 0, buf
, sizeof(buf
)));
672 rc
= unix_socket_status(sun
, !desperatep
);
674 case STALE
: unlink(sun
->sun_path
);
675 case UNUSED
: goto found
;
680 D( fprintf(stderr
, " -- can't resolve\n"); )
684 D( fprintf(stderr
, " -> `%s'\n", sun
->sun_path
); )
688 /* Decode the Unix address SUN to an Internet address SIN. If AF_HINT is
689 * nonzero, an empty address (indicative of an unbound Unix-domain socket) is
690 * translated to a wildcard Internet address of the appropriate family.
691 * Returns zero on success; -1 on failure (e.g., it wasn't one of our
694 static int decode_inet_addr(struct sockaddr
*sa
, int af_hint
,
695 const struct sockaddr_un
*sun
,
699 size_t n
= strlen(sockdir
), nn
;
702 if (!sa
) sa
= &addr
.sa
;
703 if (sun
->sun_family
!= AF_UNIX
) return (-1);
704 if (len
> sizeof(*sun
)) return (-1);
705 ((char *)sun
)[len
] = 0;
706 nn
= strlen(sun
->sun_path
);
707 D( fprintf(stderr
, "noip(%d): decode `%s'", getpid(), sun
->sun_path
); )
708 if (af_hint
&& !sun
->sun_path
[0]) {
709 wildcard_address(af_hint
, sa
);
710 D( fprintf(stderr
, " -- unbound socket\n"); )
713 if (nn
< n
+ 1 || nn
- n
>= sizeof(buf
) || sun
->sun_path
[n
] != '/' ||
714 memcmp(sun
->sun_path
, sockdir
, n
) != 0) {
715 D( fprintf(stderr
, " -- not one of ours\n"); )
718 if (parse_sockaddr(sa
, sun
->sun_path
+ n
+ 1)) return (-1);
719 D( fprintf(stderr
, " -> %s\n",
720 present_sockaddr(sa
, 0, buf
, sizeof(buf
))); )
724 /* SK is (or at least might be) a Unix-domain socket we created when an
725 * Internet socket was asked for. We've decided it should be an Internet
726 * socket after all, with family AF_HINT, so convert it. If TMP is not null,
727 * then don't replace the existing descriptor: store the new socket in *TMP
730 static int fixup_real_ip_socket(int sk
, int af_hint
, int *tmp
)
735 struct sockaddr_un sun
;
748 _(LINGER, struct linger) \
751 _(RCVTIMEO, struct timeval) \
752 _(SNDTIMEO, struct timeval)
755 if (real_getsockname(sk
, SA(&sun
), &len
))
757 if (decode_inet_addr(&addr
.sa
, af_hint
, &sun
, len
))
758 return (0); /* Not one of ours */
760 if (real_getsockopt(sk
, SOL_SOCKET
, SO_TYPE
, &type
, &len
) < 0 ||
761 (nsk
= real_socket(addr
.sa
.sa_family
, type
, 0)) < 0)
763 #define FIX(opt, ty) do { \
766 if (real_getsockopt(sk, SOL_SOCKET, SO_##opt, &ov_, &len) < 0 || \
767 real_setsockopt(nsk, SOL_SOCKET, SO_##opt, &ov_, len)) { \
777 if ((f
= fcntl(sk
, F_GETFL
)) < 0 ||
778 (fd
= fcntl(sk
, F_GETFD
)) < 0 ||
779 fcntl(nsk
, F_SETFL
, f
) < 0 ||
784 unlink(sun
.sun_path
);
786 if (fcntl(sk
, F_SETFD
, fd
) < 0) {
787 perror("noip: fixup_real_ip_socket F_SETFD");
794 /* The socket SK is about to be used to communicate with the remote address
795 * SA. Assign it a local address so that getpeername(2) does something
798 static int do_implicit_bind(int sk
, const struct sockaddr
**sa
,
799 socklen_t
*len
, struct sockaddr_un
*sun
)
802 socklen_t mylen
= sizeof(*sun
);
804 if (acl_allows_p(connect_real
, *sa
)) {
805 if (fixup_real_ip_socket(sk
, (*sa
)->sa_family
, 0)) return (-1);
807 if (real_getsockname(sk
, SA(sun
), &mylen
) < 0) return (-1);
808 if (sun
->sun_family
== AF_UNIX
) {
809 if (mylen
< sizeof(*sun
)) ((char *)sun
)[mylen
] = 0;
810 if (!sun
->sun_path
[0]) {
811 wildcard_address((*sa
)->sa_family
, &addr
.sa
);
812 encode_inet_addr(sun
, &addr
.sa
, WANT_FRESH
);
813 if (real_bind(sk
, SA(sun
), SUN_LEN(sun
))) return (-1);
815 encode_inet_addr(sun
, *sa
, WANT_EXISTING
);
823 /* We found the real address SA, with length LEN; if it's a Unix-domain
824 * address corresponding to a fake socket, convert it to cover up the
825 * deception. Whatever happens, put the result at FAKE and store its length
828 static void return_fake_name(struct sockaddr
*sa
, socklen_t len
,
829 struct sockaddr
*fake
, socklen_t
*fakelen
)
834 if (sa
->sa_family
== AF_UNIX
&&
835 !decode_inet_addr(&addr
.sa
, 0, SUN(sa
), len
)) {
837 len
= family_socklen(addr
.sa
.sa_family
);
840 if (len
> *fakelen
) len
= *fakelen
;
841 if (len
> 0) memcpy(fake
, sa
, len
);
845 /*----- Configuration -----------------------------------------------------*/
847 /* Return the process owner's home directory. */
848 static char *home(void)
853 if (getuid() == uid
&&
854 (p
= getenv("HOME")) != 0)
856 else if ((pw
= getpwuid(uid
)) != 0)
862 /* Return a good temporary directory to use. */
863 static char *tmpdir(void)
867 if ((p
= getenv("TMPDIR")) != 0) return (p
);
868 else if ((p
= getenv("TMP")) != 0) return (p
);
869 else return ("/tmp");
872 /* Return the user's name, or at least something distinctive. */
873 static char *user(void)
879 if ((p
= getenv("USER")) != 0) return (p
);
880 else if ((p
= getenv("LOGNAME")) != 0) return (p
);
881 else if ((pw
= getpwuid(uid
)) != 0) return (pw
->pw_name
);
883 snprintf(buf
, sizeof(buf
), "uid-%lu", (unsigned long)uid
);
888 /* Skip P over space characters. */
889 #define SKIPSPC do { while (*p && isspace(UC(*p))) p++; } while (0)
891 /* Set Q to point to the next word following P, null-terminate it, and step P
893 #define NEXTWORD(q) do { \
896 while (*p && !isspace(UC(*p))) p++; \
900 /* Set Q to point to the next dotted-quad address, store the ending delimiter
901 * in DEL, null-terminate it, and step P past it. */
902 static void parse_nextaddr(char **pp
, char **qq
, int *del
)
910 p
+= strcspn(p
, "]");
915 while (*p
&& (*p
== '.' || isdigit(UC(*p
)))) p
++;
922 /* Set Q to point to the next decimal number, store the ending delimiter in
923 * DEL, null-terminate it, and step P past it. */
924 #define NEXTNUMBER(q, del) do { \
927 while (*p && isdigit(UC(*p))) p++; \
932 /* Push the character DEL back so we scan it again, unless it's zero
934 #define RESCAN(del) do { if (del) *--p = del; } while (0)
936 /* Evaluate true if P is pointing to the word KW (and not some longer string
937 * of which KW is a prefix). */
939 #define KWMATCHP(kw) (strncmp(p, kw, sizeof(kw) - 1) == 0 && \
940 !isalnum(UC(p[sizeof(kw) - 1])) && \
941 (p += sizeof(kw) - 1))
943 /* Parse a port list, starting at *PP. Port lists have the form
944 * [:LOW[-HIGH]]: if omitted, all ports are included; if HIGH is omitted,
945 * it's as if HIGH = LOW. Store LOW in *MIN, HIGH in *MAX and set *PP to the
946 * rest of the string.
948 static void parse_ports(char **pp
, unsigned short *min
, unsigned short *max
)
955 { *min
= 0; *max
= 0xffff; }
958 NEXTNUMBER(q
, del
); *min
= strtoul(q
, 0, 0); RESCAN(del
);
961 { p
++; NEXTNUMBER(q
, del
); *max
= strtoul(q
, 0, 0); RESCAN(del
); }
968 /* Make a new ACL node. ACT is the verdict; AF is the address family;
969 * MINADDR and MAXADDR are the ranges on IP addresses; MINPORT and MAXPORT
970 * are the ranges on port numbers; TAIL is the list tail to attach the new
973 #define ACLNODE(tail_, act_, \
974 af_, minaddr_, maxaddr_, minport_, maxport_) do { \
979 a_->minaddr = (minaddr_); a_->maxaddr = (maxaddr_); \
980 a_->minport = (minport_); a_->maxport = (maxport_); \
981 *tail_ = a_; tail_ = &a_->next; \
984 /* Parse an ACL line. *PP points to the end of the line; *TAIL points to
985 * the list tail (i.e., the final link in the list). An ACL entry has the
986 * form +|- [any | local | ADDR | ADDR - ADDR | ADDR/ADDR | ADDR/INT] PORTS
987 * where PORTS is parsed by parse_ports above; an ACL line consists of a
988 * comma-separated sequence of entries..
990 static void parse_acl_line(char **pp
, aclnode
***tail
)
992 ipaddr minaddr
, maxaddr
;
993 unsigned short minport
, maxport
;
1002 if (*p
== '+') act
= ALLOW
;
1003 else if (*p
== '-') act
= DENY
;
1008 if (KWMATCHP("any")) {
1009 parse_ports(&p
, &minport
, &maxport
);
1010 for (i
= 0; address_families
[i
] >= 0; i
++) {
1011 af
= address_families
[i
];
1012 memset(&minaddr
, 0, sizeof(minaddr
));
1013 maxaddr
= minaddr
; mask_address(af
, &maxaddr
, 0, 1);
1014 ACLNODE(*tail
, act
, af
, minaddr
, maxaddr
, minport
, maxport
);
1016 } else if (KWMATCHP("local")) {
1017 parse_ports(&p
, &minport
, &maxport
);
1018 for (i
= 0; address_families
[i
] >= 0; i
++) {
1019 af
= address_families
[i
];
1020 memset(&minaddr
, 0, sizeof(minaddr
));
1021 maxaddr
= minaddr
; mask_address(af
, &maxaddr
, 0, 1);
1022 ACLNODE(*tail
, act
, af
, minaddr
, minaddr
, minport
, maxport
);
1023 ACLNODE(*tail
, act
, af
, maxaddr
, maxaddr
, minport
, maxport
);
1025 for (i
= 0; i
< n_local_ipaddrs
; i
++) {
1026 ACLNODE(*tail
, act
, local_ipaddrs
[i
].af
,
1027 local_ipaddrs
[i
].addr
, local_ipaddrs
[i
].addr
,
1031 parse_nextaddr(&p
, &q
, &del
);
1032 af
= guess_address_family(q
);
1033 if (inet_pton(af
, q
, &minaddr
) <= 0) goto bad
;
1038 parse_nextaddr(&p
, &q
, &del
);
1039 if (inet_pton(af
, q
, &maxaddr
) <= 0) goto bad
;
1041 } else if (*p
== '/') {
1044 n
= strtoul(q
, 0, 0);
1046 mask_address(af
, &minaddr
, n
, 0);
1047 mask_address(af
, &maxaddr
, n
, 1);
1051 parse_ports(&p
, &minport
, &maxport
);
1052 ACLNODE(*tail
, act
, af
, minaddr
, maxaddr
, minport
, maxport
);
1055 if (*p
!= ',') break;
1063 D( fprintf(stderr
, "noip(%d): bad acl spec (ignored)\n", getpid()); )
1067 /* Parse the autoports configuration directive. Syntax is MIN - MAX. */
1068 static void parse_autoports(char **pp
)
1075 NEXTNUMBER(q
, del
); x
= strtoul(q
, 0, 0); RESCAN(del
);
1077 if (*p
!= '-') goto bad
; p
++;
1078 NEXTNUMBER(q
, del
); y
= strtoul(q
, 0, 0); RESCAN(del
);
1079 minautoport
= x
; maxautoport
= y
;
1080 SKIPSPC
; if (*p
) goto bad
;
1085 D( fprintf(stderr
, "noip(%d): bad port range (ignored)\n", getpid()); )
1089 /* Parse an ACL from an environment variable VAR, attaching it to the list
1091 static void parse_acl_env(const char *var
, aclnode
***tail
)
1095 if ((p
= getenv(var
)) != 0) {
1097 parse_acl_line(&q
, tail
);
1102 /* Read the configuration from the config file and environment. */
1103 static void readconfig(void)
1111 parse_acl_env("NOIP_REALBIND_BEFORE", &bind_tail
);
1112 parse_acl_env("NOIP_REALCONNECT_BEFORE", &connect_tail
);
1113 if ((p
= getenv("NOIP_AUTOPORTS")) != 0) {
1115 parse_autoports(&q
);
1118 if ((p
= getenv("NOIP_CONFIG")) == 0)
1119 snprintf(p
= buf
, sizeof(buf
), "%s/.noip", home());
1120 D( fprintf(stderr
, "noip(%d): config file: %s\n", pid
, p
); )
1122 if ((fp
= fopen(p
, "r")) == 0) {
1123 D( fprintf(stderr
, "noip(%d): couldn't read config: %s\n",
1124 pid
, strerror(errno
)); )
1127 while (fgets(buf
, sizeof(buf
), fp
)) {
1132 if (!*p
|| *p
== '#') continue;
1133 while (n
&& isspace(UC(buf
[n
- 1]))) n
--;
1138 if (strcmp(cmd
, "socketdir") == 0)
1139 sockdir
= xstrdup(p
);
1140 else if (strcmp(cmd
, "realbind") == 0)
1141 parse_acl_line(&p
, &bind_tail
);
1142 else if (strcmp(cmd
, "realconnect") == 0)
1143 parse_acl_line(&p
, &connect_tail
);
1144 else if (strcmp(cmd
, "autoports") == 0)
1145 parse_autoports(&p
);
1146 else if (strcmp(cmd
, "debug") == 0)
1147 debug
= *p ?
atoi(p
) : 1;
1149 D( fprintf(stderr
, "noip: bad config command %s\n", cmd
); )
1154 parse_acl_env("NOIP_REALBIND", &bind_tail
);
1155 parse_acl_env("NOIP_REALCONNECT", &connect_tail
);
1156 parse_acl_env("NOIP_REALBIND_AFTER", &bind_tail
);
1157 parse_acl_env("NOIP_REALCONNECT_AFTER", &connect_tail
);
1160 if (!sockdir
) sockdir
= getenv("NOIP_SOCKETDIR");
1162 snprintf(buf
, sizeof(buf
), "%s/noip-%s", tmpdir(), user());
1163 sockdir
= xstrdup(buf
);
1165 D( fprintf(stderr
, "noip(%d): socketdir: %s\n", pid
, sockdir
);
1166 fprintf(stderr
, "noip(%d): autoports: %u-%u\n",
1167 pid
, minautoport
, maxautoport
);
1168 fprintf(stderr
, "noip(%d): realbind acl:\n", pid
);
1169 dump_acl(bind_real
);
1170 fprintf(stderr
, "noip(%d): realconnect acl:\n", pid
);
1171 dump_acl(connect_real
); )
1174 /*----- Overridden system calls -------------------------------------------*/
1176 int socket(int pf
, int ty
, int proto
)
1180 if (!family_known_p(pf
)) {
1181 errno
= EAFNOSUPPORT
;
1190 return (real_socket(pf
, ty
, proto
));
1194 int socketpair(int pf
, int ty
, int proto
, int *sk
)
1196 if (family_known_p(pf
)) {
1200 return (real_socketpair(pf
, ty
, proto
, sk
));
1203 int bind(int sk
, const struct sockaddr
*sa
, socklen_t len
)
1205 struct sockaddr_un sun
;
1207 if (family_known_p(sa
->sa_family
)) {
1209 if (acl_allows_p(bind_real
, sa
)) {
1210 if (fixup_real_ip_socket(sk
, sa
->sa_family
, 0))
1213 encode_inet_addr(&sun
, sa
, WANT_FRESH
);
1215 len
= SUN_LEN(&sun
);
1219 return (real_bind(sk
, sa
, len
));
1222 int connect(int sk
, const struct sockaddr
*sa
, socklen_t len
)
1224 struct sockaddr_un sun
;
1227 if (!family_known_p(sa
->sa_family
))
1228 rc
= real_connect(sk
, sa
, len
);
1231 do_implicit_bind(sk
, &sa
, &len
, &sun
);
1233 rc
= real_connect(sk
, sa
, len
);
1236 case ENOENT
: errno
= ECONNREFUSED
; break;
1243 ssize_t
sendto(int sk
, const void *buf
, size_t len
, int flags
,
1244 const struct sockaddr
*to
, socklen_t tolen
)
1246 struct sockaddr_un sun
;
1248 if (to
&& family_known_p(to
->sa_family
)) {
1250 do_implicit_bind(sk
, &to
, &tolen
, &sun
);
1253 return (real_sendto(sk
, buf
, len
, flags
, to
, tolen
));
1256 ssize_t
recvfrom(int sk
, void *buf
, size_t len
, int flags
,
1257 struct sockaddr
*from
, socklen_t
*fromlen
)
1260 socklen_t mylen
= sizeof(sabuf
);
1264 return real_recvfrom(sk
, buf
, len
, flags
, 0, 0);
1266 n
= real_recvfrom(sk
, buf
, len
, flags
, SA(sabuf
), &mylen
);
1269 return_fake_name(SA(sabuf
), mylen
, from
, fromlen
);
1274 ssize_t
sendmsg(int sk
, const struct msghdr
*msg
, int flags
)
1276 struct sockaddr_un sun
;
1277 const struct sockaddr
*sa
;
1278 struct msghdr mymsg
;
1280 if (msg
->msg_name
&& family_known_p(SA(msg
->msg_name
)->sa_family
)) {
1282 sa
= SA(msg
->msg_name
);
1284 do_implicit_bind(sk
, &sa
, &mymsg
.msg_namelen
, &sun
);
1285 mymsg
.msg_name
= SA(sa
);
1289 return (real_sendmsg(sk
, msg
, flags
));
1292 ssize_t
recvmsg(int sk
, struct msghdr
*msg
, int flags
)
1295 struct sockaddr
*sa
;
1300 return (real_recvmsg(sk
, msg
, flags
));
1302 sa
= SA(msg
->msg_name
);
1303 len
= msg
->msg_namelen
;
1304 msg
->msg_name
= sabuf
;
1305 msg
->msg_namelen
= sizeof(sabuf
);
1306 n
= real_recvmsg(sk
, msg
, flags
);
1309 return_fake_name(SA(sabuf
), msg
->msg_namelen
, sa
, &len
);
1311 msg
->msg_namelen
= len
;
1316 int accept(int sk
, struct sockaddr
*sa
, socklen_t
*len
)
1319 socklen_t mylen
= sizeof(sabuf
);
1320 int nsk
= real_accept(sk
, SA(sabuf
), &mylen
);
1324 return_fake_name(SA(sabuf
), mylen
, sa
, len
);
1328 int getsockname(int sk
, struct sockaddr
*sa
, socklen_t
*len
)
1332 socklen_t mylen
= sizeof(sabuf
);
1333 if (real_getsockname(sk
, SA(sabuf
), &mylen
))
1335 return_fake_name(SA(sabuf
), mylen
, sa
, len
);
1340 int getpeername(int sk
, struct sockaddr
*sa
, socklen_t
*len
)
1344 socklen_t mylen
= sizeof(sabuf
);
1345 if (real_getpeername(sk
, SA(sabuf
), &mylen
))
1347 return_fake_name(SA(sabuf
), mylen
, sa
, len
);
1352 int getsockopt(int sk
, int lev
, int opt
, void *p
, socklen_t
*len
)
1362 return (real_getsockopt(sk
, lev
, opt
, p
, len
));
1365 int setsockopt(int sk
, int lev
, int opt
, const void *p
, socklen_t len
)
1374 case SO_BINDTODEVICE
:
1375 case SO_ATTACH_FILTER
:
1376 case SO_DETACH_FILTER
:
1379 return (real_setsockopt(sk
, lev
, opt
, p
, len
));
1382 int ioctl(int fd
, unsigned long op
, ...)
1390 arg
= va_arg(ap
, void *);
1394 case SIOCGIFBRDADDR
:
1395 case SIOCGIFDSTADDR
:
1396 case SIOCGIFNETMASK
:
1398 if (fixup_real_ip_socket(fd
, AF_INET
, &sk
)) goto real
;
1400 rc
= real_ioctl(sk
, op
, arg
);
1401 PRESERVING_ERRNO({ close(sk
); });
1405 rc
= real_ioctl(fd
, op
, arg
);
1412 /*----- Initialization ----------------------------------------------------*/
1414 /* Clean up the socket directory, deleting stale sockets. */
1415 static void cleanup_sockdir(void)
1420 struct sockaddr_un sun
;
1424 if ((dir
= opendir(sockdir
)) == 0) return;
1425 sun
.sun_family
= AF_UNIX
;
1426 while ((d
= readdir(dir
)) != 0) {
1427 if (d
->d_name
[0] == '.') continue;
1428 snprintf(sun
.sun_path
, sizeof(sun
.sun_path
),
1429 "%s/%s", sockdir
, d
->d_name
);
1430 if (decode_inet_addr(&addr
.sa
, 0, &sun
, SUN_LEN(&sun
)) ||
1431 stat(sun
.sun_path
, &st
) ||
1432 !S_ISSOCK(st
.st_mode
)) {
1433 D( fprintf(stderr
, "noip(%d): ignoring unknown socketdir entry `%s'\n",
1434 pid
, sun
.sun_path
); )
1437 if (unix_socket_status(&sun
, 0) == STALE
) {
1438 D( fprintf(stderr
, "noip(%d): clearing away stale socket %s\n",
1440 unlink(sun
.sun_path
);
1446 /* Find the addresses attached to local network interfaces, and remember them
1449 static void get_local_ipaddrs(void)
1451 struct ifaddrs
*ifa_head
, *ifa
;
1456 D( fprintf(stderr
, "noip(%d): fetching local addresses...\n", pid
); )
1457 if (getifaddrs(&ifa_head
)) { perror("getifaddrs"); return; }
1458 for (n_local_ipaddrs
= 0, ifa
= ifa_head
;
1459 n_local_ipaddrs
< MAX_LOCAL_IPADDRS
&& ifa
;
1460 ifa
= ifa
->ifa_next
) {
1461 if (!ifa
->ifa_addr
|| !family_known_p(ifa
->ifa_addr
->sa_family
))
1463 ipaddr_from_sockaddr(&a
, ifa
->ifa_addr
);
1464 D({ char buf
[ADDRBUFSZ
];
1465 fprintf(stderr
, "noip(%d): local addr %s = %s", pid
,
1467 inet_ntop(ifa
->ifa_addr
->sa_family
, &a
,
1468 buf
, sizeof(buf
))); })
1469 for (i
= 0; i
< n_local_ipaddrs
; i
++) {
1470 if (ifa
->ifa_addr
->sa_family
== local_ipaddrs
[i
].af
&&
1471 ipaddr_equal_p(local_ipaddrs
[i
].af
, &a
, &local_ipaddrs
[i
].addr
)) {
1472 D( fprintf(stderr
, " (duplicate)\n"); )
1476 D( fprintf(stderr
, "\n"); )
1477 local_ipaddrs
[n_local_ipaddrs
].af
= ifa
->ifa_addr
->sa_family
;
1478 local_ipaddrs
[n_local_ipaddrs
].addr
= a
;
1482 freeifaddrs(ifa_head
);
1485 /* Print the given message to standard error. Avoids stdio. */
1486 static void printerr(const char *p
)
1487 { if (write(STDERR_FILENO
, p
, strlen(p
))) ; }
1489 /* Create the socket directory, being careful about permissions. */
1490 static void create_sockdir(void)
1494 if (lstat(sockdir
, &st
)) {
1495 if (errno
== ENOENT
) {
1496 if (mkdir(sockdir
, 0700)) {
1497 perror("noip: creating socketdir");
1500 if (!lstat(sockdir
, &st
))
1503 perror("noip: checking socketdir");
1507 if (!S_ISDIR(st
.st_mode
)) {
1508 printerr("noip: bad socketdir: not a directory\n");
1511 if (st
.st_uid
!= uid
) {
1512 printerr("noip: bad socketdir: not owner\n");
1515 if (st
.st_mode
& 077) {
1516 printerr("noip: bad socketdir: not private\n");
1521 /* Initialization function. */
1522 static void setup(void) __attribute__((constructor
));
1523 static void setup(void)
1530 if ((p
= getenv("NOIP_DEBUG")) && atoi(p
))
1532 get_local_ipaddrs();
1539 /*----- That's all, folks -------------------------------------------------*/