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 /* Unix socket status values. */
63 #define UNUSED 0u /* No sign of anyone using it */
64 #define STALE 1u /* Socket exists, but is abandoned */
65 #define USED 16u /* Socket is in active use */
66 #define LISTEN 2u /* Socket has an active listener */
68 enum { DENY
, ALLOW
}; /* ACL verdicts */
70 static int address_families
[] = { AF_INET
, AF_INET6
, -1 };
74 /* Address representations. */
75 typedef union ipaddr
{
80 /* Convenient socket address hacking. */
81 typedef union address
{
83 struct sockaddr_in sin
;
84 struct sockaddr_in6 sin6
;
87 /* Access control list nodes */
88 typedef struct aclnode
{
92 ipaddr minaddr
, maxaddr
;
93 unsigned short minport
, maxport
;
96 /* Implicit bind records */
97 typedef struct impbind
{
100 ipaddr minaddr
, maxaddr
, bindaddr
;
102 enum { EXPLICIT
, SAME
};
104 /* A type for an address range */
105 typedef struct addrrange
{
108 struct { int af
; ipaddr min
, max
; } range
;
111 enum { EMPTY
, ANY
, LOCAL
, RANGE
};
113 /* Local address records */
114 typedef struct full_ipaddr
{
118 #define MAX_LOCAL_IPADDRS 64
119 static full_ipaddr local_ipaddrs
[MAX_LOCAL_IPADDRS
];
120 static int n_local_ipaddrs
;
122 /* General configuration */
124 static char *sockdir
= 0;
125 static int debug
= 0;
126 static unsigned minautoport
= 16384, maxautoport
= 65536;
128 /* Access control lists */
129 static aclnode
*bind_real
, **bind_tail
= &bind_real
;
130 static aclnode
*connect_real
, **connect_tail
= &connect_real
;
131 static impbind
*impbinds
, **impbind_tail
= &impbinds
;
133 /*----- Import the real versions of functions -----------------------------*/
135 /* The list of functions to immport. */
137 _(socket, int, (int, int, int)) \
138 _(socketpair, int, (int, int, int, int *)) \
139 _(connect, int, (int, const struct sockaddr *, socklen_t)) \
140 _(bind, int, (int, const struct sockaddr *, socklen_t)) \
141 _(accept, int, (int, struct sockaddr *, socklen_t *)) \
142 _(getsockname, int, (int, struct sockaddr *, socklen_t *)) \
143 _(getpeername, int, (int, struct sockaddr *, socklen_t *)) \
144 _(getsockopt, int, (int, int, int, void *, socklen_t *)) \
145 _(setsockopt, int, (int, int, int, const void *, socklen_t)) \
146 _(sendto, ssize_t, (int, const void *buf, size_t, int, \
147 const struct sockaddr *to, socklen_t tolen)) \
148 _(recvfrom, ssize_t, (int, void *buf, size_t, int, \
149 struct sockaddr *from, socklen_t *fromlen)) \
150 _(sendmsg, ssize_t, (int, const struct msghdr *, int)) \
151 _(recvmsg, ssize_t, (int, struct msghdr *, int)) \
152 _(ioctl, int, (int, unsigned long, ...))
154 /* Function pointers to set up. */
155 #define DECL(imp, ret, args) static ret (*real_##imp) args;
159 /* Import the system calls. */
160 static void import(void)
162 #define IMPORT(imp, ret, args) \
163 real_##imp = (ret (*)args)dlsym(RTLD_NEXT, #imp);
168 /*----- Utilities ---------------------------------------------------------*/
170 /* Socket address casts */
171 #define SA(sa) ((struct sockaddr *)(sa))
172 #define SIN(sa) ((struct sockaddr_in *)(sa))
173 #define SIN6(sa) ((struct sockaddr_in6 *)(sa))
174 #define SUN(sa) ((struct sockaddr_un *)(sa))
177 #define UC(ch) ((unsigned char)(ch))
179 /* Memory allocation */
180 #define NEW(x) ((x) = xmalloc(sizeof(*x)))
181 #define NEWV(x, n) ((x) = xmalloc(sizeof(*x) * (n)))
185 # define D(body) { if (debug) { body } }
186 # define Dpid pid_t pid = debug ? getpid() : -1
192 /* Preservation of error status */
193 #define PRESERVING_ERRNO(body) do { \
194 int _err = errno; { body } errno = _err; \
197 /* Allocate N bytes of memory; abort on failure. */
198 static void *xmalloc(size_t n
)
202 if ((p
= malloc(n
)) == 0) { perror("malloc"); exit(127); }
206 /* Allocate a copy of the null-terminated string P; abort on failure. */
207 static char *xstrdup(const char *p
)
209 size_t n
= strlen(p
) + 1;
210 char *q
= xmalloc(n
);
215 /*----- Address-type hacking ----------------------------------------------*/
217 /* If M is a simple mask, i.e., consists of a sequence of zero bits followed
218 * by a sequence of one bits, then return the length of the latter sequence
219 * (which may be zero); otherwise return -1.
221 static int simple_mask_length(unsigned long m
)
225 while (m
& 1) { n
++; m
>>= 1; }
229 /* Answer whether AF is an interesting address family. */
230 static int family_known_p(int af
)
241 /* Return the socket address length for address family AF. */
242 static socklen_t
family_socklen(int af
)
245 case AF_INET
: return (sizeof(struct sockaddr_in
));
246 case AF_INET6
: return (sizeof(struct sockaddr_in6
));
251 /* Return the width of addresses of kind AF. */
252 static int address_width(int af
)
255 case AF_INET
: return 32;
256 case AF_INET6
: return 128;
261 /* If addresses A and B share a common prefix then return its length;
262 * otherwise return -1.
264 static int common_prefix_length(int af
, const ipaddr
*a
, const ipaddr
*b
)
268 unsigned long aa
= ntohl(a
->v4
.s_addr
), bb
= ntohl(b
->v4
.s_addr
);
269 unsigned long m
= aa
^bb
;
270 if ((aa
&m
) == 0 && (bb
&m
) == m
) return (32 - simple_mask_length(m
));
274 const uint8_t *aa
= a
->v6
.s6_addr
, *bb
= b
->v6
.s6_addr
;
279 for (i
= 0; i
< 16 && aa
[i
] == bb
[i
]; i
++);
283 if ((aa
[i
]&m
) != 0 || (bb
[i
]&m
) != m
) return (-1);
284 n
+= 8 - simple_mask_length(m
);
285 for (i
++; i
< 16; i
++)
286 if (aa
[i
] || bb
[i
] != 0xff) return (-1);
295 /* Extract the port number (in host byte-order) from SA. */
296 static int port_from_sockaddr(const struct sockaddr
*sa
)
298 switch (sa
->sa_family
) {
299 case AF_INET
: return (ntohs(SIN(sa
)->sin_port
));
300 case AF_INET6
: return (ntohs(SIN6(sa
)->sin6_port
));
305 /* Store the port number PORT (in host byte-order) in SA. */
306 static void port_to_sockaddr(struct sockaddr
*sa
, int port
)
308 switch (sa
->sa_family
) {
309 case AF_INET
: SIN(sa
)->sin_port
= htons(port
); break;
310 case AF_INET6
: SIN6(sa
)->sin6_port
= htons(port
); break;
315 /* Extract the address part from SA and store it in A. */
316 static void ipaddr_from_sockaddr(ipaddr
*a
, const struct sockaddr
*sa
)
318 switch (sa
->sa_family
) {
319 case AF_INET
: a
->v4
= SIN(sa
)->sin_addr
; break;
320 case AF_INET6
: a
->v6
= SIN6(sa
)->sin6_addr
; break;
325 /* Store the address A in SA. */
326 static void ipaddr_to_sockaddr(struct sockaddr
*sa
, const ipaddr
*a
)
328 switch (sa
->sa_family
) {
330 SIN(sa
)->sin_addr
= a
->v4
;
333 SIN6(sa
)->sin6_addr
= a
->v6
;
334 SIN6(sa
)->sin6_scope_id
= 0;
335 SIN6(sa
)->sin6_flowinfo
= 0;
342 /* Copy a whole socket address about. */
343 static void copy_sockaddr(struct sockaddr
*sa_dst
,
344 const struct sockaddr
*sa_src
)
345 { memcpy(sa_dst
, sa_src
, family_socklen(sa_src
->sa_family
)); }
347 /* Convert an AF_INET socket address into the equivalent IPv4-mapped AF_INET6
350 static void map_ipv4_sockaddr(struct sockaddr_in6
*a6
,
351 const struct sockaddr_in
*a4
)
354 in_addr_t a
= ntohl(a4
->sin_addr
.s_addr
);
356 a6
->sin6_family
= AF_INET6
;
357 a6
->sin6_port
= a4
->sin_port
;
358 a6
->sin6_scope_id
= 0;
359 a6
->sin6_flowinfo
= 0;
360 for (i
= 0; i
< 10; i
++) a6
->sin6_addr
.s6_addr
[i
] = 0;
361 for (i
= 10; i
< 12; i
++) a6
->sin6_addr
.s6_addr
[i
] = 0xff;
362 for (i
= 0; i
< 4; i
++) a6
->sin6_addr
.s6_addr
[15 - i
] = (a
>> 8*i
)&0xff;
365 /* Convert an AF_INET6 socket address containing an IPv4-mapped IPv6 address
366 * into the equivalent AF_INET4 address. Return zero on success, or -1 if
367 * the address has the wrong form.
369 static int unmap_ipv4_sockaddr(struct sockaddr_in
*a4
,
370 const struct sockaddr_in6
*a6
)
375 for (i
= 0; i
< 10; i
++) if (a6
->sin6_addr
.s6_addr
[i
] != 0) return (-1);
376 for (i
= 10; i
< 12; i
++) if (a6
->sin6_addr
.s6_addr
[i
] != 0xff) return (-1);
377 for (i
= 0, a
= 0; i
< 4; i
++) a
|= a6
->sin6_addr
.s6_addr
[15 - i
] << 8*i
;
378 a4
->sin_family
= AF_INET
;
379 a4
->sin_port
= a6
->sin6_port
;
380 a4
->sin_addr
.s_addr
= htonl(a
);
384 /* Answer whether two addresses are equal. */
385 static int ipaddr_equal_p(int af
, const ipaddr
*a
, const ipaddr
*b
)
388 case AF_INET
: return (a
->v4
.s_addr
== b
->v4
.s_addr
);
389 case AF_INET6
: return (memcmp(a
->v6
.s6_addr
, b
->v6
.s6_addr
, 16) == 0);
394 /* Answer whether the address part of SA is between A and B (inclusive). We
395 * assume that SA has the correct address family.
397 static int sockaddr_in_range_p(const struct sockaddr
*sa
,
398 const ipaddr
*a
, const ipaddr
*b
)
400 switch (sa
->sa_family
) {
402 unsigned long addr
= ntohl(SIN(sa
)->sin_addr
.s_addr
);
403 return (ntohl(a
->v4
.s_addr
) <= addr
&&
404 addr
<= ntohl(b
->v4
.s_addr
));
407 const uint8_t *ss
= SIN6(sa
)->sin6_addr
.s6_addr
;
408 const uint8_t *aa
= a
->v6
.s6_addr
, *bb
= b
->v6
.s6_addr
;
412 for (i
= 0; h
&& l
&& i
< 16; i
++, ss
++, aa
++, bb
++) {
413 if (*ss
< *aa
|| *bb
< *ss
) return (0);
414 if (*aa
< *ss
) l
= 0;
415 if (*ss
< *bb
) h
= 0;
424 /* Fill in SA with the appropriate wildcard address. */
425 static void wildcard_address(int af
, struct sockaddr
*sa
)
429 struct sockaddr_in
*sin
= SIN(sa
);
430 memset(sin
, 0, sizeof(*sin
));
431 sin
->sin_family
= AF_INET
;
433 sin
->sin_addr
.s_addr
= INADDR_ANY
;
436 struct sockaddr_in6
*sin6
= SIN6(sa
);
437 memset(sin6
, 0, sizeof(*sin6
));
438 sin6
->sin6_family
= AF_INET6
;
440 sin6
->sin6_addr
= in6addr_any
;
441 sin6
->sin6_scope_id
= 0;
442 sin6
->sin6_flowinfo
= 0;
449 /* Mask the address A, forcing all but the top PLEN bits to zero or one
450 * according to HIGHP.
452 static void mask_address(int af
, ipaddr
*a
, int plen
, int highp
)
456 unsigned long addr
= ntohl(a
->v4
.s_addr
);
457 unsigned long mask
= plen ?
~0ul << (32 - plen
) : 0;
459 if (highp
) addr
|= ~mask
;
460 a
->v4
.s_addr
= htonl(addr
& 0xffffffff);
464 unsigned m
= (0xff << (8 - plen
%8)) & 0xff;
465 unsigned s
= highp ?
0xff : 0;
467 a
->v6
.s6_addr
[i
] = (a
->v6
.s6_addr
[i
] & m
) | (s
& ~m
);
470 for (; i
< 16; i
++) a
->v6
.s6_addr
[i
] = s
;
477 /* Write a presentation form of SA to BUF, a buffer of length SZ. LEN is the
478 * address length; if it's zero, look it up based on the address family.
479 * Return a pointer to the string (which might, in an emergency, be a static
480 * string rather than your buffer).
482 static char *present_sockaddr(const struct sockaddr
*sa
, socklen_t len
,
483 char *buf
, size_t sz
)
485 #define WANT(n_) do { if (sz < (n_)) goto nospace; } while (0)
486 #define PUTC(c_) do { *buf++ = (c_); sz--; } while (0)
488 if (!sa
) return "<null-address>";
489 if (!sz
) return "<no-space-in-buffer>";
490 if (!len
) len
= family_socklen(sa
->sa_family
);
492 switch (sa
->sa_family
) {
494 struct sockaddr_un
*sun
= SUN(sa
);
495 char *p
= sun
->sun_path
;
496 size_t n
= len
- offsetof(struct sockaddr_un
, sun_path
);
504 case 0: WANT(2); PUTC('\\'); PUTC('0'); break;
505 case '\a': WANT(2); PUTC('\\'); PUTC('a'); break;
506 case '\n': WANT(2); PUTC('\\'); PUTC('n'); break;
507 case '\r': WANT(2); PUTC('\\'); PUTC('r'); break;
508 case '\t': WANT(2); PUTC('\\'); PUTC('t'); break;
509 case '\v': WANT(2); PUTC('\\'); PUTC('v'); break;
510 case '\\': WANT(2); PUTC('\\'); PUTC('\\'); break;
512 if (*p
> ' ' && *p
<= '~')
513 { WANT(1); PUTC(*p
); }
515 WANT(4); PUTC('\\'); PUTC('x');
516 PUTC((*p
>> 4)&0xf); PUTC((*p
>> 0)&0xf);
523 if (*p
!= '/') { WANT(2); PUTC('.'); PUTC('/'); }
524 while (n
&& *p
) { WANT(1); PUTC(*p
); p
++; n
--; }
528 case AF_INET
: case AF_INET6
: {
529 char addrbuf
[NI_MAXHOST
], portbuf
[NI_MAXSERV
];
530 int err
= getnameinfo(sa
, len
,
531 addrbuf
, sizeof(addrbuf
),
532 portbuf
, sizeof(portbuf
),
533 NI_NUMERICHOST
| NI_NUMERICSERV
);
535 snprintf(buf
, sz
, strchr(addrbuf
, ':') ?
"[%s]:%s" : "%s:%s",
539 snprintf(buf
, sz
, "<unknown-address-family %d>", sa
->sa_family
);
549 /* Guess the family of a textual socket address. */
550 static int guess_address_family(const char *p
)
551 { return (strchr(p
, ':') ? AF_INET6
: AF_INET
); }
553 /* Parse a socket address P and write the result to SA. */
554 static int parse_sockaddr(struct sockaddr
*sa
, const char *p
)
558 struct addrinfo
*ai
, ai_hint
= { 0 };
560 if (strlen(p
) >= sizeof(buf
) - 1) return (-1);
561 strcpy(buf
, p
); p
= buf
;
563 if ((q
= strchr(p
, ':')) == 0) return (-1);
567 if ((q
= strchr(p
, ']')) == 0) return (-1);
569 if (*q
!= ':') return (-1);
573 ai_hint
.ai_family
= AF_UNSPEC
;
574 ai_hint
.ai_socktype
= SOCK_DGRAM
;
575 ai_hint
.ai_flags
= AI_NUMERICHOST
| AI_NUMERICSERV
;
576 if (getaddrinfo(p
, q
, &ai_hint
, &ai
)) return (-1);
577 memcpy(sa
, ai
->ai_addr
, ai
->ai_addrlen
);
582 /*----- Access control lists ----------------------------------------------*/
586 static void dump_addrrange(int af
, const ipaddr
*min
, const ipaddr
*max
)
592 plen
= common_prefix_length(af
, min
, max
);
593 p
= inet_ntop(af
, min
, buf
, sizeof(buf
));
594 fprintf(stderr
, strchr(p
, ':') ?
"[%s]" : "%s", p
);
596 p
= inet_ntop(af
, &max
, buf
, sizeof(buf
));
597 fprintf(stderr
, strchr(p
, ':') ?
"-[%s]" : "-%s", p
);
598 } else if (plen
< address_width(af
))
599 fprintf(stderr
, "/%d", plen
);
602 /* Write to standard error a description of the ACL node A. */
603 static void dump_aclnode(const aclnode
*a
)
605 fprintf(stderr
, "noip(%d): %c ", getpid(), a
->act ?
'+' : '-');
606 dump_addrrange(a
->af
, &a
->minaddr
, &a
->maxaddr
);
607 if (a
->minport
!= 0 || a
->maxport
!= 0xffff) {
608 fprintf(stderr
, ":%u", (unsigned)a
->minport
);
609 if (a
->minport
!= a
->maxport
)
610 fprintf(stderr
, "-%u", (unsigned)a
->maxport
);
615 static void dump_acl(const aclnode
*a
)
619 for (; a
; a
= a
->next
) {
623 fprintf(stderr
, "noip(%d): [default policy: %s]\n", getpid(),
624 act
== ALLOW ?
"DENY" : "ALLOW");
629 /* Returns nonzero if the ACL A allows the socket address SA. */
630 static int acl_allows_p(const aclnode
*a
, const struct sockaddr
*sa
)
632 unsigned short port
= port_from_sockaddr(sa
);
636 D({ char buf
[ADDRBUFSZ
];
637 fprintf(stderr
, "noip(%d): check %s\n", pid
,
638 present_sockaddr(sa
, 0, buf
, sizeof(buf
))); })
639 for (; a
; a
= a
->next
) {
640 D( dump_aclnode(a
); )
641 if (a
->af
== sa
->sa_family
&&
642 sockaddr_in_range_p(sa
, &a
->minaddr
, &a
->maxaddr
) &&
643 a
->minport
<= port
&& port
<= a
->maxport
) {
644 D( fprintf(stderr
, "noip(%d): aha! %s\n", pid
,
645 a
->act ?
"ALLOW" : "DENY"); )
650 D( fprintf(stderr
, "noip(%d): nothing found: %s\n", pid
,
651 act ?
"DENY" : "ALLOW"); )
655 /*----- Socket address conversion -----------------------------------------*/
657 /* Return a uniformly distributed integer between MIN and MAX inclusive. */
658 static unsigned randrange(unsigned min
, unsigned max
)
662 /* It's so nice not to have to care about the quality of the generator
666 for (mask
= 1; mask
< max
; mask
= (mask
<< 1) | 1)
668 do i
= rand() & mask
; while (i
> max
);
672 /* Return the status of Unix-domain socket address SUN. Returns: UNUSED if
673 * the socket doesn't exist; USED if the path refers to an active socket, or
674 * isn't really a socket at all, or we can't tell without a careful search
675 * and QUICKP is set; or STALE if the file refers to a socket which isn't
676 * being used any more.
678 static int unix_socket_status(struct sockaddr_un
*sun
, int quickp
)
687 /* If we can't find the socket node, then it's definitely not in use. If
688 * we get some other error, then this socket is weird.
690 if (stat(sun
->sun_path
, &st
))
691 return (errno
== ENOENT ? UNUSED
: USED
);
693 /* If it's not a socket, then something weird is going on. If we're just
694 * probing quickly to find a spare port, then existence is sufficient to
697 if (!S_ISSOCK(st
.st_mode
) || quickp
)
700 /* The socket's definitely there, but is anyone actually still holding it
701 * open? The only way I know to discover this is to trundle through
702 * `/proc/net/unix'. If there's no entry, then the socket must be stale.
705 if ((fp
= fopen("/proc/net/unix", "r")) == 0)
707 if (!fgets(buf
, sizeof(buf
), fp
)) goto done
; /* skip header */
708 len
= strlen(sun
->sun_path
);
710 while (fgets(buf
, sizeof(buf
), fp
)) {
712 if (n
>= len
+ 2 && buf
[n
- len
- 2] == ' ' && buf
[n
- 1] == '\n' &&
713 memcmp(buf
+ n
- len
- 1, sun
->sun_path
, len
) == 0) {
715 if (sscanf(buf
, "%*s %*x %*x %lx", &f
) < 0 || (f
&0x00010000))
729 /* Encode SA as a Unix-domain address SUN, and return whether it's currently
732 static int encode_single_inet_addr(const struct sockaddr
*sa
,
733 struct sockaddr_un
*sun
,
739 snprintf(sun
->sun_path
, sizeof(sun
->sun_path
), "%s/%s", sockdir
,
740 present_sockaddr(sa
, 0, buf
, sizeof(buf
)));
741 rc
= unix_socket_status(sun
, quickp
);
742 if (rc
== STALE
) unlink(sun
->sun_path
);
746 /* Convert the IP address SA to a Unix-domain address SUN. Fail if the
747 * address seems already taken. If DESPARATEP then try cleaning up stale old
750 static int encode_unused_inet_addr(struct sockaddr
*sa
,
751 struct sockaddr_un
*sun
,
754 address waddr
, maddr
;
755 struct sockaddr_un wsun
;
756 int port
= port_from_sockaddr(sa
);
758 /* First, look for an exact match. Only look quickly unless we're
759 * desperate. If the socket is in use, we fail here. (This could get
760 * racy. Let's not worry about that for now.)
762 if (encode_single_inet_addr(sa
, sun
, !desperatep
)&USED
)
765 /* Next, check the corresponding wildcard address, so as to avoid
766 * inadvertant collisions with listeners. Do this in the same way.
768 wildcard_address(sa
->sa_family
, &waddr
.sa
);
769 port_to_sockaddr(&waddr
.sa
, port
);
770 if (encode_single_inet_addr(&waddr
.sa
, &wsun
, !desperatep
)&USED
)
773 /* We're not done yet. If this is an IPv4 address, then /also/ check (a)
774 * the v6-mapped version, (b) the v6-mapped v4 wildcard, /and/ (c) the v6
777 if (sa
->sa_family
== AF_INET
) {
778 map_ipv4_sockaddr(&maddr
.sin6
, SIN(&sa
));
779 if (encode_single_inet_addr(&maddr
.sa
, &wsun
, !desperatep
)&USED
)
782 map_ipv4_sockaddr(&maddr
.sin6
, &waddr
.sin
);
783 if (encode_single_inet_addr(&maddr
.sa
, &wsun
, !desperatep
)&USED
)
786 wildcard_address(AF_INET6
, &waddr
.sa
);
787 port_to_sockaddr(&waddr
.sa
, port
);
788 if (encode_single_inet_addr(&waddr
.sa
, &wsun
, !desperatep
)&USED
)
796 /* Encode the Internet address SA as a Unix-domain address SUN. If the flag
797 * `ENCF_FRESH' is set, and SA's port number is zero, then we pick an
798 * arbitrary local port. Otherwise we pick the port given. There's an
799 * unpleasant hack to find servers bound to local wildcard addresses.
800 * Returns zero on success; -1 on failure.
802 #define ENCF_FRESH 1u
803 static int encode_inet_addr(struct sockaddr_un
*sun
,
804 const struct sockaddr
*sa
,
810 struct sockaddr_in6 sin6
;
811 int port
= port_from_sockaddr(sa
);
815 D( fprintf(stderr
, "noip(%d): encode %s (%s)", getpid(),
816 present_sockaddr(sa
, 0, buf
, sizeof(buf
)),
817 (f
&ENCF_FRESH
) ?
"FRESH" : "EXISTING"); )
819 /* Start making the Unix-domain address. */
820 sun
->sun_family
= AF_UNIX
;
822 if (port
|| !(f
&ENCF_FRESH
)) {
824 /* Try the address as given. If it's in use, or we don't necessarily
825 * want an existing socket, then we're done.
827 rc
= encode_single_inet_addr(sa
, sun
, 0);
828 if ((rc
&USED
) || (f
&ENCF_FRESH
)) goto found
;
830 /* We're looking for a socket which already exists. This is
831 * unfortunately difficult, because we must deal both with wildcards and
832 * v6-mapped IPv4 addresses.
834 * * We've just tried searching for a socket whose name is an exact
835 * match for our remote address. If the remote address is IPv4, then
836 * we should try again with the v6-mapped equivalent.
838 * * Failing that, we try again with the wildcard address for the
839 * appropriate address family.
841 * * Failing /that/, if the remote address is IPv4, then we try
842 * /again/, increasingly desperately, first with the v6-mapped IPv4
843 * wildcard address, and then with the IPv6 wildcard address. This
844 * will cause magic v6-mapping to occur when the connection is
845 * accepted, which we hope won't cause too much trouble.
848 if (sa
->sa_family
== AF_INET
) {
849 map_ipv4_sockaddr(&addr
.sin6
, SIN(sa
));
850 if (encode_single_inet_addr(&addr
.sa
, sun
, 0)&USED
) goto found
;
853 wildcard_address(sa
->sa_family
, &addr
.sa
);
854 port_to_sockaddr(&addr
.sa
, port
);
855 if (encode_single_inet_addr(&addr
.sa
, sun
, 0)&USED
) goto found
;
857 if (sa
->sa_family
== AF_INET
) {
858 map_ipv4_sockaddr(&sin6
, &addr
.sin
);
859 if (encode_single_inet_addr(SA(&sin6
), sun
, 0)&USED
) goto found
;
860 wildcard_address(AF_INET6
, &addr
.sa
);
861 port_to_sockaddr(&addr
.sa
, port
);
862 if (encode_single_inet_addr(&addr
.sa
, sun
, 0)&USED
) goto found
;
865 /* Well, this isn't going to work (unless a miraculous race is lost), but
866 * we might as well try.
868 encode_single_inet_addr(sa
, sun
, 1);
871 /* We want a fresh new socket. */
873 /* Make a copy of the given address, because we're going to mangle it. */
874 copy_sockaddr(&addr
.sa
, sa
);
876 /* Try a few random-ish port numbers to see if any of them is spare. */
877 for (i
= 0; i
< 10; i
++) {
878 port_to_sockaddr(&addr
.sa
, randrange(minautoport
, maxautoport
));
879 if (!encode_unused_inet_addr(&addr
.sa
, sun
, 0)) goto found
;
882 /* Things must be getting tight. Work through all of the autoport range
883 * to see if we can find a spare one. The first time, just do it the
884 * quick way; if that doesn't work, then check harder for stale sockets.
886 for (desperatep
= 0; desperatep
< 2; desperatep
++) {
887 for (i
= minautoport
; i
<= maxautoport
; i
++) {
888 port_to_sockaddr(&addr
.sa
, i
);
889 if (!encode_unused_inet_addr(&addr
.sa
, sun
, 0)) goto found
;
893 /* We failed to find any free ports. */
895 D( fprintf(stderr
, " -- can't resolve\n"); )
901 D( fprintf(stderr
, " -> `%s'\n", sun
->sun_path
); )
905 /* Decode the Unix address SUN to an Internet address SIN. If AF_HINT is
906 * nonzero, an empty address (indicative of an unbound Unix-domain socket) is
907 * translated to a wildcard Internet address of the appropriate family.
908 * Returns zero on success; -1 on failure (e.g., it wasn't one of our
911 static int decode_inet_addr(struct sockaddr
*sa
, int af_hint
,
912 const struct sockaddr_un
*sun
,
916 size_t n
= strlen(sockdir
), nn
;
919 if (!sa
) sa
= &addr
.sa
;
920 if (sun
->sun_family
!= AF_UNIX
) return (-1);
921 if (len
> sizeof(*sun
)) return (-1);
922 ((char *)sun
)[len
] = 0;
923 nn
= strlen(sun
->sun_path
);
924 D( fprintf(stderr
, "noip(%d): decode `%s'", getpid(), sun
->sun_path
); )
925 if (af_hint
&& !sun
->sun_path
[0]) {
926 wildcard_address(af_hint
, sa
);
927 D( fprintf(stderr
, " -- unbound socket\n"); )
930 if (nn
< n
+ 1 || nn
- n
>= sizeof(buf
) || sun
->sun_path
[n
] != '/' ||
931 memcmp(sun
->sun_path
, sockdir
, n
) != 0) {
932 D( fprintf(stderr
, " -- not one of ours\n"); )
935 if (parse_sockaddr(sa
, sun
->sun_path
+ n
+ 1)) return (-1);
936 D( fprintf(stderr
, " -> %s\n",
937 present_sockaddr(sa
, 0, buf
, sizeof(buf
))); )
941 /* SK is (or at least might be) a Unix-domain socket we created when an
942 * Internet socket was asked for. We've decided it should be an Internet
943 * socket after all, with family AF_HINT, so convert it. If TMP is not null,
944 * then don't replace the existing descriptor: store the new socket in *TMP
947 static int fixup_real_ip_socket(int sk
, int af_hint
, int *tmp
)
952 struct sockaddr_un sun
;
965 _(LINGER, struct linger) \
968 _(RCVTIMEO, struct timeval) \
969 _(SNDTIMEO, struct timeval)
972 if (real_getsockname(sk
, SA(&sun
), &len
))
974 if (decode_inet_addr(&addr
.sa
, af_hint
, &sun
, len
))
975 return (0); /* Not one of ours */
977 if (real_getsockopt(sk
, SOL_SOCKET
, SO_TYPE
, &type
, &len
) < 0 ||
978 (nsk
= real_socket(addr
.sa
.sa_family
, type
, 0)) < 0)
980 #define FIX(opt, ty) do { \
983 if (real_getsockopt(sk, SOL_SOCKET, SO_##opt, &ov_, &len) < 0 || \
984 real_setsockopt(nsk, SOL_SOCKET, SO_##opt, &ov_, len)) { \
994 if ((f
= fcntl(sk
, F_GETFL
)) < 0 ||
995 (fd
= fcntl(sk
, F_GETFD
)) < 0 ||
996 fcntl(nsk
, F_SETFL
, f
) < 0 ||
1001 unlink(sun
.sun_path
);
1003 if (fcntl(sk
, F_SETFD
, fd
) < 0) {
1004 perror("noip: fixup_real_ip_socket F_SETFD");
1011 /* We found the real address SA, with length LEN; if it's a Unix-domain
1012 * address corresponding to a fake socket, convert it to cover up the
1013 * deception. Whatever happens, put the result at FAKE and store its length
1016 #define FNF_V6MAPPED 1u
1017 static void return_fake_name(struct sockaddr
*sa
, socklen_t len
,
1018 struct sockaddr
*fake
, socklen_t
*fakelen
,
1022 struct sockaddr_in6 sin6
;
1025 if (sa
->sa_family
== AF_UNIX
&&
1026 !decode_inet_addr(&addr
.sa
, 0, SUN(sa
), len
)) {
1027 if (addr
.sa
.sa_family
!= AF_INET
|| !(f
&FNF_V6MAPPED
)) {
1029 len
= family_socklen(addr
.sa
.sa_family
);
1031 map_ipv4_sockaddr(&sin6
, &addr
.sin
);
1033 len
= family_socklen(AF_INET6
);
1037 if (len
> *fakelen
) len
= *fakelen
;
1038 if (len
> 0) memcpy(fake
, sa
, len
);
1042 /* Variant of `return_fake_name' above, specifically handling the weirdness
1043 * of remote v6-mapped IPv4 addresses. If SK's fake local address is IPv6,
1044 * and the remote address is IPv4, then return a v6-mapped version of the
1047 static void return_fake_peer(int sk
, struct sockaddr
*sa
, socklen_t len
,
1048 struct sockaddr
*fake
, socklen_t
*fakelen
)
1051 socklen_t mylen
= sizeof(sabuf
);
1057 rc
= real_getsockname(sk
, SA(sabuf
), &mylen
);
1058 if (!rc
&& sa
->sa_family
== AF_UNIX
&&
1059 !decode_inet_addr(&addr
.sa
, 0, SUN(sabuf
), mylen
) &&
1060 addr
.sa
.sa_family
== AF_INET6
)
1061 fnf
|= FNF_V6MAPPED
;
1063 return_fake_name(sa
, len
, fake
, fakelen
, fnf
);
1066 /*----- Implicit binding --------------------------------------------------*/
1070 static void dump_impbind(const impbind
*i
)
1072 char buf
[ADDRBUFSZ
];
1074 fprintf(stderr
, "noip(%d): ", getpid());
1075 dump_addrrange(i
->af
, &i
->minaddr
, &i
->maxaddr
);
1077 case SAME
: fprintf(stderr
, " <self>"); break;
1079 fprintf(stderr
, " %s", inet_ntop(i
->af
, &i
->bindaddr
,
1084 fputc('\n', stderr
);
1087 static void dump_impbind_list(void)
1091 for (i
= impbinds
; i
; i
= i
->next
) dump_impbind(i
);
1096 /* The socket SK is about to be used to communicate with the remote address
1097 * SA. Assign it a local address so that getpeername(2) does something
1100 * If the flag `IBF_V6MAPPED' is set then, then SA must be an `AF_INET'
1101 * address; after deciding on the appropriate local address, convert it to be
1102 * an IPv4-mapped IPv6 address before final conversion to a Unix-domain
1103 * socket address and actually binding. Note that this could well mean that
1104 * the socket ends up bound to the v6-mapped v4 wildcard address
1105 * ::ffff:0.0.0.0, which looks very strange but is meaningful.
1107 #define IBF_V6MAPPED 1u
1108 static int do_implicit_bind(int sk
, const struct sockaddr
*sa
, unsigned f
)
1111 struct sockaddr_in6 sin6
;
1112 struct sockaddr_un sun
;
1116 D( fprintf(stderr
, "noip(%d): checking impbind list...\n", pid
); )
1117 for (i
= impbinds
; i
; i
= i
->next
) {
1118 D( dump_impbind(i
); )
1119 if (sa
->sa_family
== i
->af
&&
1120 sockaddr_in_range_p(sa
, &i
->minaddr
, &i
->maxaddr
)) {
1121 D( fprintf(stderr
, "noip(%d): match!\n", pid
); )
1122 addr
.sa
.sa_family
= sa
->sa_family
;
1123 ipaddr_to_sockaddr(&addr
.sa
, &i
->bindaddr
);
1127 D( fprintf(stderr
, "noip(%d): no match; using wildcard\n", pid
); )
1128 wildcard_address(sa
->sa_family
, &addr
.sa
);
1130 if (addr
.sa
.sa_family
!= AF_INET
|| !(f
&IBF_V6MAPPED
)) sa
= &addr
.sa
;
1131 else { map_ipv4_sockaddr(&sin6
, &addr
.sin
); sa
= SA(&sin6
); }
1132 encode_inet_addr(&sun
, sa
, ENCF_FRESH
);
1133 D( fprintf(stderr
, "noip(%d): implicitly binding to %s\n",
1134 pid
, sun
.sun_path
); )
1135 if (real_bind(sk
, SA(&sun
), SUN_LEN(&sun
))) return (-1);
1139 /* The socket SK is about to communicate with the remote address *SA. Ensure
1140 * that the socket has a local address, and adjust *SA to refer to the real
1143 * If we need to translate the remote address, then the Unix-domain endpoint
1144 * address will end in *SUN, and *SA will be adjusted to point to it.
1146 static int fixup_client_socket(int sk
, const struct sockaddr
**sa_r
,
1147 socklen_t
*len_r
, struct sockaddr_un
*sun
)
1149 struct sockaddr_in sin
;
1150 socklen_t mylen
= sizeof(*sun
);
1151 const struct sockaddr
*sa
= *sa_r
;
1154 /* If this isn't a Unix-domain socket then there's nothing to do. */
1155 if (real_getsockname(sk
, SA(sun
), &mylen
) < 0) return (-1);
1156 if (sun
->sun_family
!= AF_UNIX
) return (0);
1157 if (mylen
< sizeof(*sun
)) ((char *)sun
)[mylen
] = 0;
1159 /* If the remote address is v6-mapped IPv4, then unmap it so as to search
1160 * for IPv4 servers. Also remember to v6-map the local address when we
1163 if (sa
->sa_family
== AF_INET6
&& !(unmap_ipv4_sockaddr(&sin
, SIN6(sa
)))) {
1165 ibf
|= IBF_V6MAPPED
;
1168 /* If we're allowed to talk to a real remote endpoint, then fix things up
1169 * as necessary and proceed.
1171 if (acl_allows_p(connect_real
, sa
)) {
1172 if (fixup_real_ip_socket(sk
, (*sa_r
)->sa_family
, 0)) return (-1);
1176 /* Speaking of which, if we don't have a local address, then we should
1179 if (!sun
->sun_path
[0] && do_implicit_bind(sk
, sa
, ibf
)) return (-1);
1181 /* And then come up with a remote address. */
1182 encode_inet_addr(sun
, sa
, 0);
1184 *len_r
= SUN_LEN(sun
);
1188 /*----- Configuration -----------------------------------------------------*/
1190 /* Return the process owner's home directory. */
1191 static char *home(void)
1196 if (getuid() == uid
&&
1197 (p
= getenv("HOME")) != 0)
1199 else if ((pw
= getpwuid(uid
)) != 0)
1200 return (pw
->pw_dir
);
1205 /* Return a good temporary directory to use. */
1206 static char *tmpdir(void)
1210 if ((p
= getenv("TMPDIR")) != 0) return (p
);
1211 else if ((p
= getenv("TMP")) != 0) return (p
);
1212 else return ("/tmp");
1215 /* Return the user's name, or at least something distinctive. */
1216 static char *user(void)
1218 static char buf
[16];
1222 if ((p
= getenv("USER")) != 0) return (p
);
1223 else if ((p
= getenv("LOGNAME")) != 0) return (p
);
1224 else if ((pw
= getpwuid(uid
)) != 0) return (pw
->pw_name
);
1226 snprintf(buf
, sizeof(buf
), "uid-%lu", (unsigned long)uid
);
1231 /* Skip P over space characters. */
1232 #define SKIPSPC do { while (*p && isspace(UC(*p))) p++; } while (0)
1234 /* Set Q to point to the next word following P, null-terminate it, and step P
1236 #define NEXTWORD(q) do { \
1239 while (*p && !isspace(UC(*p))) p++; \
1243 /* Set Q to point to the next dotted-quad address, store the ending delimiter
1244 * in DEL, null-terminate it, and step P past it. */
1245 static void parse_nextaddr(char **pp
, char **qq
, int *del
)
1253 p
+= strcspn(p
, "]");
1258 while (*p
&& (*p
== '.' || isdigit(UC(*p
)))) p
++;
1265 /* Set Q to point to the next decimal number, store the ending delimiter in
1266 * DEL, null-terminate it, and step P past it. */
1267 #define NEXTNUMBER(q, del) do { \
1270 while (*p && isdigit(UC(*p))) p++; \
1275 /* Push the character DEL back so we scan it again, unless it's zero
1277 #define RESCAN(del) do { if (del) *--p = del; } while (0)
1279 /* Evaluate true if P is pointing to the word KW (and not some longer string
1280 * of which KW is a prefix). */
1282 #define KWMATCHP(kw) (strncmp(p, kw, sizeof(kw) - 1) == 0 && \
1283 !isalnum(UC(p[sizeof(kw) - 1])) && \
1284 (p += sizeof(kw) - 1))
1286 /* Parse a port list, starting at *PP. Port lists have the form
1287 * [:LOW[-HIGH]]: if omitted, all ports are included; if HIGH is omitted,
1288 * it's as if HIGH = LOW. Store LOW in *MIN, HIGH in *MAX and set *PP to the
1289 * rest of the string.
1291 static void parse_ports(char **pp
, unsigned short *min
, unsigned short *max
)
1298 { *min
= 0; *max
= 0xffff; }
1301 NEXTNUMBER(q
, del
); *min
= strtoul(q
, 0, 0); RESCAN(del
);
1304 { p
++; NEXTNUMBER(q
, del
); *max
= strtoul(q
, 0, 0); RESCAN(del
); }
1311 /* Parse an address range designator starting at PP and store a
1312 * representation of it in R. An address range designator has the form:
1314 * any | local | ADDR | ADDR - ADDR | ADDR/ADDR | ADDR/INT
1316 static int parse_addrrange(char **pp
, addrrange
*r
)
1324 if (KWMATCHP("any")) r
->type
= ANY
;
1325 else if (KWMATCHP("local")) r
->type
= LOCAL
;
1327 parse_nextaddr(&p
, &q
, &del
);
1328 af
= guess_address_family(q
);
1329 if (inet_pton(af
, q
, &r
->u
.range
.min
) <= 0) goto bad
;
1334 parse_nextaddr(&p
, &q
, &del
);
1335 if (inet_pton(af
, q
, &r
->u
.range
.max
) <= 0) goto bad
;
1337 } else if (*p
== '/') {
1340 n
= strtoul(q
, 0, 0);
1341 r
->u
.range
.max
= r
->u
.range
.min
;
1342 mask_address(af
, &r
->u
.range
.min
, n
, 0);
1343 mask_address(af
, &r
->u
.range
.max
, n
, 1);
1346 r
->u
.range
.max
= r
->u
.range
.min
;
1357 /* Call FUNC on each individual address range in R. */
1358 static void foreach_addrrange(const addrrange
*r
,
1359 void (*func
)(int af
,
1365 ipaddr minaddr
, maxaddr
;
1372 for (i
= 0; address_families
[i
] >= 0; i
++) {
1373 af
= address_families
[i
];
1374 memset(&minaddr
, 0, sizeof(minaddr
));
1375 maxaddr
= minaddr
; mask_address(af
, &maxaddr
, 0, 1);
1376 func(af
, &minaddr
, &maxaddr
, p
);
1380 for (i
= 0; address_families
[i
] >= 0; i
++) {
1381 af
= address_families
[i
];
1382 memset(&minaddr
, 0, sizeof(minaddr
));
1383 maxaddr
= minaddr
; mask_address(af
, &maxaddr
, 0, 1);
1384 func(af
, &minaddr
, &minaddr
, p
);
1385 func(af
, &maxaddr
, &maxaddr
, p
);
1387 for (i
= 0; i
< n_local_ipaddrs
; i
++) {
1388 func(local_ipaddrs
[i
].af
,
1389 &local_ipaddrs
[i
].addr
, &local_ipaddrs
[i
].addr
,
1394 func(r
->u
.range
.af
, &r
->u
.range
.min
, &r
->u
.range
.max
, p
);
1401 struct add_aclnode_ctx
{
1403 unsigned short minport
, maxport
;
1407 static void add_aclnode(int af
, const ipaddr
*min
, const ipaddr
*max
,
1410 struct add_aclnode_ctx
*ctx
= p
;
1416 a
->minaddr
= *min
; a
->maxaddr
= *max
;
1417 a
->minport
= ctx
->minport
; a
->maxport
= ctx
->maxport
;
1418 **ctx
->tail
= a
; *ctx
->tail
= &a
->next
;
1421 /* Parse an ACL line. *PP points to the end of the line; *TAIL points to
1422 * the list tail (i.e., the final link in the list). An ACL entry has the
1423 * form +|- ADDR-RANGE PORTS
1424 * where PORTS is parsed by parse_ports above; an ACL line consists of a
1425 * comma-separated sequence of entries..
1427 static void parse_acl_line(char **pp
, aclnode
***tail
)
1429 struct add_aclnode_ctx ctx
;
1436 if (*p
== '+') ctx
.act
= ALLOW
;
1437 else if (*p
== '-') ctx
.act
= DENY
;
1441 if (parse_addrrange(&p
, &r
)) goto bad
;
1442 parse_ports(&p
, &ctx
.minport
, &ctx
.maxport
);
1443 foreach_addrrange(&r
, add_aclnode
, &ctx
);
1445 if (*p
!= ',') break;
1453 D( fprintf(stderr
, "noip(%d): bad acl spec (ignored)\n", getpid()); )
1457 /* Parse an ACL from an environment variable VAR, attaching it to the list
1460 static void parse_acl_env(const char *var
, aclnode
***tail
)
1464 if ((p
= getenv(var
)) != 0) {
1466 parse_acl_line(&q
, tail
);
1471 struct add_impbind_ctx
{
1476 static void add_impbind(int af
, const ipaddr
*min
, const ipaddr
*max
,
1479 struct add_impbind_ctx
*ctx
= p
;
1482 if (ctx
->af
&& af
!= ctx
->af
) return;
1486 i
->minaddr
= *min
; i
->maxaddr
= *max
;
1488 case EXPLICIT
: i
->bindaddr
= ctx
->addr
;
1492 *impbind_tail
= i
; impbind_tail
= &i
->next
;
1495 /* Parse an implicit-bind line. An implicit-bind entry has the form
1496 * ADDR-RANGE {ADDR | same}
1498 static void parse_impbind_line(char **pp
)
1500 struct add_impbind_ctx ctx
;
1506 if (parse_addrrange(&p
, &r
)) goto bad
;
1508 if (KWMATCHP("same")) {
1513 parse_nextaddr(&p
, &q
, &del
);
1514 ctx
.af
= guess_address_family(q
);
1515 if (inet_pton(ctx
.af
, q
, &ctx
.addr
) < 0) goto bad
;
1518 foreach_addrrange(&r
, add_impbind
, &ctx
);
1520 if (*p
!= ',') break;
1528 D( fprintf(stderr
, "noip(%d): bad implicit-bind spec (ignored)\n",
1533 /* Parse implicit-bind instructions from an environment variable VAR,
1534 * attaching it to the list.
1536 static void parse_impbind_env(const char *var
)
1540 if ((p
= getenv(var
)) != 0) {
1542 parse_impbind_line(&q
);
1547 /* Parse the autoports configuration directive. Syntax is MIN - MAX. */
1548 static void parse_autoports(char **pp
)
1555 NEXTNUMBER(q
, del
); x
= strtoul(q
, 0, 0); RESCAN(del
);
1557 if (*p
!= '-') goto bad
;
1559 NEXTNUMBER(q
, del
); y
= strtoul(q
, 0, 0); RESCAN(del
);
1560 minautoport
= x
; maxautoport
= y
;
1561 SKIPSPC
; if (*p
) goto bad
;
1566 D( fprintf(stderr
, "noip(%d): bad port range (ignored)\n", getpid()); )
1570 /* Read the configuration from the config file and environment. */
1571 static void readconfig(void)
1579 parse_acl_env("NOIP_REALBIND_BEFORE", &bind_tail
);
1580 parse_acl_env("NOIP_REALCONNECT_BEFORE", &connect_tail
);
1581 parse_impbind_env("NOIP_IMPBIND_BEFORE");
1582 if ((p
= getenv("NOIP_AUTOPORTS")) != 0) {
1584 parse_autoports(&q
);
1587 if ((p
= getenv("NOIP_CONFIG")) == 0)
1588 snprintf(p
= buf
, sizeof(buf
), "%s/.noip", home());
1589 D( fprintf(stderr
, "noip(%d): config file: %s\n", pid
, p
); )
1591 if ((fp
= fopen(p
, "r")) == 0) {
1592 D( fprintf(stderr
, "noip(%d): couldn't read config: %s\n",
1593 pid
, strerror(errno
)); )
1596 while (fgets(buf
, sizeof(buf
), fp
)) {
1601 if (!*p
|| *p
== '#') continue;
1602 while (n
&& isspace(UC(buf
[n
- 1]))) n
--;
1607 if (strcmp(cmd
, "socketdir") == 0)
1608 sockdir
= xstrdup(p
);
1609 else if (strcmp(cmd
, "realbind") == 0)
1610 parse_acl_line(&p
, &bind_tail
);
1611 else if (strcmp(cmd
, "realconnect") == 0)
1612 parse_acl_line(&p
, &connect_tail
);
1613 else if (strcmp(cmd
, "impbind") == 0)
1614 parse_impbind_line(&p
);
1615 else if (strcmp(cmd
, "autoports") == 0)
1616 parse_autoports(&p
);
1617 else if (strcmp(cmd
, "debug") == 0)
1618 debug
= *p ?
atoi(p
) : 1;
1620 D( fprintf(stderr
, "noip(%d): bad config command %s\n", pid
, cmd
); )
1625 parse_acl_env("NOIP_REALBIND", &bind_tail
);
1626 parse_acl_env("NOIP_REALCONNECT", &connect_tail
);
1627 parse_impbind_env("NOIP_IMPBIND");
1628 parse_acl_env("NOIP_REALBIND_AFTER", &bind_tail
);
1629 parse_acl_env("NOIP_REALCONNECT_AFTER", &connect_tail
);
1630 parse_impbind_env("NOIP_IMPBIND_AFTER");
1634 if (!sockdir
) sockdir
= getenv("NOIP_SOCKETDIR");
1636 snprintf(buf
, sizeof(buf
), "%s/noip-%s", tmpdir(), user());
1637 sockdir
= xstrdup(buf
);
1639 D( fprintf(stderr
, "noip(%d): socketdir: %s\n", pid
, sockdir
);
1640 fprintf(stderr
, "noip(%d): autoports: %u-%u\n",
1641 pid
, minautoport
, maxautoport
);
1642 fprintf(stderr
, "noip(%d): realbind acl:\n", pid
);
1643 dump_acl(bind_real
);
1644 fprintf(stderr
, "noip(%d): realconnect acl:\n", pid
);
1645 dump_acl(connect_real
);
1646 fprintf(stderr
, "noip(%d): impbind list:\n", pid
);
1647 dump_impbind_list(); )
1650 /*----- Overridden system calls -------------------------------------------*/
1652 static void dump_syserr(long rc
)
1653 { fprintf(stderr
, " => %ld (E%d)\n", rc
, errno
); }
1655 static void dump_sysresult(long rc
)
1657 if (rc
< 0) dump_syserr(rc
);
1658 else fprintf(stderr
, " => %ld\n", rc
);
1661 static void dump_addrresult(long rc
, const struct sockaddr
*sa
,
1664 char addrbuf
[ADDRBUFSZ
];
1666 if (rc
< 0) dump_syserr(rc
);
1668 fprintf(stderr
, " => %ld [%s]\n", rc
,
1669 present_sockaddr(sa
, len
, addrbuf
, sizeof(addrbuf
)));
1673 int socket(int pf
, int ty
, int proto
)
1677 D( fprintf(stderr
, "noip(%d): SOCKET pf=%d, type=%d, proto=%d",
1678 getpid(), pf
, ty
, proto
); )
1682 if (!family_known_p(pf
)) {
1683 D( fprintf(stderr
, " -> unknown; refuse\n"); )
1684 errno
= EAFNOSUPPORT
;
1687 D( fprintf(stderr
, " -> inet; substitute"); )
1695 D( fprintf(stderr
, " -> safe; permit"); )
1698 sk
= real_socket(pf
, ty
, proto
);
1699 D( dump_sysresult(sk
); )
1703 int socketpair(int pf
, int ty
, int proto
, int *sk
)
1707 D( fprintf(stderr
, "noip(%d): SOCKETPAIR pf=%d, type=%d, proto=%d",
1708 getpid(), pf
, ty
, proto
); )
1709 if (!family_known_p(pf
))
1710 D( fprintf(stderr
, " -> unknown; permit"); )
1712 D( fprintf(stderr
, " -> inet; substitute"); )
1716 rc
= real_socketpair(pf
, ty
, proto
, sk
);
1717 D( if (rc
< 0) dump_syserr(rc
);
1718 else fprintf(stderr
, " => %d (%d, %d)\n", rc
, sk
[0], sk
[1]); )
1722 int bind(int sk
, const struct sockaddr
*sa
, socklen_t len
)
1724 struct sockaddr_un sun
;
1728 D({ char buf
[ADDRBUFSZ
];
1729 fprintf(stderr
, "noip(%d): BIND sk=%d, sa[%d]=%s", pid
,
1730 sk
, len
, present_sockaddr(sa
, len
, buf
, sizeof(buf
))); })
1732 if (!family_known_p(sa
->sa_family
))
1733 D( fprintf(stderr
, " -> unknown af; pass through"); )
1735 D( fprintf(stderr
, " -> checking...\n"); )
1737 if (acl_allows_p(bind_real
, sa
)) {
1738 if (fixup_real_ip_socket(sk
, sa
->sa_family
, 0))
1741 encode_inet_addr(&sun
, sa
, ENCF_FRESH
);
1743 len
= SUN_LEN(&sun
);
1746 D( fprintf(stderr
, "noip(%d): BIND ...", pid
); )
1748 rc
= real_bind(sk
, sa
, len
);
1749 D( dump_sysresult(rc
); )
1753 int connect(int sk
, const struct sockaddr
*sa
, socklen_t len
)
1755 struct sockaddr_un sun
;
1759 D({ char buf
[ADDRBUFSZ
];
1760 fprintf(stderr
, "noip(%d): CONNECT sk=%d, sa[%d]=%s", pid
,
1761 sk
, len
, present_sockaddr(sa
, len
, buf
, sizeof(buf
))); })
1763 if (!family_known_p(sa
->sa_family
)) {
1764 D( fprintf(stderr
, " -> unknown af; pass through"); )
1765 rc
= real_connect(sk
, sa
, len
);
1767 D( fprintf(stderr
, " -> checking...\n"); )
1769 fixup_client_socket(sk
, &sa
, &len
, &sun
);
1771 D( fprintf(stderr
, "noip(%d): CONNECT ...", pid
); )
1772 rc
= real_connect(sk
, sa
, len
);
1775 case ENOENT
: errno
= ECONNREFUSED
; break;
1779 D( dump_sysresult(rc
); )
1783 ssize_t
sendto(int sk
, const void *buf
, size_t len
, int flags
,
1784 const struct sockaddr
*to
, socklen_t tolen
)
1786 struct sockaddr_un sun
;
1790 D({ char addrbuf
[ADDRBUFSZ
];
1791 fprintf(stderr
, "noip(%d): SENDTO sk=%d, len=%lu, flags=%d, to[%d]=%s",
1792 pid
, sk
, (unsigned long)len
, flags
, tolen
,
1793 present_sockaddr(to
, tolen
, addrbuf
, sizeof(addrbuf
))); })
1796 D( fprintf(stderr
, " -> null address; leaving"); )
1797 else if (!family_known_p(to
->sa_family
))
1798 D( fprintf(stderr
, " -> unknown af; pass through"); )
1800 D( fprintf(stderr
, " -> checking...\n"); )
1802 fixup_client_socket(sk
, &to
, &tolen
, &sun
);
1804 D( fprintf(stderr
, "noip(%d): SENDTO ...", pid
); )
1806 n
= real_sendto(sk
, buf
, len
, flags
, to
, tolen
);
1807 D( dump_sysresult(n
); )
1811 ssize_t
recvfrom(int sk
, void *buf
, size_t len
, int flags
,
1812 struct sockaddr
*from
, socklen_t
*fromlen
)
1815 socklen_t mylen
= sizeof(sabuf
);
1819 D( fprintf(stderr
, "noip(%d): RECVFROM sk=%d, len=%lu, flags=%d",
1820 pid
, sk
, (unsigned long)len
, flags
); )
1823 D( fprintf(stderr
, " -> null addr; pass through"); )
1824 n
= real_recvfrom(sk
, buf
, len
, flags
, 0, 0);
1826 n
= real_recvfrom(sk
, buf
, len
, flags
, SA(sabuf
), &mylen
);
1828 D( fprintf(stderr
, " -> converting...\n"); )
1830 return_fake_peer(sk
, SA(sabuf
), mylen
, from
, fromlen
);
1832 D( fprintf(stderr
, "noip(%d): ... RECVFROM", pid
); )
1835 D( dump_addrresult(n
, from
, fromlen ?
*fromlen
: 0); )
1839 ssize_t
sendmsg(int sk
, const struct msghdr
*msg
, int flags
)
1841 struct sockaddr_un sun
;
1842 const struct sockaddr
*sa
= SA(msg
->msg_name
);
1843 struct msghdr mymsg
;
1847 D({ char addrbuf
[ADDRBUFSZ
];
1848 fprintf(stderr
, "noip(%d): SENDMSG sk=%d, "
1849 "msg_flags=%d, msg_name[%d]=%s, ...",
1850 pid
, sk
, msg
->msg_flags
, msg
->msg_namelen
,
1851 present_sockaddr(sa
, msg
->msg_namelen
,
1852 addrbuf
, sizeof(addrbuf
))); })
1855 D( fprintf(stderr
, " -> null address; leaving"); )
1856 else if (!family_known_p(sa
->sa_family
))
1857 D( fprintf(stderr
, " -> unknown af; pass through"); )
1859 D( fprintf(stderr
, " -> checking...\n"); )
1862 fixup_client_socket(sk
, &sa
, &mymsg
.msg_namelen
, &sun
);
1863 mymsg
.msg_name
= SA(sa
);
1866 D( fprintf(stderr
, "noip(%d): SENDMSG ...", pid
); )
1868 n
= real_sendmsg(sk
, msg
, flags
);
1869 D( dump_sysresult(n
); )
1873 ssize_t
recvmsg(int sk
, struct msghdr
*msg
, int flags
)
1876 struct sockaddr
*sa
= SA(msg
->msg_name
);
1877 socklen_t len
= msg
->msg_namelen
;
1881 D( fprintf(stderr
, "noip(%d): RECVMSG sk=%d msg_flags=%d, ...",
1882 pid
, sk
, msg
->msg_flags
); )
1884 if (!msg
->msg_name
) {
1885 D( fprintf(stderr
, " -> null addr; pass through"); )
1886 return (real_recvmsg(sk
, msg
, flags
));
1888 msg
->msg_name
= sabuf
;
1889 msg
->msg_namelen
= sizeof(sabuf
);
1890 n
= real_recvmsg(sk
, msg
, flags
);
1892 D( fprintf(stderr
, " -> converting...\n"); )
1894 return_fake_peer(sk
, SA(sabuf
), msg
->msg_namelen
, sa
, &len
);
1897 D( fprintf(stderr
, "noip(%d): ... RECVMSG", pid
); )
1899 msg
->msg_namelen
= len
;
1901 D( dump_addrresult(n
, sa
, len
); )
1905 int accept(int sk
, struct sockaddr
*sa
, socklen_t
*len
)
1908 socklen_t mylen
= sizeof(sabuf
);
1912 D( fprintf(stderr
, "noip(%d): ACCEPT sk=%d", pid
, sk
); )
1914 nsk
= real_accept(sk
, SA(sabuf
), &mylen
);
1915 if (nsk
< 0) /* failed */;
1916 else if (!sa
) D( fprintf(stderr
, " -> address not wanted"); )
1918 D( fprintf(stderr
, " -> converting...\n"); )
1919 return_fake_peer(sk
, SA(sabuf
), mylen
, sa
, len
);
1920 D( fprintf(stderr
, "noip(%d): ... ACCEPT", pid
); )
1922 D( dump_addrresult(nsk
, sa
, len ?
*len
: 0); )
1926 int getsockname(int sk
, struct sockaddr
*sa
, socklen_t
*len
)
1929 socklen_t mylen
= sizeof(sabuf
);
1933 D( fprintf(stderr
, "noip(%d): GETSOCKNAME sk=%d", pid
, sk
); )
1934 rc
= real_getsockname(sk
, SA(sabuf
), &mylen
);
1936 D( fprintf(stderr
, " -> converting...\n"); )
1937 return_fake_name(SA(sabuf
), mylen
, sa
, len
, 0);
1938 D( fprintf(stderr
, "noip(%d): ... GETSOCKNAME", pid
); )
1940 D( dump_addrresult(rc
, sa
, *len
); )
1944 int getpeername(int sk
, struct sockaddr
*sa
, socklen_t
*len
)
1947 socklen_t mylen
= sizeof(sabuf
);
1951 D( fprintf(stderr
, "noip(%d): GETPEERNAME sk=%d", pid
, sk
); )
1952 rc
= real_getpeername(sk
, SA(sabuf
), &mylen
);
1954 D( fprintf(stderr
, " -> converting...\n"); )
1955 return_fake_peer(sk
, SA(sabuf
), mylen
, sa
, len
);
1956 D( fprintf(stderr
, "noip(%d): ... GETPEERNAME", pid
); )
1958 D( dump_addrresult(rc
, sa
, *len
); )
1962 int getsockopt(int sk
, int lev
, int opt
, void *p
, socklen_t
*len
)
1973 return (real_getsockopt(sk
, lev
, opt
, p
, len
));
1976 int setsockopt(int sk
, int lev
, int opt
, const void *p
, socklen_t len
)
1986 case SO_BINDTODEVICE
:
1987 case SO_ATTACH_FILTER
:
1988 case SO_DETACH_FILTER
:
1991 return (real_setsockopt(sk
, lev
, opt
, p
, len
));
1994 int ioctl(int fd
, unsigned long op
, ...)
2002 arg
= va_arg(ap
, void *);
2006 case SIOCGIFBRDADDR
:
2007 case SIOCGIFDSTADDR
:
2008 case SIOCGIFNETMASK
:
2010 if (fixup_real_ip_socket(fd
, AF_INET
, &sk
)) goto real
;
2012 rc
= real_ioctl(sk
, op
, arg
);
2013 PRESERVING_ERRNO({ close(sk
); });
2017 rc
= real_ioctl(fd
, op
, arg
);
2024 /*----- Initialization ----------------------------------------------------*/
2026 /* Clean up the socket directory, deleting stale sockets. */
2027 static void cleanup_sockdir(void)
2032 struct sockaddr_un sun
;
2036 if ((dir
= opendir(sockdir
)) == 0) return;
2037 sun
.sun_family
= AF_UNIX
;
2038 while ((d
= readdir(dir
)) != 0) {
2039 if (d
->d_name
[0] == '.') continue;
2040 snprintf(sun
.sun_path
, sizeof(sun
.sun_path
),
2041 "%s/%s", sockdir
, d
->d_name
);
2042 if (decode_inet_addr(&addr
.sa
, 0, &sun
, SUN_LEN(&sun
)) ||
2043 stat(sun
.sun_path
, &st
) ||
2044 !S_ISSOCK(st
.st_mode
)) {
2045 D( fprintf(stderr
, "noip(%d): ignoring unknown socketdir entry `%s'\n",
2046 pid
, sun
.sun_path
); )
2049 if (unix_socket_status(&sun
, 0) == STALE
) {
2050 D( fprintf(stderr
, "noip(%d): clearing away stale socket %s\n",
2052 unlink(sun
.sun_path
);
2058 /* Find the addresses attached to local network interfaces, and remember them
2061 static void get_local_ipaddrs(void)
2063 struct ifaddrs
*ifa_head
, *ifa
;
2068 D( fprintf(stderr
, "noip(%d): fetching local addresses...\n", pid
); )
2069 if (getifaddrs(&ifa_head
)) { perror("getifaddrs"); return; }
2070 for (n_local_ipaddrs
= 0, ifa
= ifa_head
;
2071 n_local_ipaddrs
< MAX_LOCAL_IPADDRS
&& ifa
;
2072 ifa
= ifa
->ifa_next
) {
2073 if (!ifa
->ifa_addr
|| !family_known_p(ifa
->ifa_addr
->sa_family
))
2075 ipaddr_from_sockaddr(&a
, ifa
->ifa_addr
);
2076 D({ char buf
[ADDRBUFSZ
];
2077 fprintf(stderr
, "noip(%d): local addr %s = %s", pid
,
2079 inet_ntop(ifa
->ifa_addr
->sa_family
, &a
,
2080 buf
, sizeof(buf
))); })
2081 for (i
= 0; i
< n_local_ipaddrs
; i
++) {
2082 if (ifa
->ifa_addr
->sa_family
== local_ipaddrs
[i
].af
&&
2083 ipaddr_equal_p(local_ipaddrs
[i
].af
, &a
, &local_ipaddrs
[i
].addr
)) {
2084 D( fprintf(stderr
, " (duplicate)\n"); )
2088 D( fprintf(stderr
, "\n"); )
2089 local_ipaddrs
[n_local_ipaddrs
].af
= ifa
->ifa_addr
->sa_family
;
2090 local_ipaddrs
[n_local_ipaddrs
].addr
= a
;
2094 freeifaddrs(ifa_head
);
2097 /* Print the given message to standard error. Avoids stdio. */
2098 static void printerr(const char *p
)
2099 { if (write(STDERR_FILENO
, p
, strlen(p
))) ; }
2101 /* Create the socket directory, being careful about permissions. */
2102 static void create_sockdir(void)
2106 if (lstat(sockdir
, &st
)) {
2107 if (errno
== ENOENT
) {
2108 if (mkdir(sockdir
, 0700)) {
2109 perror("noip: creating socketdir");
2112 if (!lstat(sockdir
, &st
))
2115 perror("noip: checking socketdir");
2119 if (!S_ISDIR(st
.st_mode
)) {
2120 printerr("noip: bad socketdir: not a directory\n");
2123 if (st
.st_uid
!= uid
) {
2124 printerr("noip: bad socketdir: not owner\n");
2127 if (st
.st_mode
& 077) {
2128 printerr("noip: bad socketdir: not private\n");
2133 /* Initialization function. */
2134 static void setup(void) __attribute__((constructor
));
2135 static void setup(void)
2142 if ((p
= getenv("NOIP_DEBUG")) && atoi(p
))
2144 get_local_ipaddrs();
2151 /*----- That's all, folks -------------------------------------------------*/