3 * Make programs use Unix-domain sockets instead of IP
5 * (c) 2008 Straylight/Edgeware
8 /*----- Licensing notice --------------------------------------------------*
10 * This file is part of the preload-hacks package.
12 * Preload-hacks are free software; you can redistribute it and/or modify
13 * them under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or (at
15 * your option) any later version.
17 * Preload-hacks are distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
19 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
22 * You should have received a copy of the GNU General Public License along
23 * with preload-hacks; if not, write to the Free Software Foundation, Inc.,
24 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
32 /*----- Header files ------------------------------------------------------*/
47 #include <sys/ioctl.h>
48 #include <sys/socket.h>
52 #include <netinet/in.h>
53 #include <arpa/inet.h>
54 #include <netinet/tcp.h>
55 #include <netinet/udp.h>
59 /*----- Data structures ---------------------------------------------------*/
61 enum { UNUSED
, STALE
, USED
}; /* Unix socket status values */
62 enum { WANT_FRESH
, WANT_EXISTING
}; /* Socket address dispositions */
63 enum { DENY
, ALLOW
}; /* ACL verdicts */
65 static int address_families
[] = { AF_INET
, -1 };
69 /* Address representations. */
70 typedef union ipaddr
{
74 /* Convenient socket address hacking. */
75 typedef union address
{
77 struct sockaddr_in sin
;
80 /* Access control list nodes */
81 typedef struct aclnode
{
85 ipaddr minaddr
, maxaddr
;
86 unsigned short minport
, maxport
;
89 /* Local address records */
90 typedef struct full_ipaddr
{
94 #define MAX_LOCAL_IPADDRS 16
95 static full_ipaddr local_ipaddrs
[MAX_LOCAL_IPADDRS
];
96 static int n_local_ipaddrs
;
98 /* General configuration */
100 static char *sockdir
= 0;
101 static int debug
= 0;
102 static unsigned minautoport
= 16384, maxautoport
= 65536;
104 /* Access control lists */
105 static aclnode
*bind_real
, **bind_tail
= &bind_real
;
106 static aclnode
*connect_real
, **connect_tail
= &connect_real
;
108 /*----- Import the real versions of functions -----------------------------*/
110 /* The list of functions to immport. */
112 _(socket, int, (int, int, int)) \
113 _(socketpair, int, (int, int, int, int *)) \
114 _(connect, int, (int, const struct sockaddr *, socklen_t)) \
115 _(bind, int, (int, const struct sockaddr *, socklen_t)) \
116 _(accept, int, (int, struct sockaddr *, socklen_t *)) \
117 _(getsockname, int, (int, struct sockaddr *, socklen_t *)) \
118 _(getpeername, int, (int, struct sockaddr *, socklen_t *)) \
119 _(getsockopt, int, (int, int, int, void *, socklen_t *)) \
120 _(setsockopt, int, (int, int, int, const void *, socklen_t)) \
121 _(sendto, ssize_t, (int, const void *buf, size_t, int, \
122 const struct sockaddr *to, socklen_t tolen)) \
123 _(recvfrom, ssize_t, (int, void *buf, size_t, int, \
124 struct sockaddr *from, socklen_t *fromlen)) \
125 _(sendmsg, ssize_t, (int, const struct msghdr *, int)) \
126 _(recvmsg, ssize_t, (int, struct msghdr *, int))
128 /* Function pointers to set up. */
129 #define DECL(imp, ret, args) static ret (*real_##imp) args;
133 /* Import the system calls. */
134 static void import(void)
136 #define IMPORT(imp, ret, args) \
137 real_##imp = (ret (*)args)dlsym(RTLD_NEXT, #imp);
142 /*----- Utilities ---------------------------------------------------------*/
144 /* Socket address casts */
145 #define SA(sa) ((struct sockaddr *)(sa))
146 #define SIN(sa) ((struct sockaddr_in *)(sa))
147 #define SUN(sa) ((struct sockaddr_un *)(sa))
150 #define UC(ch) ((unsigned char)(ch))
152 /* Memory allocation */
153 #define NEW(x) ((x) = xmalloc(sizeof(*x)))
154 #define NEWV(x, n) ((x) = xmalloc(sizeof(*x) * (n)))
158 # define D(body) { if (debug) { body } }
163 /* Preservation of error status */
164 #define PRESERVING_ERRNO(body) do { \
165 int _err = errno; { body } errno = _err; \
168 /* Allocate N bytes of memory; abort on failure. */
169 static void *xmalloc(size_t n
)
173 if ((p
= malloc(n
)) == 0) { perror("malloc"); exit(127); }
177 /* Allocate a copy of the null-terminated string P; abort on failure. */
178 static char *xstrdup(const char *p
)
180 size_t n
= strlen(p
) + 1;
181 char *q
= xmalloc(n
);
186 /*----- Address-type hacking ----------------------------------------------*/
188 /* If M is a simple mask, i.e., consists of a sequence of zero bits followed
189 * by a sequence of one bits, then return the length of the latter sequence
190 * (which may be zero); otherwise return -1.
192 static int simple_mask_length(unsigned long m
)
196 while (m
& 1) { n
++; m
>>= 1; }
200 /* Answer whether AF is an interesting address family. */
201 static int family_known_p(int af
)
211 /* Return the socket address length for address family AF. */
212 static socklen_t
family_socklen(int af
)
215 case AF_INET
: return (sizeof(struct sockaddr_in
));
220 /* Return the width of addresses of kind AF. */
221 static int address_width(int af
)
224 case AF_INET
: return 32;
229 /* If addresses A and B share a common prefix then return its length;
230 * otherwise return -1.
232 static int common_prefix_length(int af
, const ipaddr
*a
, const ipaddr
*b
)
236 unsigned long aa
= ntohl(a
->v4
.s_addr
), bb
= ntohl(b
->v4
.s_addr
);
237 unsigned long m
= aa
^bb
;
238 if ((aa
&m
) == 0 && (bb
&m
) == m
) return (32 - simple_mask_length(m
));
246 /* Extract the port number (in host byte-order) from SA. */
247 static int port_from_sockaddr(const struct sockaddr
*sa
)
249 switch (sa
->sa_family
) {
250 case AF_INET
: return (ntohs(SIN(sa
)->sin_port
));
255 /* Store the port number PORT (in host byte-order) in SA. */
256 static void port_to_sockaddr(struct sockaddr
*sa
, int port
)
258 switch (sa
->sa_family
) {
259 case AF_INET
: SIN(sa
)->sin_port
= htons(port
); break;
263 /* Extract the address part from SA and store it in A. */
264 static void ipaddr_from_sockaddr(ipaddr
*a
, const struct sockaddr
*sa
)
266 switch (sa
->sa_family
) {
267 case AF_INET
: a
->v4
= SIN(sa
)->sin_addr
; break;
272 /* Copy a whole socket address about. */
273 static void copy_sockaddr(struct sockaddr
*sa_dst
,
274 const struct sockaddr
*sa_src
)
275 { memcpy(sa_dst
, sa_src
, family_socklen(sa_src
->sa_family
)); }
277 /* Answer whether two addresses are equal. */
278 static int ipaddr_equal_p(int af
, const ipaddr
*a
, const ipaddr
*b
)
281 case AF_INET
: return (a
->v4
.s_addr
== b
->v4
.s_addr
);
286 /* Answer whether the address part of SA is between A and B (inclusive). We
287 * assume that SA has the correct address family.
289 static int sockaddr_in_range_p(const struct sockaddr
*sa
,
290 const ipaddr
*a
, const ipaddr
*b
)
292 switch (sa
->sa_family
) {
294 unsigned long addr
= ntohl(SIN(sa
)->sin_addr
.s_addr
);
295 return (ntohl(a
->v4
.s_addr
) <= addr
&&
296 addr
<= ntohl(b
->v4
.s_addr
));
303 /* Fill in SA with the appropriate wildcard address. */
304 static void wildcard_address(int af
, struct sockaddr
*sa
)
308 struct sockaddr_in
*sin
= SIN(sa
);
309 memset(sin
, 0, sizeof(*sin
));
310 sin
->sin_family
= AF_INET
;
312 sin
->sin_addr
.s_addr
= INADDR_ANY
;
319 /* Mask the address A, forcing all but the top PLEN bits to zero or one
320 * according to HIGHP.
322 static void mask_address(int af
, ipaddr
*a
, int plen
, int highp
)
326 unsigned long addr
= ntohl(a
->v4
.s_addr
);
327 unsigned long mask
= plen ?
~0ul << (32 - plen
) : 0;
329 if (highp
) addr
|= ~mask
;
330 a
->v4
.s_addr
= htonl(addr
& 0xffffffff);
337 /* Write a presentation form of SA to BUF, a buffer of length SZ. LEN is the
338 * address length; if it's zero, look it up based on the address family.
339 * Return a pointer to the string (which might, in an emergency, be a static
340 * string rather than your buffer).
342 static char *present_sockaddr(const struct sockaddr
*sa
, socklen_t len
,
343 char *buf
, size_t sz
)
345 #define WANT(n_) do { if (sz < (n_)) goto nospace; } while (0)
346 #define PUTC(c_) do { *buf++ = (c_); sz--; } while (0)
348 if (!sz
) return "<no-space-in-buffer>";
349 if (!len
) len
= family_socklen(sa
->sa_family
);
351 switch (sa
->sa_family
) {
353 struct sockaddr_un
*sun
= SUN(sa
);
354 char *p
= sun
->sun_path
;
355 size_t n
= len
- offsetof(struct sockaddr_un
, sun_path
);
363 case 0: WANT(2); PUTC('\\'); PUTC('0'); break;
364 case '\a': WANT(2); PUTC('\\'); PUTC('a'); break;
365 case '\n': WANT(2); PUTC('\\'); PUTC('n'); break;
366 case '\r': WANT(2); PUTC('\\'); PUTC('r'); break;
367 case '\t': WANT(2); PUTC('\\'); PUTC('t'); break;
368 case '\v': WANT(2); PUTC('\\'); PUTC('v'); break;
369 case '\\': WANT(2); PUTC('\\'); PUTC('\\'); break;
371 if (*p
> ' ' && *p
<= '~')
372 { WANT(1); PUTC(*p
); }
374 WANT(4); PUTC('\\'); PUTC('x');
375 PUTC((*p
>> 4)&0xf); PUTC((*p
>> 0)&0xf);
382 if (*p
!= '/') { WANT(2); PUTC('.'); PUTC('/'); }
383 while (n
&& *p
) { WANT(1); PUTC(*p
); p
++; n
--; }
388 char addrbuf
[NI_MAXHOST
], portbuf
[NI_MAXSERV
];
389 int err
= getnameinfo(sa
, len
,
390 addrbuf
, sizeof(addrbuf
),
391 portbuf
, sizeof(portbuf
),
392 NI_NUMERICHOST
| NI_NUMERICSERV
);
394 snprintf(buf
, sz
, strchr(addrbuf
, ':') ?
"[%s]:%s" : "%s:%s",
398 snprintf(buf
, sz
, "<unknown-address-family %d>", sa
->sa_family
);
408 /* Guess the family of a textual socket address. */
409 static int guess_address_family(const char *p
)
410 { return (AF_INET
); }
412 /* Parse a socket address P and write the result to SA. */
413 static int parse_sockaddr(struct sockaddr
*sa
, const char *p
)
417 struct addrinfo
*ai
, ai_hint
= { 0 };
419 if (strlen(p
) >= sizeof(buf
) - 1) return (-1);
420 strcpy(buf
, p
); p
= buf
;
422 if ((q
= strchr(p
, ':')) == 0) return (-1);
426 if ((q
= strchr(p
, ']')) == 0) return (-1);
428 if (*q
!= ':') return (-1);
432 ai_hint
.ai_family
= AF_UNSPEC
;
433 ai_hint
.ai_socktype
= SOCK_DGRAM
;
434 ai_hint
.ai_flags
= AI_NUMERICHOST
| AI_NUMERICSERV
;
435 if (getaddrinfo(p
, q
, &ai_hint
, &ai
)) return (-1);
436 memcpy(sa
, ai
->ai_addr
, ai
->ai_addrlen
);
441 /*----- Access control lists ----------------------------------------------*/
445 /* Write to standard error a description of the ACL node A. */
446 static void dump_aclnode(aclnode
*a
)
452 fprintf(stderr
, "noip: %c ", a
->act ?
'+' : '-');
453 plen
= common_prefix_length(a
->af
, &a
->minaddr
, &a
->maxaddr
);
454 p
= inet_ntop(a
->af
, &a
->minaddr
, buf
, sizeof(buf
));
455 fprintf(stderr
, strchr(p
, ':') ?
"[%s]" : "%s", p
);
457 p
= inet_ntop(a
->af
, &a
->maxaddr
, buf
, sizeof(buf
));
458 fprintf(stderr
, strchr(p
, ':') ?
"-[%s]" : "-%s", p
);
459 } else if (plen
< address_width(a
->af
))
460 fprintf(stderr
, "/%d", plen
);
461 if (a
->minport
!= 0 || a
->maxport
!= 0xffff) {
462 fprintf(stderr
, ":%u", (unsigned)a
->minport
);
463 if (a
->minport
!= a
->maxport
)
464 fprintf(stderr
, "-%u", (unsigned)a
->maxport
);
469 static void dump_acl(aclnode
*a
)
473 for (; a
; a
= a
->next
) {
477 fprintf(stderr
, "noip: [default policy: %s]\n",
478 act
== ALLOW ?
"DENY" : "ALLOW");
483 /* Returns nonzero if the ACL A allows the socket address SA. */
484 static int acl_allows_p(aclnode
*a
, const struct sockaddr
*sa
)
486 unsigned short port
= port_from_sockaddr(sa
);
489 D({ char buf
[ADDRBUFSZ
];
490 fprintf(stderr
, "noip: check %s\n",
491 present_sockaddr(sa
, 0, buf
, sizeof(buf
))); })
492 for (; a
; a
= a
->next
) {
493 D( dump_aclnode(a
); )
494 if (sockaddr_in_range_p(sa
, &a
->minaddr
, &a
->maxaddr
) &&
495 a
->minport
<= port
&& port
<= a
->maxport
) {
496 D( fprintf(stderr
, "noip: aha! %s\n", a
->act ?
"ALLOW" : "DENY"); )
501 D( fprintf(stderr
, "noip: nothing found: %s\n", act ?
"DENY" : "ALLOW"); )
505 /*----- Socket address conversion -----------------------------------------*/
507 /* Return a uniformly distributed integer between MIN and MAX inclusive. */
508 static unsigned randrange(unsigned min
, unsigned max
)
512 /* It's so nice not to have to care about the quality of the generator
516 for (mask
= 1; mask
< max
; mask
= (mask
<< 1) | 1)
518 do i
= rand() & mask
; while (i
> max
);
522 /* Return the status of Unix-domain socket address SUN. Returns: UNUSED if
523 * the socket doesn't exist; USED if the path refers to an active socket, or
524 * isn't really a socket at all, or we can't tell without a careful search
525 * and QUICKP is set; or STALE if the file refers to a socket which isn't
526 * being used any more.
528 static int unix_socket_status(struct sockaddr_un
*sun
, int quickp
)
536 if (stat(sun
->sun_path
, &st
))
537 return (errno
== ENOENT ? UNUSED
: USED
);
538 if (!S_ISSOCK(st
.st_mode
) || quickp
)
541 if ((fp
= fopen("/proc/net/unix", "r")) == 0)
543 if (!fgets(buf
, sizeof(buf
), fp
)) goto done
; /* skip header */
544 len
= strlen(sun
->sun_path
);
545 while (fgets(buf
, sizeof(buf
), fp
)) {
547 if (n
>= len
+ 2 && buf
[n
- len
- 2] == ' ' && buf
[n
- 1] == '\n' &&
548 memcmp(buf
+ n
- len
- 1, sun
->sun_path
, len
) == 0)
559 /* Encode the Internet address SA as a Unix-domain address SUN. If WANT is
560 * WANT_FRESH, and SA's port number is zero, then we pick an arbitrary local
561 * port. Otherwise we pick the port given. There's an unpleasant hack to
562 * find servers bound to local wildcard addresses. Returns zero on success;
565 static int encode_inet_addr(struct sockaddr_un
*sun
,
566 const struct sockaddr
*sa
,
575 D( fprintf(stderr
, "noip: encode %s (%s)",
576 present_sockaddr(sa
, 0, buf
, sizeof(buf
)),
577 want
== WANT_EXISTING ?
"EXISTING" : "FRESH"); )
578 sun
->sun_family
= AF_UNIX
;
579 if (port_from_sockaddr(sa
) || want
== WANT_EXISTING
) {
580 snprintf(sun
->sun_path
, sizeof(sun
->sun_path
), "%s/%s", sockdir
,
581 present_sockaddr(sa
, 0, buf
, sizeof(buf
)));
582 rc
= unix_socket_status(sun
, 0);
583 if (rc
== STALE
) unlink(sun
->sun_path
);
584 if (rc
!= USED
&& want
== WANT_EXISTING
) {
585 wildcard_address(sa
->sa_family
, &addr
.sa
);
586 port_to_sockaddr(&addr
.sa
, port_from_sockaddr(sa
));
587 snprintf(sun
->sun_path
, sizeof(sun
->sun_path
), "%s/%s", sockdir
,
588 present_sockaddr(&addr
.sa
, 0, buf
, sizeof(buf
)));
589 if (unix_socket_status(sun
, 0) == STALE
) unlink(sun
->sun_path
);
592 copy_sockaddr(&addr
.sa
, sa
);
593 for (i
= 0; i
< 10; i
++) {
594 port_to_sockaddr(&addr
.sa
, randrange(minautoport
, maxautoport
));
595 snprintf(sun
->sun_path
, sizeof(sun
->sun_path
), "%s/%s", sockdir
,
596 present_sockaddr(&addr
.sa
, 0, buf
, sizeof(buf
)));
597 if (unix_socket_status(sun
, 1) == UNUSED
) goto found
;
599 for (desperatep
= 0; desperatep
< 2; desperatep
++) {
600 for (i
= minautoport
; i
<= maxautoport
; i
++) {
601 port_to_sockaddr(&addr
.sa
, i
);
602 snprintf(sun
->sun_path
, sizeof(sun
->sun_path
), "%s/%s", sockdir
,
603 present_sockaddr(&addr
.sa
, 0, buf
, sizeof(buf
)));
604 rc
= unix_socket_status(sun
, !desperatep
);
606 case STALE
: unlink(sun
->sun_path
);
607 case UNUSED
: goto found
;
612 D( fprintf(stderr
, " -- can't resolve\n"); )
616 D( fprintf(stderr
, " -> `%s'\n", sun
->sun_path
); )
620 /* Decode the Unix address SUN to an Internet address SIN. If AF_HINT is
621 * nonzero, an empty address (indicative of an unbound Unix-domain socket) of
622 * the is translated to a wildcard Internet address of the appropriate
623 * family. Returns zero on success; -1 on failure (e.g., it wasn't one of
626 static int decode_inet_addr(struct sockaddr
*sa
, int af_hint
,
627 const struct sockaddr_un
*sun
,
631 size_t n
= strlen(sockdir
), nn
;
634 if (!sa
) sa
= &addr
.sa
;
635 if (sun
->sun_family
!= AF_UNIX
) return (-1);
636 if (len
> sizeof(*sun
)) return (-1);
637 ((char *)sun
)[len
] = 0;
638 nn
= strlen(sun
->sun_path
);
639 D( fprintf(stderr
, "noip: decode `%s'", sun
->sun_path
); )
640 if (af_hint
&& !sun
->sun_path
[0]) {
641 wildcard_address(af_hint
, sa
);
642 D( fprintf(stderr
, " -- unbound socket\n"); )
645 if (nn
< n
+ 1 || nn
- n
>= sizeof(buf
) || sun
->sun_path
[n
] != '/' ||
646 memcmp(sun
->sun_path
, sockdir
, n
) != 0) {
647 D( fprintf(stderr
, " -- not one of ours\n"); )
650 if (parse_sockaddr(sa
, sun
->sun_path
+ n
+ 1)) return (-1);
651 D( fprintf(stderr
, " -> %s\n",
652 present_sockaddr(sa
, 0, buf
, sizeof(buf
))); )
656 /* SK is (or at least might be) a Unix-domain socket we created when an
657 * Internet socket was asked for. We've decided it should be an Internet
658 * socket after all, with family AF_HINT, so convert it.
660 static int fixup_real_ip_socket(int sk
, int af_hint
)
665 struct sockaddr_un sun
;
678 _(LINGER, struct linger) \
681 _(RCVTIMEO, struct timeval) \
682 _(SNDTIMEO, struct timeval)
685 if (real_getsockname(sk
, SA(&sun
), &len
))
687 if (decode_inet_addr(&addr
.sa
, af_hint
, &sun
, len
))
688 return (0); /* Not one of ours */
690 if (real_getsockopt(sk
, SOL_SOCKET
, SO_TYPE
, &type
, &len
) < 0 ||
691 (nsk
= real_socket(addr
.sa
.sa_family
, type
, 0)) < 0)
693 #define FIX(opt, ty) do { \
696 if (real_getsockopt(sk, SOL_SOCKET, SO_##opt, &ov_, &len) < 0 || \
697 real_setsockopt(nsk, SOL_SOCKET, SO_##opt, &ov_, len)) { \
704 if ((f
= fcntl(sk
, F_GETFL
)) < 0 ||
705 (fd
= fcntl(sk
, F_GETFD
)) < 0 ||
706 fcntl(nsk
, F_SETFL
, f
) < 0 ||
711 unlink(sun
.sun_path
);
713 if (fcntl(sk
, F_SETFD
, fd
) < 0) {
714 perror("noip: fixup_real_ip_socket F_SETFD");
720 /* The socket SK is about to be used to communicate with the remote address
721 * SA. Assign it a local address so that getpeername(2) does something
724 static int do_implicit_bind(int sk
, const struct sockaddr
**sa
,
725 socklen_t
*len
, struct sockaddr_un
*sun
)
728 socklen_t mylen
= sizeof(*sun
);
730 if (acl_allows_p(connect_real
, *sa
)) {
731 if (fixup_real_ip_socket(sk
, (*sa
)->sa_family
)) return (-1);
733 if (real_getsockname(sk
, SA(sun
), &mylen
) < 0) return (-1);
734 if (sun
->sun_family
== AF_UNIX
) {
735 if (mylen
< sizeof(*sun
)) ((char *)sun
)[mylen
] = 0;
736 if (!sun
->sun_path
[0]) {
737 wildcard_address((*sa
)->sa_family
, &addr
.sa
);
738 encode_inet_addr(sun
, &addr
.sa
, WANT_FRESH
);
739 if (real_bind(sk
, SA(sun
), SUN_LEN(sun
))) return (-1);
741 encode_inet_addr(sun
, *sa
, WANT_EXISTING
);
749 /* We found the real address SA, with length LEN; if it's a Unix-domain
750 * address corresponding to a fake socket, convert it to cover up the
751 * deception. Whatever happens, put the result at FAKE and store its length
754 static void return_fake_name(struct sockaddr
*sa
, socklen_t len
,
755 struct sockaddr
*fake
, socklen_t
*fakelen
)
760 if (sa
->sa_family
== AF_UNIX
&&
761 !decode_inet_addr(&addr
.sa
, 0, SUN(sa
), len
)) {
763 len
= family_socklen(addr
.sa
.sa_family
);
766 if (len
> *fakelen
) len
= *fakelen
;
767 if (len
> 0) memcpy(fake
, sa
, len
);
771 /*----- Configuration -----------------------------------------------------*/
773 /* Return the process owner's home directory. */
774 static char *home(void)
779 if (getuid() == uid
&&
780 (p
= getenv("HOME")) != 0)
782 else if ((pw
= getpwuid(uid
)) != 0)
788 /* Return a good temporary directory to use. */
789 static char *tmpdir(void)
793 if ((p
= getenv("TMPDIR")) != 0) return (p
);
794 else if ((p
= getenv("TMP")) != 0) return (p
);
795 else return ("/tmp");
798 /* Return the user's name, or at least something distinctive. */
799 static char *user(void)
805 if ((p
= getenv("USER")) != 0) return (p
);
806 else if ((p
= getenv("LOGNAME")) != 0) return (p
);
807 else if ((pw
= getpwuid(uid
)) != 0) return (pw
->pw_name
);
809 snprintf(buf
, sizeof(buf
), "uid-%lu", (unsigned long)uid
);
814 /* Skip P over space characters. */
815 #define SKIPSPC do { while (*p && isspace(UC(*p))) p++; } while (0)
817 /* Set Q to point to the next word following P, null-terminate it, and step P
819 #define NEXTWORD(q) do { \
822 while (*p && !isspace(UC(*p))) p++; \
826 /* Set Q to point to the next dotted-quad address, store the ending delimiter
827 * in DEL, null-terminate it, and step P past it. */
828 static void parse_nextaddr(char **pp
, char **qq
, int *del
)
836 p
+= strcspn(p
, "]");
841 while (*p
&& (*p
== '.' || isdigit(UC(*p
)))) p
++;
848 /* Set Q to point to the next decimal number, store the ending delimiter in
849 * DEL, null-terminate it, and step P past it. */
850 #define NEXTNUMBER(q, del) do { \
853 while (*p && isdigit(UC(*p))) p++; \
858 /* Push the character DEL back so we scan it again, unless it's zero
860 #define RESCAN(del) do { if (del) *--p = del; } while (0)
862 /* Evaluate true if P is pointing to the word KW (and not some longer string
863 * of which KW is a prefix). */
865 #define KWMATCHP(kw) (strncmp(p, kw, sizeof(kw) - 1) == 0 && \
866 !isalnum(UC(p[sizeof(kw) - 1])) && \
867 (p += sizeof(kw) - 1))
869 /* Parse a port list, starting at *PP. Port lists have the form
870 * [:LOW[-HIGH]]: if omitted, all ports are included; if HIGH is omitted,
871 * it's as if HIGH = LOW. Store LOW in *MIN, HIGH in *MAX and set *PP to the
872 * rest of the string.
874 static void parse_ports(char **pp
, unsigned short *min
, unsigned short *max
)
881 { *min
= 0; *max
= 0xffff; }
884 NEXTNUMBER(q
, del
); *min
= strtoul(q
, 0, 0); RESCAN(del
);
887 { p
++; NEXTNUMBER(q
, del
); *max
= strtoul(q
, 0, 0); RESCAN(del
); }
894 /* Make a new ACL node. ACT is the verdict; AF is the address family;
895 * MINADDR and MAXADDR are the ranges on IP addresses; MINPORT and MAXPORT
896 * are the ranges on port numbers; TAIL is the list tail to attach the new
899 #define ACLNODE(tail_, act_, \
900 af_, minaddr_, maxaddr_, minport_, maxport_) do { \
905 a_->minaddr = (minaddr_); a_->maxaddr = (maxaddr_); \
906 a_->minport = (minport_); a_->maxport = (maxport_); \
907 *tail_ = a_; tail_ = &a_->next; \
910 /* Parse an ACL line. *PP points to the end of the line; *TAIL points to
911 * the list tail (i.e., the final link in the list). An ACL entry has the
912 * form +|- [any | local | ADDR | ADDR - ADDR | ADDR/ADDR | ADDR/INT] PORTS
913 * where PORTS is parsed by parse_ports above; an ACL line consists of a
914 * comma-separated sequence of entries..
916 static void parse_acl_line(char **pp
, aclnode
***tail
)
918 ipaddr minaddr
, maxaddr
;
919 unsigned short minport
, maxport
;
928 if (*p
== '+') act
= ALLOW
;
929 else if (*p
== '-') act
= DENY
;
934 if (KWMATCHP("any")) {
935 parse_ports(&p
, &minport
, &maxport
);
936 for (i
= 0; address_families
[i
] >= 0; i
++) {
937 af
= address_families
[i
];
938 memset(&minaddr
, 0, sizeof(minaddr
));
939 maxaddr
= minaddr
; mask_address(af
, &maxaddr
, 0, 1);
940 ACLNODE(*tail
, act
, af
, minaddr
, maxaddr
, minport
, maxport
);
942 } else if (KWMATCHP("local")) {
943 parse_ports(&p
, &minport
, &maxport
);
944 for (i
= 0; address_families
[i
] >= 0; i
++) {
945 af
= address_families
[i
];
946 memset(&minaddr
, 0, sizeof(minaddr
));
947 maxaddr
= minaddr
; mask_address(af
, &maxaddr
, 0, 1);
948 ACLNODE(*tail
, act
, af
, minaddr
, minaddr
, minport
, maxport
);
949 ACLNODE(*tail
, act
, af
, maxaddr
, maxaddr
, minport
, maxport
);
951 for (i
= 0; i
< n_local_ipaddrs
; i
++) {
952 ACLNODE(*tail
, act
, local_ipaddrs
[i
].af
,
953 local_ipaddrs
[i
].addr
, local_ipaddrs
[i
].addr
,
957 parse_nextaddr(&p
, &q
, &del
);
958 af
= guess_address_family(q
);
959 if (inet_pton(af
, q
, &minaddr
) <= 0) goto bad
;
964 parse_nextaddr(&p
, &q
, &del
);
965 if (inet_pton(af
, q
, &maxaddr
) <= 0) goto bad
;
967 } else if (*p
== '/') {
970 n
= strtoul(q
, 0, 0);
972 mask_address(af
, &minaddr
, n
, 0);
973 mask_address(af
, &maxaddr
, n
, 1);
976 parse_ports(&p
, &minport
, &maxport
);
977 ACLNODE(*tail
, act
, af
, minaddr
, maxaddr
, minport
, maxport
);
980 if (*p
!= ',') break;
986 D( fprintf(stderr
, "noip: bad acl spec (ignored)\n"); )
990 /* Parse the autoports configuration directive. Syntax is MIN - MAX. */
991 static void parse_autoports(char **pp
)
998 NEXTNUMBER(q
, del
); x
= strtoul(q
, 0, 0); RESCAN(del
);
1000 if (*p
!= '-') goto bad
; p
++;
1001 NEXTNUMBER(q
, del
); y
= strtoul(q
, 0, 0); RESCAN(del
);
1002 minautoport
= x
; maxautoport
= y
;
1006 D( fprintf(stderr
, "bad port range (ignored)\n"); )
1010 /* Parse an ACL from an environment variable VAR, attaching it to the list
1012 static void parse_acl_env(const char *var
, aclnode
***tail
)
1016 if ((p
= getenv(var
)) != 0) {
1018 parse_acl_line(&q
, tail
);
1023 /* Read the configuration from the config file and environment. */
1024 static void readconfig(void)
1031 parse_acl_env("NOIP_REALBIND_BEFORE", &bind_tail
);
1032 parse_acl_env("NOIP_REALCONNECT_BEFORE", &connect_tail
);
1033 if ((p
= getenv("NOIP_AUTOPORTS")) != 0) {
1035 parse_autoports(&q
);
1038 if ((p
= getenv("NOIP_CONFIG")) == 0)
1039 snprintf(p
= buf
, sizeof(buf
), "%s/.noip", home());
1040 D( fprintf(stderr
, "noip: config file: %s\n", p
); )
1042 if ((fp
= fopen(p
, "r")) == 0) {
1043 D( fprintf(stderr
, "noip: couldn't read config: %s\n",
1047 while (fgets(buf
, sizeof(buf
), fp
)) {
1052 if (!*p
|| *p
== '#') continue;
1053 while (n
&& isspace(UC(buf
[n
- 1]))) n
--;
1058 if (strcmp(cmd
, "socketdir") == 0)
1059 sockdir
= xstrdup(p
);
1060 else if (strcmp(cmd
, "realbind") == 0)
1061 parse_acl_line(&p
, &bind_tail
);
1062 else if (strcmp(cmd
, "realconnect") == 0)
1063 parse_acl_line(&p
, &connect_tail
);
1064 else if (strcmp(cmd
, "autoports") == 0)
1065 parse_autoports(&p
);
1066 else if (strcmp(cmd
, "debug") == 0)
1067 debug
= *p ?
atoi(p
) : 1;
1069 D( fprintf(stderr
, "noip: bad config command %s\n", cmd
); )
1074 parse_acl_env("NOIP_REALBIND", &bind_tail
);
1075 parse_acl_env("NOIP_REALCONNECT", &connect_tail
);
1076 parse_acl_env("NOIP_REALBIND_AFTER", &bind_tail
);
1077 parse_acl_env("NOIP_REALCONNECT_AFTER", &connect_tail
);
1080 if (!sockdir
) sockdir
= getenv("NOIP_SOCKETDIR");
1082 snprintf(buf
, sizeof(buf
), "%s/noip-%s", tmpdir(), user());
1083 sockdir
= xstrdup(buf
);
1085 D( fprintf(stderr
, "noip: socketdir: %s\n", sockdir
);
1086 fprintf(stderr
, "noip: autoports: %u-%u\n",
1087 minautoport
, maxautoport
);
1088 fprintf(stderr
, "noip: realbind acl:\n");
1089 dump_acl(bind_real
);
1090 fprintf(stderr
, "noip: realconnect acl:\n");
1091 dump_acl(connect_real
); )
1094 /*----- Overridden system calls -------------------------------------------*/
1096 int socket(int pf
, int ty
, int proto
)
1100 if (!family_known_p(pf
)) {
1101 errno
= EAFNOSUPPORT
;
1110 return (real_socket(pf
, ty
, proto
));
1114 int socketpair(int pf
, int ty
, int proto
, int *sk
)
1116 if (pf
== PF_INET
) {
1120 return (real_socketpair(pf
, ty
, proto
, sk
));
1123 int bind(int sk
, const struct sockaddr
*sa
, socklen_t len
)
1125 struct sockaddr_un sun
;
1127 if (family_known_p(sa
->sa_family
)) {
1129 if (acl_allows_p(bind_real
, sa
)) {
1130 if (fixup_real_ip_socket(sk
, sa
->sa_family
))
1133 encode_inet_addr(&sun
, sa
, WANT_FRESH
);
1135 len
= SUN_LEN(&sun
);
1139 return (real_bind(sk
, sa
, len
));
1142 int connect(int sk
, const struct sockaddr
*sa
, socklen_t len
)
1144 struct sockaddr_un sun
;
1147 if (!family_known_p(sa
->sa_family
))
1148 rc
= real_connect(sk
, sa
, len
);
1151 do_implicit_bind(sk
, &sa
, &len
, &sun
);
1153 rc
= real_connect(sk
, sa
, len
);
1156 case ENOENT
: errno
= ECONNREFUSED
; break;
1163 ssize_t
sendto(int sk
, const void *buf
, size_t len
, int flags
,
1164 const struct sockaddr
*to
, socklen_t tolen
)
1166 struct sockaddr_un sun
;
1168 if (to
&& to
->sa_family
== AF_INET
) {
1170 do_implicit_bind(sk
, &to
, &tolen
, &sun
);
1173 return (real_sendto(sk
, buf
, len
, flags
, to
, tolen
));
1176 ssize_t
recvfrom(int sk
, void *buf
, size_t len
, int flags
,
1177 struct sockaddr
*from
, socklen_t
*fromlen
)
1180 socklen_t mylen
= sizeof(sabuf
);
1184 return real_recvfrom(sk
, buf
, len
, flags
, 0, 0);
1186 n
= real_recvfrom(sk
, buf
, len
, flags
, SA(sabuf
), &mylen
);
1189 return_fake_name(SA(sabuf
), mylen
, from
, fromlen
);
1194 ssize_t
sendmsg(int sk
, const struct msghdr
*msg
, int flags
)
1196 struct sockaddr_un sun
;
1197 const struct sockaddr
*sa
;
1198 struct msghdr mymsg
;
1200 if (msg
->msg_name
&& SA(msg
->msg_name
)->sa_family
== AF_INET
) {
1202 sa
= SA(msg
->msg_name
);
1204 do_implicit_bind(sk
, &sa
, &mymsg
.msg_namelen
, &sun
);
1205 mymsg
.msg_name
= SA(sa
);
1209 return (real_sendmsg(sk
, msg
, flags
));
1212 ssize_t
recvmsg(int sk
, struct msghdr
*msg
, int flags
)
1215 struct sockaddr
*sa
;
1220 return (real_recvmsg(sk
, msg
, flags
));
1222 sa
= SA(msg
->msg_name
);
1223 len
= msg
->msg_namelen
;
1224 msg
->msg_name
= sabuf
;
1225 msg
->msg_namelen
= sizeof(sabuf
);
1226 n
= real_recvmsg(sk
, msg
, flags
);
1229 return_fake_name(SA(sabuf
), msg
->msg_namelen
, sa
, &len
);
1231 msg
->msg_namelen
= len
;
1236 int accept(int sk
, struct sockaddr
*sa
, socklen_t
*len
)
1239 socklen_t mylen
= sizeof(sabuf
);
1240 int nsk
= real_accept(sk
, SA(sabuf
), &mylen
);
1244 return_fake_name(SA(sabuf
), mylen
, sa
, len
);
1248 int getsockname(int sk
, struct sockaddr
*sa
, socklen_t
*len
)
1252 socklen_t mylen
= sizeof(sabuf
);
1253 if (real_getsockname(sk
, SA(sabuf
), &mylen
))
1255 return_fake_name(SA(sabuf
), mylen
, sa
, len
);
1260 int getpeername(int sk
, struct sockaddr
*sa
, socklen_t
*len
)
1264 socklen_t mylen
= sizeof(sabuf
);
1265 if (real_getpeername(sk
, SA(sabuf
), &mylen
))
1267 return_fake_name(SA(sabuf
), mylen
, sa
, len
);
1272 int getsockopt(int sk
, int lev
, int opt
, void *p
, socklen_t
*len
)
1282 return (real_getsockopt(sk
, lev
, opt
, p
, len
));
1285 int setsockopt(int sk
, int lev
, int opt
, const void *p
, socklen_t len
)
1294 case SO_BINDTODEVICE
:
1295 case SO_ATTACH_FILTER
:
1296 case SO_DETACH_FILTER
:
1299 return (real_setsockopt(sk
, lev
, opt
, p
, len
));
1302 /*----- Initialization ----------------------------------------------------*/
1304 /* Clean up the socket directory, deleting stale sockets. */
1305 static void cleanup_sockdir(void)
1310 struct sockaddr_un sun
;
1313 if ((dir
= opendir(sockdir
)) == 0) return;
1314 sun
.sun_family
= AF_UNIX
;
1315 while ((d
= readdir(dir
)) != 0) {
1316 if (d
->d_name
[0] == '.') continue;
1317 snprintf(sun
.sun_path
, sizeof(sun
.sun_path
),
1318 "%s/%s", sockdir
, d
->d_name
);
1319 if (decode_inet_addr(&addr
.sa
, 0, &sun
, SUN_LEN(&sun
)) ||
1320 stat(sun
.sun_path
, &st
) ||
1321 !S_ISSOCK(st
.st_mode
)) {
1322 D( fprintf(stderr
, "noip: ignoring unknown socketdir entry `%s'\n",
1326 if (unix_socket_status(&sun
, 0) == STALE
) {
1327 D( fprintf(stderr
, "noip: clearing away stale socket %s\n",
1329 unlink(sun
.sun_path
);
1335 /* Find the addresses attached to local network interfaces, and remember them
1338 static void get_local_ipaddrs(void)
1340 struct ifaddrs
*ifa_head
, *ifa
;
1344 if (getifaddrs(&ifa_head
)) { perror("getifaddrs"); return; }
1345 for (n_local_ipaddrs
= 0, ifa
= ifa_head
;
1346 n_local_ipaddrs
< MAX_LOCAL_IPADDRS
&& ifa
;
1347 ifa
= ifa
->ifa_next
) {
1348 if (!ifa
->ifa_addr
|| !family_known_p(ifa
->ifa_addr
->sa_family
))
1350 ipaddr_from_sockaddr(&a
, ifa
->ifa_addr
);
1351 D({ char buf
[ADDRBUFSZ
];
1352 fprintf(stderr
, "noip: local addr %s = %s", ifa
->ifa_name
,
1353 inet_ntop(ifa
->ifa_addr
->sa_family
, &a
,
1354 buf
, sizeof(buf
))); })
1355 for (i
= 0; i
< n_local_ipaddrs
; i
++) {
1356 if (ifa
->ifa_addr
->sa_family
== local_ipaddrs
[i
].af
&&
1357 ipaddr_equal_p(local_ipaddrs
[i
].af
, &a
, &local_ipaddrs
[i
].addr
)) {
1358 D( fprintf(stderr
, " (duplicate)\n"); )
1362 D( fprintf(stderr
, "\n"); )
1363 local_ipaddrs
[n_local_ipaddrs
].af
= ifa
->ifa_addr
->sa_family
;
1364 local_ipaddrs
[n_local_ipaddrs
].addr
= a
;
1368 freeifaddrs(ifa_head
);
1371 /* Print the given message to standard error. Avoids stdio. */
1372 static void printerr(const char *p
)
1373 { if (write(STDERR_FILENO
, p
, strlen(p
))) ; }
1375 /* Create the socket directory, being careful about permissions. */
1376 static void create_sockdir(void)
1380 if (stat(sockdir
, &st
)) {
1381 if (errno
== ENOENT
) {
1382 if (mkdir(sockdir
, 0700)) {
1383 perror("noip: creating socketdir");
1386 if (!stat(sockdir
, &st
))
1389 perror("noip: checking socketdir");
1393 if (!S_ISDIR(st
.st_mode
)) {
1394 printerr("noip: bad socketdir: not a directory\n");
1397 if (st
.st_uid
!= uid
) {
1398 printerr("noip: bad socketdir: not owner\n");
1401 if (st
.st_mode
& 077) {
1402 printerr("noip: bad socketdir: not private\n");
1407 /* Initialization function. */
1408 static void setup(void) __attribute__((constructor
));
1409 static void setup(void)
1416 if ((p
= getenv("NOIP_DEBUG")) && atoi(p
))
1418 get_local_ipaddrs();
1425 /*----- That's all, folks -------------------------------------------------*/