chiark / gitweb /
noip.c (unix_socket_status): Return whether anyone's listening.
[preload-hacks] / noip.c
CommitLineData
1d1ccf4f
MW
1/* -*-c-*-
2 *
3 * Make programs use Unix-domain sockets instead of IP
4 *
5 * (c) 2008 Straylight/Edgeware
6 */
7
8/*----- Licensing notice --------------------------------------------------*
9 *
10 * This file is part of the preload-hacks package.
11 *
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.
16 *
de6df72d
MW
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
20 * for more details.
1d1ccf4f
MW
21 *
22 * You should have received a copy of the GNU General Public License along
de6df72d
MW
23 * with preload-hacks; if not, write to the Free Software Foundation, Inc.,
24 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
1d1ccf4f
MW
25 */
26
e4976bb0 27#define _GNU_SOURCE
28#undef sun
29#undef SUN
30#define DEBUG
31
1d1ccf4f
MW
32/*----- Header files ------------------------------------------------------*/
33
9314b85a 34#include <assert.h>
e4976bb0 35#include <ctype.h>
36#include <errno.h>
658c1774 37#include <stdarg.h>
9314b85a 38#include <stddef.h>
e4976bb0 39#include <stdio.h>
40#include <stdlib.h>
41
42#include <unistd.h>
43#include <dirent.h>
44#include <dlfcn.h>
45#include <fcntl.h>
46#include <pwd.h>
47
48#include <sys/ioctl.h>
49#include <sys/socket.h>
50#include <sys/stat.h>
51#include <sys/un.h>
52
53#include <netinet/in.h>
54#include <arpa/inet.h>
55#include <netinet/tcp.h>
56#include <netinet/udp.h>
9f1396d9 57#include <ifaddrs.h>
9314b85a 58#include <netdb.h>
e4976bb0 59
1d1ccf4f
MW
60/*----- Data structures ---------------------------------------------------*/
61
74eb4869
MW
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 */
97162e5b 66#define LISTEN 2u /* Socket has an active listener */
74eb4869 67
1d1ccf4f
MW
68enum { DENY, ALLOW }; /* ACL verdicts */
69
2a06ea0b 70static int address_families[] = { AF_INET, AF_INET6, -1 };
9314b85a
MW
71
72#define ADDRBUFSZ 64
73
74/* Address representations. */
75typedef union ipaddr {
76 struct in_addr v4;
2a06ea0b 77 struct in6_addr v6;
9314b85a
MW
78} ipaddr;
79
80/* Convenient socket address hacking. */
81typedef union address {
82 struct sockaddr sa;
83 struct sockaddr_in sin;
2a06ea0b 84 struct sockaddr_in6 sin6;
9314b85a
MW
85} address;
86
1d1ccf4f 87/* Access control list nodes */
e4976bb0 88typedef struct aclnode {
89 struct aclnode *next;
90 int act;
9314b85a
MW
91 int af;
92 ipaddr minaddr, maxaddr;
e4976bb0 93 unsigned short minport, maxport;
94} aclnode;
95
7be80f86
MW
96/* Implicit bind records */
97typedef struct impbind {
98 struct impbind *next;
99 int af, how;
100 ipaddr minaddr, maxaddr, bindaddr;
101} impbind;
102enum { EXPLICIT, SAME };
103
006dd63f
MW
104/* A type for an address range */
105typedef struct addrrange {
106 int type;
107 union {
108 struct { int af; ipaddr min, max; } range;
109 } u;
110} addrrange;
111enum { EMPTY, ANY, LOCAL, RANGE };
112
1d1ccf4f 113/* Local address records */
9314b85a
MW
114typedef struct full_ipaddr {
115 int af;
116 ipaddr addr;
117} full_ipaddr;
2a06ea0b 118#define MAX_LOCAL_IPADDRS 64
9314b85a 119static full_ipaddr local_ipaddrs[MAX_LOCAL_IPADDRS];
e4976bb0 120static int n_local_ipaddrs;
121
1d1ccf4f 122/* General configuration */
e4976bb0 123static uid_t uid;
124static char *sockdir = 0;
125static int debug = 0;
f6049fdd 126static unsigned minautoport = 16384, maxautoport = 65536;
e4976bb0 127
1d1ccf4f 128/* Access control lists */
e4976bb0 129static aclnode *bind_real, **bind_tail = &bind_real;
130static aclnode *connect_real, **connect_tail = &connect_real;
7be80f86 131static impbind *impbinds, **impbind_tail = &impbinds;
e4976bb0 132
1d1ccf4f 133/*----- Import the real versions of functions -----------------------------*/
e4976bb0 134
1d1ccf4f 135/* The list of functions to immport. */
e4976bb0 136#define IMPORTS(_) \
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, \
7d769c69 149 struct sockaddr *from, socklen_t *fromlen)) \
e4976bb0 150 _(sendmsg, ssize_t, (int, const struct msghdr *, int)) \
658c1774
MW
151 _(recvmsg, ssize_t, (int, struct msghdr *, int)) \
152 _(ioctl, int, (int, unsigned long, ...))
e4976bb0 153
1d1ccf4f 154/* Function pointers to set up. */
e4976bb0 155#define DECL(imp, ret, args) static ret (*real_##imp) args;
156IMPORTS(DECL)
157#undef DECL
158
1d1ccf4f 159/* Import the system calls. */
e4976bb0 160static void import(void)
161{
162#define IMPORT(imp, ret, args) \
163 real_##imp = (ret (*)args)dlsym(RTLD_NEXT, #imp);
164 IMPORTS(IMPORT)
165#undef IMPORT
166}
167
1d1ccf4f 168/*----- Utilities ---------------------------------------------------------*/
e4976bb0 169
1d1ccf4f 170/* Socket address casts */
e4976bb0 171#define SA(sa) ((struct sockaddr *)(sa))
172#define SIN(sa) ((struct sockaddr_in *)(sa))
2a06ea0b 173#define SIN6(sa) ((struct sockaddr_in6 *)(sa))
e4976bb0 174#define SUN(sa) ((struct sockaddr_un *)(sa))
175
1d1ccf4f 176/* Raw bytes */
e4976bb0 177#define UC(ch) ((unsigned char)(ch))
178
1d1ccf4f 179/* Memory allocation */
e4976bb0 180#define NEW(x) ((x) = xmalloc(sizeof(*x)))
181#define NEWV(x, n) ((x) = xmalloc(sizeof(*x) * (n)))
182
1d1ccf4f 183/* Debugging */
e4976bb0 184#ifdef DEBUG
185# define D(body) { if (debug) { body } }
e397f0bd 186# define Dpid pid_t pid = debug ? getpid() : -1
e4976bb0 187#else
188# define D(body) ;
e397f0bd 189# define Dpid
e4976bb0 190#endif
191
1d1ccf4f 192/* Preservation of error status */
e4976bb0 193#define PRESERVING_ERRNO(body) do { \
194 int _err = errno; { body } errno = _err; \
195} while (0)
196
1d1ccf4f 197/* Allocate N bytes of memory; abort on failure. */
e4976bb0 198static void *xmalloc(size_t n)
199{
200 void *p;
201 if (!n) return (0);
3ef1fec9 202 if ((p = malloc(n)) == 0) { perror("malloc"); exit(127); }
e4976bb0 203 return (p);
204}
205
1d1ccf4f 206/* Allocate a copy of the null-terminated string P; abort on failure. */
e4976bb0 207static char *xstrdup(const char *p)
208{
209 size_t n = strlen(p) + 1;
210 char *q = xmalloc(n);
211 memcpy(q, p, n);
212 return (q);
213}
9314b85a
MW
214
215/*----- Address-type hacking ----------------------------------------------*/
216
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.
220 */
221static int simple_mask_length(unsigned long m)
222{
223 int n = 0;
224
225 while (m & 1) { n++; m >>= 1; }
226 return (m ? -1 : n);
227}
228
229/* Answer whether AF is an interesting address family. */
230static int family_known_p(int af)
231{
232 switch (af) {
233 case AF_INET:
2a06ea0b 234 case AF_INET6:
9314b85a
MW
235 return (1);
236 default:
237 return (0);
238 }
239}
240
241/* Return the socket address length for address family AF. */
242static socklen_t family_socklen(int af)
243{
244 switch (af) {
245 case AF_INET: return (sizeof(struct sockaddr_in));
2a06ea0b 246 case AF_INET6: return (sizeof(struct sockaddr_in6));
9314b85a
MW
247 default: abort();
248 }
249}
250
251/* Return the width of addresses of kind AF. */
252static int address_width(int af)
253{
254 switch (af) {
255 case AF_INET: return 32;
2a06ea0b 256 case AF_INET6: return 128;
9314b85a
MW
257 default: abort();
258 }
259}
260
261/* If addresses A and B share a common prefix then return its length;
262 * otherwise return -1.
263 */
264static int common_prefix_length(int af, const ipaddr *a, const ipaddr *b)
265{
266 switch (af) {
267 case AF_INET: {
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));
271 else return (-1);
272 } break;
2a06ea0b
MW
273 case AF_INET6: {
274 const uint8_t *aa = a->v6.s6_addr, *bb = b->v6.s6_addr;
275 unsigned m;
276 unsigned n;
277 int i;
278
279 for (i = 0; i < 16 && aa[i] == bb[i]; i++);
280 n = 8*i;
281 if (i < 16) {
282 m = aa[i]^bb[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);
287 }
288 return (n);
289 } break;
9314b85a
MW
290 default:
291 abort();
292 }
293}
294
295/* Extract the port number (in host byte-order) from SA. */
296static int port_from_sockaddr(const struct sockaddr *sa)
297{
298 switch (sa->sa_family) {
299 case AF_INET: return (ntohs(SIN(sa)->sin_port));
2a06ea0b 300 case AF_INET6: return (ntohs(SIN6(sa)->sin6_port));
9314b85a
MW
301 default: abort();
302 }
303}
304
305/* Store the port number PORT (in host byte-order) in SA. */
306static void port_to_sockaddr(struct sockaddr *sa, int port)
307{
308 switch (sa->sa_family) {
309 case AF_INET: SIN(sa)->sin_port = htons(port); break;
2a06ea0b 310 case AF_INET6: SIN6(sa)->sin6_port = htons(port); break;
9314b85a
MW
311 default: abort();
312 }
313}
10cee633 314
9314b85a
MW
315/* Extract the address part from SA and store it in A. */
316static void ipaddr_from_sockaddr(ipaddr *a, const struct sockaddr *sa)
317{
318 switch (sa->sa_family) {
319 case AF_INET: a->v4 = SIN(sa)->sin_addr; break;
2a06ea0b 320 case AF_INET6: a->v6 = SIN6(sa)->sin6_addr; break;
9314b85a
MW
321 default: abort();
322 }
323}
324
7be80f86
MW
325/* Store the address A in SA. */
326static void ipaddr_to_sockaddr(struct sockaddr *sa, const ipaddr *a)
327{
328 switch (sa->sa_family) {
329 case AF_INET:
330 SIN(sa)->sin_addr = a->v4;
331 break;
332 case AF_INET6:
333 SIN6(sa)->sin6_addr = a->v6;
334 SIN6(sa)->sin6_scope_id = 0;
335 SIN6(sa)->sin6_flowinfo = 0;
336 break;
337 default:
338 abort();
339 }
340}
341
9314b85a
MW
342/* Copy a whole socket address about. */
343static 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)); }
346
a62e4ece
MW
347/* Convert an AF_INET socket address into the equivalent IPv4-mapped AF_INET6
348 * address.
349 */
350static void map_ipv4_sockaddr(struct sockaddr_in6 *a6,
351 const struct sockaddr_in *a4)
352{
353 size_t i;
354 in_addr_t a = ntohl(a4->sin_addr.s_addr);
355
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;
363}
364
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.
368 */
369static int unmap_ipv4_sockaddr(struct sockaddr_in *a4,
370 const struct sockaddr_in6 *a6)
371{
372 size_t i;
373 in_addr_t a;
374
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);
381 return (0);
382}
383
9314b85a
MW
384/* Answer whether two addresses are equal. */
385static int ipaddr_equal_p(int af, const ipaddr *a, const ipaddr *b)
386{
387 switch (af) {
388 case AF_INET: return (a->v4.s_addr == b->v4.s_addr);
2a06ea0b 389 case AF_INET6: return (memcmp(a->v6.s6_addr, b->v6.s6_addr, 16) == 0);
9314b85a
MW
390 default: abort();
391 }
392}
393
394/* Answer whether the address part of SA is between A and B (inclusive). We
395 * assume that SA has the correct address family.
396 */
397static int sockaddr_in_range_p(const struct sockaddr *sa,
398 const ipaddr *a, const ipaddr *b)
399{
400 switch (sa->sa_family) {
401 case AF_INET: {
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));
405 } break;
2a06ea0b
MW
406 case AF_INET6: {
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;
409 int h = 1, l = 1;
410 int i;
411
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;
416 }
417 return (1);
418 } break;
9314b85a
MW
419 default:
420 abort();
421 }
422}
423
424/* Fill in SA with the appropriate wildcard address. */
425static void wildcard_address(int af, struct sockaddr *sa)
426{
427 switch (af) {
428 case AF_INET: {
429 struct sockaddr_in *sin = SIN(sa);
430 memset(sin, 0, sizeof(*sin));
431 sin->sin_family = AF_INET;
432 sin->sin_port = 0;
433 sin->sin_addr.s_addr = INADDR_ANY;
434 } break;
2a06ea0b
MW
435 case AF_INET6: {
436 struct sockaddr_in6 *sin6 = SIN6(sa);
dc2b0a44 437 memset(sin6, 0, sizeof(*sin6));
2a06ea0b
MW
438 sin6->sin6_family = AF_INET6;
439 sin6->sin6_port = 0;
440 sin6->sin6_addr = in6addr_any;
441 sin6->sin6_scope_id = 0;
442 sin6->sin6_flowinfo = 0;
443 } break;
9314b85a
MW
444 default:
445 abort();
446 }
447}
448
449/* Mask the address A, forcing all but the top PLEN bits to zero or one
450 * according to HIGHP.
451 */
452static void mask_address(int af, ipaddr *a, int plen, int highp)
453{
454 switch (af) {
455 case AF_INET: {
456 unsigned long addr = ntohl(a->v4.s_addr);
457 unsigned long mask = plen ? ~0ul << (32 - plen) : 0;
458 addr &= mask;
459 if (highp) addr |= ~mask;
460 a->v4.s_addr = htonl(addr & 0xffffffff);
461 } break;
2a06ea0b
MW
462 case AF_INET6: {
463 int i = plen/8;
464 unsigned m = (0xff << (8 - plen%8)) & 0xff;
465 unsigned s = highp ? 0xff : 0;
466 if (m) {
467 a->v6.s6_addr[i] = (a->v6.s6_addr[i] & m) | (s & ~m);
468 i++;
469 }
470 for (; i < 16; i++) a->v6.s6_addr[i] = s;
471 } break;
9314b85a
MW
472 default:
473 abort();
474 }
475}
476
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).
481 */
482static char *present_sockaddr(const struct sockaddr *sa, socklen_t len,
483 char *buf, size_t sz)
484{
485#define WANT(n_) do { if (sz < (n_)) goto nospace; } while (0)
486#define PUTC(c_) do { *buf++ = (c_); sz--; } while (0)
487
ad0f7002 488 if (!sa) return "<null-address>";
9314b85a
MW
489 if (!sz) return "<no-space-in-buffer>";
490 if (!len) len = family_socklen(sa->sa_family);
491
492 switch (sa->sa_family) {
493 case AF_UNIX: {
494 struct sockaddr_un *sun = SUN(sa);
495 char *p = sun->sun_path;
496 size_t n = len - offsetof(struct sockaddr_un, sun_path);
497
498 assert(n);
499 if (*p == 0) {
500 WANT(1); PUTC('@');
501 p++; n--;
502 while (n) {
503 switch (*p) {
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;
511 default:
512 if (*p > ' ' && *p <= '~')
513 { WANT(1); PUTC(*p); }
514 else {
515 WANT(4); PUTC('\\'); PUTC('x');
516 PUTC((*p >> 4)&0xf); PUTC((*p >> 0)&0xf);
517 }
518 break;
519 }
520 p++; n--;
521 }
522 } else {
523 if (*p != '/') { WANT(2); PUTC('.'); PUTC('/'); }
524 while (n && *p) { WANT(1); PUTC(*p); p++; n--; }
525 }
526 WANT(1); PUTC(0);
527 } break;
2a06ea0b 528 case AF_INET: case AF_INET6: {
9314b85a
MW
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);
534 assert(!err);
535 snprintf(buf, sz, strchr(addrbuf, ':') ? "[%s]:%s" : "%s:%s",
536 addrbuf, portbuf);
537 } break;
538 default:
539 snprintf(buf, sz, "<unknown-address-family %d>", sa->sa_family);
540 break;
541 }
542 return (buf);
543
544nospace:
545 buf[sz - 1] = 0;
546 return (buf);
547}
548
549/* Guess the family of a textual socket address. */
550static int guess_address_family(const char *p)
2a06ea0b 551 { return (strchr(p, ':') ? AF_INET6 : AF_INET); }
9314b85a
MW
552
553/* Parse a socket address P and write the result to SA. */
554static int parse_sockaddr(struct sockaddr *sa, const char *p)
555{
556 char buf[ADDRBUFSZ];
557 char *q;
558 struct addrinfo *ai, ai_hint = { 0 };
559
560 if (strlen(p) >= sizeof(buf) - 1) return (-1);
561 strcpy(buf, p); p = buf;
562 if (*p != '[') {
563 if ((q = strchr(p, ':')) == 0) return (-1);
564 *q++ = 0;
565 } else {
566 p++;
567 if ((q = strchr(p, ']')) == 0) return (-1);
568 *q++ = 0;
569 if (*q != ':') return (-1);
570 q++;
571 }
572
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);
578 freeaddrinfo(ai);
579 return (0);
580}
581
1d1ccf4f 582/*----- Access control lists ----------------------------------------------*/
e4976bb0 583
584#ifdef DEBUG
585
006dd63f 586static void dump_addrrange(int af, const ipaddr *min, const ipaddr *max)
e4976bb0 587{
9314b85a
MW
588 char buf[ADDRBUFSZ];
589 const char *p;
590 int plen;
e4976bb0 591
006dd63f
MW
592 plen = common_prefix_length(af, min, max);
593 p = inet_ntop(af, min, buf, sizeof(buf));
9314b85a
MW
594 fprintf(stderr, strchr(p, ':') ? "[%s]" : "%s", p);
595 if (plen < 0) {
006dd63f 596 p = inet_ntop(af, &max, buf, sizeof(buf));
9314b85a 597 fprintf(stderr, strchr(p, ':') ? "-[%s]" : "-%s", p);
006dd63f 598 } else if (plen < address_width(af))
9314b85a 599 fprintf(stderr, "/%d", plen);
006dd63f
MW
600}
601
602/* Write to standard error a description of the ACL node A. */
603static void dump_aclnode(const aclnode *a)
604{
605 fprintf(stderr, "noip(%d): %c ", getpid(), a->act ? '+' : '-');
606 dump_addrrange(a->af, &a->minaddr, &a->maxaddr);
e4976bb0 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);
611 }
612 fputc('\n', stderr);
613}
614
bb182ccf 615static void dump_acl(const aclnode *a)
1d1ccf4f
MW
616{
617 int act = ALLOW;
618
619 for (; a; a = a->next) {
620 dump_aclnode(a);
621 act = a->act;
622 }
e397f0bd 623 fprintf(stderr, "noip(%d): [default policy: %s]\n", getpid(),
1d1ccf4f
MW
624 act == ALLOW ? "DENY" : "ALLOW");
625}
626
e4976bb0 627#endif
628
9314b85a 629/* Returns nonzero if the ACL A allows the socket address SA. */
bb182ccf 630static int acl_allows_p(const aclnode *a, const struct sockaddr *sa)
e4976bb0 631{
9314b85a 632 unsigned short port = port_from_sockaddr(sa);
e4976bb0 633 int act = ALLOW;
e397f0bd 634 Dpid;
e4976bb0 635
9314b85a 636 D({ char buf[ADDRBUFSZ];
e397f0bd 637 fprintf(stderr, "noip(%d): check %s\n", pid,
9314b85a 638 present_sockaddr(sa, 0, buf, sizeof(buf))); })
e4976bb0 639 for (; a; a = a->next) {
640 D( dump_aclnode(a); )
deedf22d
MW
641 if (a->af == sa->sa_family &&
642 sockaddr_in_range_p(sa, &a->minaddr, &a->maxaddr) &&
e4976bb0 643 a->minport <= port && port <= a->maxport) {
e397f0bd
MW
644 D( fprintf(stderr, "noip(%d): aha! %s\n", pid,
645 a->act ? "ALLOW" : "DENY"); )
e4976bb0 646 return (a->act);
647 }
648 act = a->act;
649 }
e397f0bd
MW
650 D( fprintf(stderr, "noip(%d): nothing found: %s\n", pid,
651 act ? "DENY" : "ALLOW"); )
e4976bb0 652 return (!act);
653}
654
1d1ccf4f 655/*----- Socket address conversion -----------------------------------------*/
e4976bb0 656
1d1ccf4f 657/* Return a uniformly distributed integer between MIN and MAX inclusive. */
f6049fdd 658static unsigned randrange(unsigned min, unsigned max)
659{
660 unsigned mask, i;
661
662 /* It's so nice not to have to care about the quality of the generator
9314b85a
MW
663 * much!
664 */
f6049fdd 665 max -= min;
666 for (mask = 1; mask < max; mask = (mask << 1) | 1)
667 ;
668 do i = rand() & mask; while (i > max);
669 return (i + min);
670}
671
1d1ccf4f
MW
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.
677 */
678static int unix_socket_status(struct sockaddr_un *sun, int quickp)
679{
680 struct stat st;
681 FILE *fp = 0;
682 size_t len, n;
683 int rc;
97162e5b 684 unsigned long f;
1d1ccf4f
MW
685 char buf[256];
686
4b1a6174
MW
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.
689 */
1d1ccf4f
MW
690 if (stat(sun->sun_path, &st))
691 return (errno == ENOENT ? UNUSED : USED);
4b1a6174
MW
692
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
695 * discourage us now.
696 */
1d1ccf4f
MW
697 if (!S_ISSOCK(st.st_mode) || quickp)
698 return (USED);
4b1a6174
MW
699
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.
703 */
1d1ccf4f
MW
704 rc = USED;
705 if ((fp = fopen("/proc/net/unix", "r")) == 0)
706 goto done;
72d85cdb 707 if (!fgets(buf, sizeof(buf), fp)) goto done; /* skip header */
1d1ccf4f 708 len = strlen(sun->sun_path);
61fbb4a5 709 rc = 0;
1d1ccf4f
MW
710 while (fgets(buf, sizeof(buf), fp)) {
711 n = strlen(buf);
712 if (n >= len + 2 && buf[n - len - 2] == ' ' && buf[n - 1] == '\n' &&
61fbb4a5
MW
713 memcmp(buf + n - len - 1, sun->sun_path, len) == 0) {
714 rc |= USED;
97162e5b
MW
715 if (sscanf(buf, "%*s %*x %*x %lx", &f) < 0 || (f&0x00010000))
716 rc |= LISTEN;
61fbb4a5 717 }
1d1ccf4f
MW
718 }
719 if (ferror(fp))
720 goto done;
61fbb4a5 721 if (!rc) rc = STALE;
1d1ccf4f
MW
722done:
723 if (fp) fclose(fp);
4b1a6174
MW
724
725 /* All done. */
1d1ccf4f
MW
726 return (rc);
727}
728
81e3737d
MW
729/* Encode SA as a Unix-domain address SUN, and return whether it's currently
730 * in use.
731 */
732static int encode_single_inet_addr(const struct sockaddr *sa,
733 struct sockaddr_un *sun,
734 int quickp)
735{
736 char buf[ADDRBUFSZ];
737 int rc;
738
739 snprintf(sun->sun_path, sizeof(sun->sun_path), "%s/%s", sockdir,
740 present_sockaddr(sa, 0, buf, sizeof(buf)));
c0ae47b3
MW
741 rc = unix_socket_status(sun, quickp);
742 if (rc == STALE) unlink(sun->sun_path);
743 return (rc);
81e3737d
MW
744}
745
f6e0ea86
MW
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
748 * sockets.
749 */
750static int encode_unused_inet_addr(struct sockaddr *sa,
751 struct sockaddr_un *sun,
752 int desperatep)
753{
a62e4ece 754 address waddr, maddr;
f6e0ea86 755 struct sockaddr_un wsun;
d0e289af 756 int port = port_from_sockaddr(sa);
f6e0ea86 757
4b1a6174
MW
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.)
761 */
74eb4869 762 if (encode_single_inet_addr(sa, sun, !desperatep)&USED)
81e3737d 763 return (-1);
f6e0ea86 764
4b1a6174
MW
765 /* Next, check the corresponding wildcard address, so as to avoid
766 * inadvertant collisions with listeners. Do this in the same way.
767 */
f6e0ea86 768 wildcard_address(sa->sa_family, &waddr.sa);
d0e289af 769 port_to_sockaddr(&waddr.sa, port);
74eb4869 770 if (encode_single_inet_addr(&waddr.sa, &wsun, !desperatep)&USED)
81e3737d 771 return (-1);
f6e0ea86 772
a62e4ece
MW
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
775 * wildcard. Ugh!
776 */
777 if (sa->sa_family == AF_INET) {
778 map_ipv4_sockaddr(&maddr.sin6, SIN(&sa));
74eb4869 779 if (encode_single_inet_addr(&maddr.sa, &wsun, !desperatep)&USED)
a62e4ece
MW
780 return (-1);
781
782 map_ipv4_sockaddr(&maddr.sin6, &waddr.sin);
74eb4869 783 if (encode_single_inet_addr(&maddr.sa, &wsun, !desperatep)&USED)
a62e4ece
MW
784 return (-1);
785
786 wildcard_address(AF_INET6, &waddr.sa);
787 port_to_sockaddr(&waddr.sa, port);
74eb4869 788 if (encode_single_inet_addr(&waddr.sa, &wsun, !desperatep)&USED)
a62e4ece
MW
789 return (-1);
790 }
791
4b1a6174 792 /* All is well. */
f6e0ea86
MW
793 return (0);
794}
795
4b9d1fad
MW
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.
1d1ccf4f 801 */
4b9d1fad 802#define ENCF_FRESH 1u
e4976bb0 803static int encode_inet_addr(struct sockaddr_un *sun,
9314b85a 804 const struct sockaddr *sa,
4b9d1fad 805 unsigned f)
e4976bb0 806{
807 int i;
3ef1fec9 808 int desperatep = 0;
9314b85a 809 address addr;
a62e4ece 810 struct sockaddr_in6 sin6;
d0e289af 811 int port = port_from_sockaddr(sa);
74eb4869 812 int rc;
9314b85a 813 char buf[ADDRBUFSZ];
e4976bb0 814
e397f0bd 815 D( fprintf(stderr, "noip(%d): encode %s (%s)", getpid(),
9314b85a 816 present_sockaddr(sa, 0, buf, sizeof(buf)),
4b9d1fad 817 (f&ENCF_FRESH) ? "FRESH" : "EXISTING"); )
4b1a6174
MW
818
819 /* Start making the Unix-domain address. */
e4976bb0 820 sun->sun_family = AF_UNIX;
4b1a6174 821
4b9d1fad 822 if (port || !(f&ENCF_FRESH)) {
4b1a6174
MW
823
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.
826 */
74eb4869
MW
827 rc = encode_single_inet_addr(sa, sun, 0);
828 if ((rc&USED) || (f&ENCF_FRESH)) goto found;
4b1a6174 829
a62e4ece
MW
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.
833 *
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.
837 *
838 * * Failing that, we try again with the wildcard address for the
839 * appropriate address family.
840 *
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.
4b1a6174 846 */
a62e4ece
MW
847
848 if (sa->sa_family == AF_INET) {
849 map_ipv4_sockaddr(&addr.sin6, SIN(sa));
74eb4869 850 if (encode_single_inet_addr(&addr.sa, sun, 0)&USED) goto found;
a62e4ece
MW
851 }
852
aed729d0
MW
853 wildcard_address(sa->sa_family, &addr.sa);
854 port_to_sockaddr(&addr.sa, port);
74eb4869 855 if (encode_single_inet_addr(&addr.sa, sun, 0)&USED) goto found;
a62e4ece
MW
856
857 if (sa->sa_family == AF_INET) {
858 map_ipv4_sockaddr(&sin6, &addr.sin);
74eb4869 859 if (encode_single_inet_addr(SA(&sin6), sun, 0)&USED) goto found;
a62e4ece
MW
860 wildcard_address(AF_INET6, &addr.sa);
861 port_to_sockaddr(&addr.sa, port);
74eb4869 862 if (encode_single_inet_addr(&addr.sa, sun, 0)&USED) goto found;
a62e4ece
MW
863 }
864
865 /* Well, this isn't going to work (unless a miraculous race is lost), but
866 * we might as well try.
867 */
868 encode_single_inet_addr(sa, sun, 1);
4b1a6174 869
e4976bb0 870 } else {
4b1a6174
MW
871 /* We want a fresh new socket. */
872
873 /* Make a copy of the given address, because we're going to mangle it. */
9314b85a 874 copy_sockaddr(&addr.sa, sa);
4b1a6174
MW
875
876 /* Try a few random-ish port numbers to see if any of them is spare. */
f6049fdd 877 for (i = 0; i < 10; i++) {
9314b85a 878 port_to_sockaddr(&addr.sa, randrange(minautoport, maxautoport));
f6e0ea86 879 if (!encode_unused_inet_addr(&addr.sa, sun, 0)) goto found;
f6049fdd 880 }
4b1a6174
MW
881
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.
885 */
3ef1fec9 886 for (desperatep = 0; desperatep < 2; desperatep++) {
f6049fdd 887 for (i = minautoport; i <= maxautoport; i++) {
9314b85a 888 port_to_sockaddr(&addr.sa, i);
f6e0ea86 889 if (!encode_unused_inet_addr(&addr.sa, sun, 0)) goto found;
e4976bb0 890 }
891 }
4b1a6174
MW
892
893 /* We failed to find any free ports. */
e4976bb0 894 errno = EADDRINUSE;
895 D( fprintf(stderr, " -- can't resolve\n"); )
896 return (-1);
e4976bb0 897 }
4b1a6174
MW
898
899 /* Success. */
5d8b1560 900found:
e4976bb0 901 D( fprintf(stderr, " -> `%s'\n", sun->sun_path); )
902 return (0);
903}
904
9314b85a 905/* Decode the Unix address SUN to an Internet address SIN. If AF_HINT is
c0876c8c
MW
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
909 * addresses).
00a98a8a 910 */
9314b85a 911static int decode_inet_addr(struct sockaddr *sa, int af_hint,
e4976bb0 912 const struct sockaddr_un *sun,
9314b85a 913 socklen_t len)
e4976bb0 914{
9314b85a 915 char buf[ADDRBUFSZ];
a2114371 916 size_t n = strlen(sockdir), nn;
9314b85a 917 address addr;
e4976bb0 918
9314b85a
MW
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;
a2114371 923 nn = strlen(sun->sun_path);
e397f0bd 924 D( fprintf(stderr, "noip(%d): decode `%s'", getpid(), sun->sun_path); )
9314b85a
MW
925 if (af_hint && !sun->sun_path[0]) {
926 wildcard_address(af_hint, sa);
e4976bb0 927 D( fprintf(stderr, " -- unbound socket\n"); )
928 return (0);
929 }
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"); )
933 return (-1);
934 }
9314b85a
MW
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))); )
e4976bb0 938 return (0);
939}
940
1d1ccf4f
MW
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
86134bfe
MW
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
945 * and return zero.
1d1ccf4f 946 */
86134bfe 947static int fixup_real_ip_socket(int sk, int af_hint, int *tmp)
e4976bb0 948{
949 int nsk;
950 int type;
951 int f, fd;
952 struct sockaddr_un sun;
9314b85a 953 address addr;
e4976bb0 954 socklen_t len;
955
956#define OPTS(_) \
957 _(DEBUG, int) \
958 _(REUSEADDR, int) \
959 _(DONTROUTE, int) \
960 _(BROADCAST, int) \
961 _(SNDBUF, int) \
962 _(RCVBUF, int) \
963 _(OOBINLINE, int) \
964 _(NO_CHECK, int) \
965 _(LINGER, struct linger) \
966 _(BSDCOMPAT, int) \
967 _(RCVLOWAT, int) \
968 _(RCVTIMEO, struct timeval) \
969 _(SNDTIMEO, struct timeval)
970
971 len = sizeof(sun);
972 if (real_getsockname(sk, SA(&sun), &len))
973 return (-1);
9314b85a 974 if (decode_inet_addr(&addr.sa, af_hint, &sun, len))
e4976bb0 975 return (0); /* Not one of ours */
976 len = sizeof(type);
977 if (real_getsockopt(sk, SOL_SOCKET, SO_TYPE, &type, &len) < 0 ||
9314b85a 978 (nsk = real_socket(addr.sa.sa_family, type, 0)) < 0)
e4976bb0 979 return (-1);
980#define FIX(opt, ty) do { \
981 ty ov_; \
982 len = sizeof(ov_); \
983 if (real_getsockopt(sk, SOL_SOCKET, SO_##opt, &ov_, &len) < 0 || \
984 real_setsockopt(nsk, SOL_SOCKET, SO_##opt, &ov_, len)) { \
9fb8e5c9 985 close(nsk); \
e4976bb0 986 return (-1); \
987 } \
988} while (0);
989 OPTS(FIX)
990#undef FIX
86134bfe
MW
991 if (tmp)
992 *tmp = nsk;
993 else {
994 if ((f = fcntl(sk, F_GETFL)) < 0 ||
995 (fd = fcntl(sk, F_GETFD)) < 0 ||
996 fcntl(nsk, F_SETFL, f) < 0 ||
997 dup2(nsk, sk) < 0) {
998 close(nsk);
999 return (-1);
1000 }
1001 unlink(sun.sun_path);
9fb8e5c9 1002 close(nsk);
86134bfe
MW
1003 if (fcntl(sk, F_SETFD, fd) < 0) {
1004 perror("noip: fixup_real_ip_socket F_SETFD");
1005 abort();
1006 }
e4976bb0 1007 }
1008 return (0);
1009}
1010
7be80f86
MW
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
1014 * at FAKELEN.
1015 */
a62e4ece 1016#define FNF_V6MAPPED 1u
7be80f86 1017static void return_fake_name(struct sockaddr *sa, socklen_t len,
a62e4ece
MW
1018 struct sockaddr *fake, socklen_t *fakelen,
1019 unsigned f)
7be80f86
MW
1020{
1021 address addr;
a62e4ece 1022 struct sockaddr_in6 sin6;
7be80f86
MW
1023 socklen_t alen;
1024
1025 if (sa->sa_family == AF_UNIX &&
1026 !decode_inet_addr(&addr.sa, 0, SUN(sa), len)) {
a62e4ece
MW
1027 if (addr.sa.sa_family != AF_INET || !(f&FNF_V6MAPPED)) {
1028 sa = &addr.sa;
1029 len = family_socklen(addr.sa.sa_family);
1030 } else {
1031 map_ipv4_sockaddr(&sin6, &addr.sin);
1032 sa = SA(&sin6);
1033 len = family_socklen(AF_INET6);
1034 }
7be80f86
MW
1035 }
1036 alen = len;
1037 if (len > *fakelen) len = *fakelen;
1038 if (len > 0) memcpy(fake, sa, len);
1039 *fakelen = alen;
1040}
1041
a62e4ece
MW
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
1045 * remote address.
1046 */
1047static void return_fake_peer(int sk, struct sockaddr *sa, socklen_t len,
1048 struct sockaddr *fake, socklen_t *fakelen)
1049{
1050 char sabuf[1024];
1051 socklen_t mylen = sizeof(sabuf);
1052 unsigned fnf = 0;
1053 address addr;
1054 int rc;
1055
1056 PRESERVING_ERRNO({
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;
1062 });
1063 return_fake_name(sa, len, fake, fakelen, fnf);
1064}
1065
7be80f86
MW
1066/*----- Implicit binding --------------------------------------------------*/
1067
1068#ifdef DEBUG
1069
1070static void dump_impbind(const impbind *i)
1071{
1072 char buf[ADDRBUFSZ];
1073
1074 fprintf(stderr, "noip(%d): ", getpid());
1075 dump_addrrange(i->af, &i->minaddr, &i->maxaddr);
1076 switch (i->how) {
1077 case SAME: fprintf(stderr, " <self>"); break;
1078 case EXPLICIT:
1079 fprintf(stderr, " %s", inet_ntop(i->af, &i->bindaddr,
1080 buf, sizeof(buf)));
1081 break;
1082 default: abort();
1083 }
1084 fputc('\n', stderr);
1085}
1086
1087static void dump_impbind_list(void)
1088{
1089 const impbind *i;
1090
1091 for (i = impbinds; i; i = i->next) dump_impbind(i);
1092}
1093
1094#endif
1095
1d1ccf4f 1096/* The socket SK is about to be used to communicate with the remote address
9314b85a
MW
1097 * SA. Assign it a local address so that getpeername(2) does something
1098 * useful.
a62e4ece
MW
1099 *
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.
1d1ccf4f 1106 */
a62e4ece
MW
1107#define IBF_V6MAPPED 1u
1108static int do_implicit_bind(int sk, const struct sockaddr *sa, unsigned f)
e4976bb0 1109{
9314b85a 1110 address addr;
a62e4ece 1111 struct sockaddr_in6 sin6;
6e1fe695 1112 struct sockaddr_un sun;
7be80f86
MW
1113 const impbind *i;
1114 Dpid;
e4976bb0 1115
6e1fe695
MW
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);
1124 goto found;
e4976bb0 1125 }
1126 }
6e1fe695
MW
1127 D( fprintf(stderr, "noip(%d): no match; using wildcard\n", pid); )
1128 wildcard_address(sa->sa_family, &addr.sa);
1129found:
a62e4ece
MW
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);
43598265
MW
1133 D( fprintf(stderr, "noip(%d): implicitly binding to %s\n",
1134 pid, sun.sun_path); )
6e1fe695
MW
1135 if (real_bind(sk, SA(&sun), SUN_LEN(&sun))) return (-1);
1136 return (0);
1137}
1138
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
1141 * remote endpoint.
1142 *
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.
1145 */
1146static int fixup_client_socket(int sk, const struct sockaddr **sa_r,
1147 socklen_t *len_r, struct sockaddr_un *sun)
1148{
a62e4ece 1149 struct sockaddr_in sin;
6e1fe695
MW
1150 socklen_t mylen = sizeof(*sun);
1151 const struct sockaddr *sa = *sa_r;
a62e4ece 1152 unsigned ibf = 0;
6e1fe695 1153
7d7cba35
MW
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;
1158
a62e4ece
MW
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
1161 * autobind.
1162 */
1163 if (sa->sa_family == AF_INET6 && !(unmap_ipv4_sockaddr(&sin, SIN6(sa)))) {
1164 sa = SA(&sin);
1165 ibf |= IBF_V6MAPPED;
1166 }
1167
6e1fe695
MW
1168 /* If we're allowed to talk to a real remote endpoint, then fix things up
1169 * as necessary and proceed.
1170 */
1171 if (acl_allows_p(connect_real, sa)) {
1172 if (fixup_real_ip_socket(sk, (*sa_r)->sa_family, 0)) return (-1);
1173 return (0);
1174 }
1175
6e1fe695
MW
1176 /* Speaking of which, if we don't have a local address, then we should
1177 * arrange one now.
1178 */
a62e4ece 1179 if (!sun->sun_path[0] && do_implicit_bind(sk, sa, ibf)) return (-1);
6e1fe695
MW
1180
1181 /* And then come up with a remote address. */
1182 encode_inet_addr(sun, sa, 0);
1183 *sa_r = SA(sun);
1184 *len_r = SUN_LEN(sun);
e4976bb0 1185 return (0);
1186}
1187
1d1ccf4f 1188/*----- Configuration -----------------------------------------------------*/
e4976bb0 1189
1d1ccf4f 1190/* Return the process owner's home directory. */
e4976bb0 1191static char *home(void)
1192{
1193 char *p;
1194 struct passwd *pw;
1195
3ef1fec9 1196 if (getuid() == uid &&
1197 (p = getenv("HOME")) != 0)
1198 return (p);
1199 else if ((pw = getpwuid(uid)) != 0)
1200 return (pw->pw_dir);
1201 else
1202 return "/notexist";
e4976bb0 1203}
1204
1d1ccf4f 1205/* Return a good temporary directory to use. */
e4976bb0 1206static char *tmpdir(void)
1207{
1208 char *p;
1209
1210 if ((p = getenv("TMPDIR")) != 0) return (p);
1211 else if ((p = getenv("TMP")) != 0) return (p);
1212 else return ("/tmp");
1213}
1214
1d1ccf4f 1215/* Return the user's name, or at least something distinctive. */
e4976bb0 1216static char *user(void)
1217{
1218 static char buf[16];
1219 char *p;
1220 struct passwd *pw;
1221
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);
1225 else {
1226 snprintf(buf, sizeof(buf), "uid-%lu", (unsigned long)uid);
1227 return (buf);
1228 }
1229}
1230
1d1ccf4f 1231/* Skip P over space characters. */
e4976bb0 1232#define SKIPSPC do { while (*p && isspace(UC(*p))) p++; } while (0)
1d1ccf4f
MW
1233
1234/* Set Q to point to the next word following P, null-terminate it, and step P
1235 * past it. */
e4976bb0 1236#define NEXTWORD(q) do { \
1237 SKIPSPC; \
1238 q = p; \
1239 while (*p && !isspace(UC(*p))) p++; \
1240 if (*p) *p++ = 0; \
1241} while (0)
1d1ccf4f
MW
1242
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. */
9314b85a
MW
1245static void parse_nextaddr(char **pp, char **qq, int *del)
1246{
1247 char *p = *pp;
1248
1249 SKIPSPC;
1250 if (*p == '[') {
1251 p++; SKIPSPC;
1252 *qq = p;
1253 p += strcspn(p, "]");
1254 if (*p) *p++ = 0;
1255 *del = 0;
1256 } else {
1257 *qq = p;
1258 while (*p && (*p == '.' || isdigit(UC(*p)))) p++;
1259 *del = *p;
1260 if (*p) *p++ = 0;
1261 }
1262 *pp = p;
1263}
1d1ccf4f
MW
1264
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. */
e4976bb0 1267#define NEXTNUMBER(q, del) do { \
1268 SKIPSPC; \
1269 q = p; \
1270 while (*p && isdigit(UC(*p))) p++; \
1271 del = *p; \
1272 if (*p) *p++ = 0; \
1273} while (0)
1d1ccf4f
MW
1274
1275/* Push the character DEL back so we scan it again, unless it's zero
1276 * (end-of-file). */
e4976bb0 1277#define RESCAN(del) do { if (del) *--p = del; } while (0)
1d1ccf4f
MW
1278
1279/* Evaluate true if P is pointing to the word KW (and not some longer string
1280 * of which KW is a prefix). */
1281
e4976bb0 1282#define KWMATCHP(kw) (strncmp(p, kw, sizeof(kw) - 1) == 0 && \
1283 !isalnum(UC(p[sizeof(kw) - 1])) && \
1284 (p += sizeof(kw) - 1))
9f82ba1f 1285
1d1ccf4f
MW
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.
1290 */
e4976bb0 1291static void parse_ports(char **pp, unsigned short *min, unsigned short *max)
1292{
1293 char *p = *pp, *q;
1294 int del;
1295
1296 SKIPSPC;
f6049fdd 1297 if (*p != ':')
1298 { *min = 0; *max = 0xffff; }
1299 else {
e4976bb0 1300 p++;
f6049fdd 1301 NEXTNUMBER(q, del); *min = strtoul(q, 0, 0); RESCAN(del);
e4976bb0 1302 SKIPSPC;
f6049fdd 1303 if (*p == '-')
d83beb5c 1304 { p++; NEXTNUMBER(q, del); *max = strtoul(q, 0, 0); RESCAN(del); }
f6049fdd 1305 else
e4976bb0 1306 *max = *min;
1307 }
1308 *pp = p;
1309}
1310
006dd63f
MW
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:
1313 *
1314 * any | local | ADDR | ADDR - ADDR | ADDR/ADDR | ADDR/INT
1d1ccf4f 1315 */
006dd63f 1316static int parse_addrrange(char **pp, addrrange *r)
e4976bb0 1317{
006dd63f
MW
1318 char *p = *pp, *q;
1319 int n;
e4976bb0 1320 int del;
006dd63f 1321 int af;
e4976bb0 1322
006dd63f
MW
1323 SKIPSPC;
1324 if (KWMATCHP("any")) r->type = ANY;
1325 else if (KWMATCHP("local")) r->type = LOCAL;
1326 else {
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;
1330 RESCAN(del);
a6d9626b 1331 SKIPSPC;
006dd63f
MW
1332 if (*p == '-') {
1333 p++;
1334 parse_nextaddr(&p, &q, &del);
1335 if (inet_pton(af, q, &r->u.range.max) <= 0) goto bad;
1336 RESCAN(del);
1337 } else if (*p == '/') {
1338 p++;
1339 NEXTNUMBER(q, del);
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);
1344 RESCAN(del);
1345 } else
1346 r->u.range.max = r->u.range.min;
1347 r->type = RANGE;
1348 r->u.range.af = af;
1349 }
1350 *pp = p;
1351 return (0);
e4976bb0 1352
006dd63f
MW
1353bad:
1354 return (-1);
1355}
1356
1357/* Call FUNC on each individual address range in R. */
1358static void foreach_addrrange(const addrrange *r,
1359 void (*func)(int af,
1360 const ipaddr *min,
1361 const ipaddr *max,
1362 void *p),
1363 void *p)
1364{
1365 ipaddr minaddr, maxaddr;
1366 int i, af;
1367
1368 switch (r->type) {
1369 case EMPTY:
1370 break;
1371 case ANY:
9314b85a
MW
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);
006dd63f 1376 func(af, &minaddr, &maxaddr, p);
9314b85a 1377 }
006dd63f
MW
1378 break;
1379 case LOCAL:
9314b85a
MW
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);
006dd63f
MW
1384 func(af, &minaddr, &minaddr, p);
1385 func(af, &maxaddr, &maxaddr, p);
9314b85a 1386 }
a6d9626b 1387 for (i = 0; i < n_local_ipaddrs; i++) {
006dd63f
MW
1388 func(local_ipaddrs[i].af,
1389 &local_ipaddrs[i].addr, &local_ipaddrs[i].addr,
1390 p);
a6d9626b 1391 }
006dd63f
MW
1392 break;
1393 case RANGE:
1394 func(r->u.range.af, &r->u.range.min, &r->u.range.max, p);
1395 break;
1396 default:
1397 abort();
1398 }
1399}
1400
1401struct add_aclnode_ctx {
1402 int act;
1403 unsigned short minport, maxport;
1404 aclnode ***tail;
1405};
1406
1407static void add_aclnode(int af, const ipaddr *min, const ipaddr *max,
1408 void *p)
1409{
1410 struct add_aclnode_ctx *ctx = p;
1411 aclnode *a;
1412
1413 NEW(a);
1414 a->act = ctx->act;
1415 a->af = af;
1416 a->minaddr = *min; a->maxaddr = *max;
1417 a->minport = ctx->minport; a->maxport = ctx->maxport;
1418 **ctx->tail = a; *ctx->tail = &a->next;
1419}
1420
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..
1426 */
1427static void parse_acl_line(char **pp, aclnode ***tail)
1428{
1429 struct add_aclnode_ctx ctx;
1430 addrrange r;
1431 char *p = *pp;
1432
1433 ctx.tail = tail;
1434 for (;;) {
1435 SKIPSPC;
1436 if (*p == '+') ctx.act = ALLOW;
1437 else if (*p == '-') ctx.act = DENY;
1438 else goto bad;
1439
1440 p++;
1441 if (parse_addrrange(&p, &r)) goto bad;
1442 parse_ports(&p, &ctx.minport, &ctx.maxport);
1443 foreach_addrrange(&r, add_aclnode, &ctx);
a6d9626b 1444 SKIPSPC;
1445 if (*p != ',') break;
1cce4a41 1446 if (*p) p++;
e4976bb0 1447 }
67fd355a 1448 if (*p) goto bad;
f797ea6d 1449 *pp = p;
e4976bb0 1450 return;
1451
1452bad:
e397f0bd 1453 D( fprintf(stderr, "noip(%d): bad acl spec (ignored)\n", getpid()); )
e4976bb0 1454 return;
1455}
1456
051fa2d8
MW
1457/* Parse an ACL from an environment variable VAR, attaching it to the list
1458 * TAIL.
1459 */
1460static void parse_acl_env(const char *var, aclnode ***tail)
1461{
1462 char *p, *q;
1463
1464 if ((p = getenv(var)) != 0) {
1465 p = q = xstrdup(p);
1466 parse_acl_line(&q, tail);
1467 free(p);
1468 }
1469}
1470
7be80f86
MW
1471struct add_impbind_ctx {
1472 int af, how;
1473 ipaddr addr;
1474};
1475
1476static void add_impbind(int af, const ipaddr *min, const ipaddr *max,
1477 void *p)
1478{
1479 struct add_impbind_ctx *ctx = p;
1480 impbind *i;
1481
1482 if (ctx->af && af != ctx->af) return;
1483 NEW(i);
1484 i->af = af;
1485 i->how = ctx->how;
1486 i->minaddr = *min; i->maxaddr = *max;
1487 switch (ctx->how) {
1488 case EXPLICIT: i->bindaddr = ctx->addr;
1489 case SAME: break;
1490 default: abort();
1491 }
1492 *impbind_tail = i; impbind_tail = &i->next;
1493}
1494
1495/* Parse an implicit-bind line. An implicit-bind entry has the form
1496 * ADDR-RANGE {ADDR | same}
1497 */
1498static void parse_impbind_line(char **pp)
1499{
1500 struct add_impbind_ctx ctx;
1501 char *p = *pp, *q;
1502 addrrange r;
1503 int del;
1504
1505 for (;;) {
1506 if (parse_addrrange(&p, &r)) goto bad;
1507 SKIPSPC;
1508 if (KWMATCHP("same")) {
1509 ctx.how = SAME;
1510 ctx.af = 0;
1511 } else {
1512 ctx.how = EXPLICIT;
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;
1516 RESCAN(del);
1517 }
1518 foreach_addrrange(&r, add_impbind, &ctx);
1519 SKIPSPC;
1520 if (*p != ',') break;
1521 if (*p) p++;
1522 }
1523 if (*p) goto bad;
1524 *pp = p;
1525 return;
1526
1527bad:
1528 D( fprintf(stderr, "noip(%d): bad implicit-bind spec (ignored)\n",
1529 getpid()); )
1530 return;
1531}
1532
1533/* Parse implicit-bind instructions from an environment variable VAR,
1534 * attaching it to the list.
1535 */
1536static void parse_impbind_env(const char *var)
1537{
1538 char *p, *q;
1539
1540 if ((p = getenv(var)) != 0) {
1541 p = q = xstrdup(p);
1542 parse_impbind_line(&q);
1543 free(p);
1544 }
1545}
1546
1d1ccf4f 1547/* Parse the autoports configuration directive. Syntax is MIN - MAX. */
f6049fdd 1548static void parse_autoports(char **pp)
1549{
1550 char *p = *pp, *q;
1551 unsigned x, y;
1552 int del;
1553
1554 SKIPSPC;
1555 NEXTNUMBER(q, del); x = strtoul(q, 0, 0); RESCAN(del);
1556 SKIPSPC;
c6569cc9
MW
1557 if (*p != '-') goto bad;
1558 p++;
f6049fdd 1559 NEXTNUMBER(q, del); y = strtoul(q, 0, 0); RESCAN(del);
1560 minautoport = x; maxautoport = y;
67fd355a 1561 SKIPSPC; if (*p) goto bad;
f797ea6d 1562 *pp = p;
f6049fdd 1563 return;
1564
1565bad:
e397f0bd 1566 D( fprintf(stderr, "noip(%d): bad port range (ignored)\n", getpid()); )
f6049fdd 1567 return;
1568}
1569
1d1ccf4f 1570/* Read the configuration from the config file and environment. */
e4976bb0 1571static void readconfig(void)
1572{
1573 FILE *fp;
1574 char buf[1024];
1575 size_t n;
f6049fdd 1576 char *p, *q, *cmd;
e397f0bd 1577 Dpid;
e4976bb0 1578
a6d9626b 1579 parse_acl_env("NOIP_REALBIND_BEFORE", &bind_tail);
1580 parse_acl_env("NOIP_REALCONNECT_BEFORE", &connect_tail);
7be80f86 1581 parse_impbind_env("NOIP_IMPBIND_BEFORE");
f6049fdd 1582 if ((p = getenv("NOIP_AUTOPORTS")) != 0) {
1583 p = q = xstrdup(p);
1584 parse_autoports(&q);
1585 free(p);
1586 }
4ab301de 1587 if ((p = getenv("NOIP_CONFIG")) == 0)
1588 snprintf(p = buf, sizeof(buf), "%s/.noip", home());
e397f0bd 1589 D( fprintf(stderr, "noip(%d): config file: %s\n", pid, p); )
4ab301de 1590
1591 if ((fp = fopen(p, "r")) == 0) {
e397f0bd
MW
1592 D( fprintf(stderr, "noip(%d): couldn't read config: %s\n",
1593 pid, strerror(errno)); )
f6049fdd 1594 goto done;
4ab301de 1595 }
e4976bb0 1596 while (fgets(buf, sizeof(buf), fp)) {
1597 n = strlen(buf);
1598 p = buf;
1599
1600 SKIPSPC;
1601 if (!*p || *p == '#') continue;
1602 while (n && isspace(UC(buf[n - 1]))) n--;
1603 buf[n] = 0;
1604 NEXTWORD(cmd);
1605 SKIPSPC;
1606
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);
7be80f86
MW
1613 else if (strcmp(cmd, "impbind") == 0)
1614 parse_impbind_line(&p);
f6049fdd 1615 else if (strcmp(cmd, "autoports") == 0)
1616 parse_autoports(&p);
e4976bb0 1617 else if (strcmp(cmd, "debug") == 0)
1618 debug = *p ? atoi(p) : 1;
1619 else
7be80f86 1620 D( fprintf(stderr, "noip(%d): bad config command %s\n", pid, cmd); )
e4976bb0 1621 }
1622 fclose(fp);
1623
1624done:
a6d9626b 1625 parse_acl_env("NOIP_REALBIND", &bind_tail);
1626 parse_acl_env("NOIP_REALCONNECT", &connect_tail);
7be80f86 1627 parse_impbind_env("NOIP_IMPBIND");
a6d9626b 1628 parse_acl_env("NOIP_REALBIND_AFTER", &bind_tail);
1629 parse_acl_env("NOIP_REALCONNECT_AFTER", &connect_tail);
7be80f86 1630 parse_impbind_env("NOIP_IMPBIND_AFTER");
e4976bb0 1631 *bind_tail = 0;
1632 *connect_tail = 0;
7be80f86 1633 *impbind_tail = 0;
a6d9626b 1634 if (!sockdir) sockdir = getenv("NOIP_SOCKETDIR");
e4976bb0 1635 if (!sockdir) {
1636 snprintf(buf, sizeof(buf), "%s/noip-%s", tmpdir(), user());
1637 sockdir = xstrdup(buf);
1638 }
e397f0bd
MW
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);
e4976bb0 1643 dump_acl(bind_real);
e397f0bd 1644 fprintf(stderr, "noip(%d): realconnect acl:\n", pid);
7be80f86
MW
1645 dump_acl(connect_real);
1646 fprintf(stderr, "noip(%d): impbind list:\n", pid);
1647 dump_impbind_list(); )
e4976bb0 1648}
1649
1d1ccf4f 1650/*----- Overridden system calls -------------------------------------------*/
e4976bb0 1651
dc3956b3
MW
1652static void dump_syserr(long rc)
1653 { fprintf(stderr, " => %ld (E%d)\n", rc, errno); }
1654
1655static void dump_sysresult(long rc)
1656{
1657 if (rc < 0) dump_syserr(rc);
1658 else fprintf(stderr, " => %ld\n", rc);
1659}
1660
1661static void dump_addrresult(long rc, const struct sockaddr *sa,
1662 socklen_t len)
1663{
1664 char addrbuf[ADDRBUFSZ];
1665
1666 if (rc < 0) dump_syserr(rc);
1667 else {
1668 fprintf(stderr, " => %ld [%s]\n", rc,
1669 present_sockaddr(sa, len, addrbuf, sizeof(addrbuf)));
1670 }
1671}
1672
e4976bb0 1673int socket(int pf, int ty, int proto)
1674{
dc3956b3
MW
1675 int sk;
1676
1677 D( fprintf(stderr, "noip(%d): SOCKET pf=%d, type=%d, proto=%d",
1678 getpid(), pf, ty, proto); )
1679
8ce11853 1680 switch (pf) {
9314b85a
MW
1681 default:
1682 if (!family_known_p(pf)) {
dc3956b3 1683 D( fprintf(stderr, " -> unknown; refuse\n"); )
9314b85a 1684 errno = EAFNOSUPPORT;
dc3956b3 1685 sk = -1;
9314b85a 1686 }
dc3956b3 1687 D( fprintf(stderr, " -> inet; substitute"); )
8ce11853
MW
1688 pf = PF_UNIX;
1689 proto = 0;
dc3956b3 1690 break;
8ce11853 1691 case PF_UNIX:
41c50995
MW
1692#ifdef PF_NETLINK
1693 case PF_NETLINK:
1694#endif
dc3956b3
MW
1695 D( fprintf(stderr, " -> safe; permit"); )
1696 break;
e4976bb0 1697 }
dc3956b3
MW
1698 sk = real_socket(pf, ty, proto);
1699 D( dump_sysresult(sk); )
1700 return (sk);
e4976bb0 1701}
1702
1703int socketpair(int pf, int ty, int proto, int *sk)
1704{
dc3956b3
MW
1705 int rc;
1706
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"); )
1711 else {
1712 D( fprintf(stderr, " -> inet; substitute"); )
e4976bb0 1713 pf = PF_UNIX;
1714 proto = 0;
1715 }
dc3956b3
MW
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]); )
1719 return (rc);
e4976bb0 1720}
1721
1722int bind(int sk, const struct sockaddr *sa, socklen_t len)
1723{
1724 struct sockaddr_un sun;
dc3956b3
MW
1725 int rc;
1726 Dpid;
e4976bb0 1727
dc3956b3
MW
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))); })
1731
1732 if (!family_known_p(sa->sa_family))
1733 D( fprintf(stderr, " -> unknown af; pass through"); )
1734 else {
1735 D( fprintf(stderr, " -> checking...\n"); )
e4976bb0 1736 PRESERVING_ERRNO({
9314b85a 1737 if (acl_allows_p(bind_real, sa)) {
86134bfe 1738 if (fixup_real_ip_socket(sk, sa->sa_family, 0))
e4976bb0 1739 return (-1);
1740 } else {
4b9d1fad 1741 encode_inet_addr(&sun, sa, ENCF_FRESH);
e4976bb0 1742 sa = SA(&sun);
1743 len = SUN_LEN(&sun);
1744 }
1745 });
dc3956b3 1746 D( fprintf(stderr, "noip(%d): BIND ...", pid); )
e4976bb0 1747 }
dc3956b3
MW
1748 rc = real_bind(sk, sa, len);
1749 D( dump_sysresult(rc); )
1750 return (rc);
e4976bb0 1751}
1752
1753int connect(int sk, const struct sockaddr *sa, socklen_t len)
1754{
1755 struct sockaddr_un sun;
53390eff 1756 int rc;
dc3956b3 1757 Dpid;
e4976bb0 1758
dc3956b3
MW
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))); })
1762
1763 if (!family_known_p(sa->sa_family)) {
1764 D( fprintf(stderr, " -> unknown af; pass through"); )
9314b85a 1765 rc = real_connect(sk, sa, len);
dc3956b3
MW
1766 } else {
1767 D( fprintf(stderr, " -> checking...\n"); )
9314b85a 1768 PRESERVING_ERRNO({
6e1fe695 1769 fixup_client_socket(sk, &sa, &len, &sun);
9314b85a 1770 });
dc3956b3 1771 D( fprintf(stderr, "noip(%d): CONNECT ...", pid); )
9314b85a
MW
1772 rc = real_connect(sk, sa, len);
1773 if (rc < 0) {
1774 switch (errno) {
1775 case ENOENT: errno = ECONNREFUSED; break;
6df6f816 1776 }
9314b85a 1777 }
53390eff 1778 }
dc3956b3 1779 D( dump_sysresult(rc); )
9314b85a 1780 return (rc);
e4976bb0 1781}
1782
1783ssize_t sendto(int sk, const void *buf, size_t len, int flags,
1784 const struct sockaddr *to, socklen_t tolen)
1785{
1786 struct sockaddr_un sun;
dc3956b3
MW
1787 ssize_t n;
1788 Dpid;
1789
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))); })
e4976bb0 1794
dc3956b3
MW
1795 if (!to)
1796 D( fprintf(stderr, " -> null address; leaving"); )
1797 else if (!family_known_p(to->sa_family))
1798 D( fprintf(stderr, " -> unknown af; pass through"); )
1799 else {
1800 D( fprintf(stderr, " -> checking...\n"); )
e4976bb0 1801 PRESERVING_ERRNO({
6e1fe695 1802 fixup_client_socket(sk, &to, &tolen, &sun);
e4976bb0 1803 });
dc3956b3 1804 D( fprintf(stderr, "noip(%d): SENDTO ...", pid); )
e4976bb0 1805 }
dc3956b3
MW
1806 n = real_sendto(sk, buf, len, flags, to, tolen);
1807 D( dump_sysresult(n); )
1808 return (n);
e4976bb0 1809}
1810
1811ssize_t recvfrom(int sk, void *buf, size_t len, int flags,
1812 struct sockaddr *from, socklen_t *fromlen)
1813{
1814 char sabuf[1024];
1815 socklen_t mylen = sizeof(sabuf);
1816 ssize_t n;
dc3956b3 1817 Dpid;
e4976bb0 1818
dc3956b3
MW
1819 D( fprintf(stderr, "noip(%d): RECVFROM sk=%d, len=%lu, flags=%d",
1820 pid, sk, (unsigned long)len, flags); )
1821
1822 if (!from) {
1823 D( fprintf(stderr, " -> null addr; pass through"); )
1824 n = real_recvfrom(sk, buf, len, flags, 0, 0);
1825 } else {
6ec34720
MW
1826 n = real_recvfrom(sk, buf, len, flags, SA(sabuf), &mylen);
1827 if (n >= 0) {
1828 D( fprintf(stderr, " -> converting...\n"); )
1829 PRESERVING_ERRNO({
a62e4ece 1830 return_fake_peer(sk, SA(sabuf), mylen, from, fromlen);
6ec34720
MW
1831 });
1832 D( fprintf(stderr, "noip(%d): ... RECVFROM", pid); )
1833 }
dc3956b3
MW
1834 }
1835 D( dump_addrresult(n, from, fromlen ? *fromlen : 0); )
e4976bb0 1836 return (n);
1837}
1838
1839ssize_t sendmsg(int sk, const struct msghdr *msg, int flags)
1840{
1841 struct sockaddr_un sun;
dc3956b3 1842 const struct sockaddr *sa = SA(msg->msg_name);
e4976bb0 1843 struct msghdr mymsg;
dc3956b3
MW
1844 ssize_t n;
1845 Dpid;
e4976bb0 1846
dc3956b3
MW
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))); })
1853
1854 if (!sa)
1855 D( fprintf(stderr, " -> null address; leaving"); )
1856 else if (!family_known_p(sa->sa_family))
1857 D( fprintf(stderr, " -> unknown af; pass through"); )
1858 else {
1859 D( fprintf(stderr, " -> checking...\n"); )
e4976bb0 1860 PRESERVING_ERRNO({
e4976bb0 1861 mymsg = *msg;
6e1fe695 1862 fixup_client_socket(sk, &sa, &mymsg.msg_namelen, &sun);
e4976bb0 1863 mymsg.msg_name = SA(sa);
1864 msg = &mymsg;
1865 });
dc3956b3 1866 D( fprintf(stderr, "noip(%d): SENDMSG ...", pid); )
e4976bb0 1867 }
dc3956b3
MW
1868 n = real_sendmsg(sk, msg, flags);
1869 D( dump_sysresult(n); )
1870 return (n);
e4976bb0 1871}
1872
1873ssize_t recvmsg(int sk, struct msghdr *msg, int flags)
1874{
1875 char sabuf[1024];
dc3956b3
MW
1876 struct sockaddr *sa = SA(msg->msg_name);
1877 socklen_t len = msg->msg_namelen;
e4976bb0 1878 ssize_t n;
dc3956b3 1879 Dpid;
e4976bb0 1880
dc3956b3
MW
1881 D( fprintf(stderr, "noip(%d): RECVMSG sk=%d msg_flags=%d, ...",
1882 pid, sk, msg->msg_flags); )
1883
1884 if (!msg->msg_name) {
1885 D( fprintf(stderr, " -> null addr; pass through"); )
9314b85a 1886 return (real_recvmsg(sk, msg, flags));
dc3956b3 1887 } else {
6ec34720
MW
1888 msg->msg_name = sabuf;
1889 msg->msg_namelen = sizeof(sabuf);
1890 n = real_recvmsg(sk, msg, flags);
1891 if (n >= 0) {
1892 D( fprintf(stderr, " -> converting...\n"); )
1893 PRESERVING_ERRNO({
a62e4ece 1894 return_fake_peer(sk, SA(sabuf), msg->msg_namelen, sa, &len);
6ec34720
MW
1895 });
1896 }
1897 D( fprintf(stderr, "noip(%d): ... RECVMSG", pid); )
1898 msg->msg_name = sa;
1899 msg->msg_namelen = len;
dc3956b3
MW
1900 }
1901 D( dump_addrresult(n, sa, len); )
e4976bb0 1902 return (n);
1903}
1904
1905int accept(int sk, struct sockaddr *sa, socklen_t *len)
1906{
1907 char sabuf[1024];
1908 socklen_t mylen = sizeof(sabuf);
dc3956b3
MW
1909 int nsk;
1910 Dpid;
e4976bb0 1911
dc3956b3
MW
1912 D( fprintf(stderr, "noip(%d): ACCEPT sk=%d", pid, sk); )
1913
1914 nsk = real_accept(sk, SA(sabuf), &mylen);
1915 if (nsk < 0) /* failed */;
1916 else if (!sa) D( fprintf(stderr, " -> address not wanted"); )
1917 else {
1918 D( fprintf(stderr, " -> converting...\n"); )
a62e4ece 1919 return_fake_peer(sk, SA(sabuf), mylen, sa, len);
dc3956b3
MW
1920 D( fprintf(stderr, "noip(%d): ... ACCEPT", pid); )
1921 }
1922 D( dump_addrresult(nsk, sa, len ? *len : 0); )
e4976bb0 1923 return (nsk);
1924}
1925
1926int getsockname(int sk, struct sockaddr *sa, socklen_t *len)
1927{
0415c10e
MW
1928 char sabuf[1024];
1929 socklen_t mylen = sizeof(sabuf);
dc3956b3
MW
1930 int rc;
1931 Dpid;
1932
1933 D( fprintf(stderr, "noip(%d): GETSOCKNAME sk=%d", pid, sk); )
0415c10e
MW
1934 rc = real_getsockname(sk, SA(sabuf), &mylen);
1935 if (rc >= 0) {
1936 D( fprintf(stderr, " -> converting...\n"); )
a62e4ece 1937 return_fake_name(SA(sabuf), mylen, sa, len, 0);
0415c10e
MW
1938 D( fprintf(stderr, "noip(%d): ... GETSOCKNAME", pid); )
1939 }
dc3956b3
MW
1940 D( dump_addrresult(rc, sa, *len); )
1941 return (rc);
e4976bb0 1942}
1943
1944int getpeername(int sk, struct sockaddr *sa, socklen_t *len)
1945{
0415c10e
MW
1946 char sabuf[1024];
1947 socklen_t mylen = sizeof(sabuf);
dc3956b3
MW
1948 int rc;
1949 Dpid;
1950
1951 D( fprintf(stderr, "noip(%d): GETPEERNAME sk=%d", pid, sk); )
0415c10e
MW
1952 rc = real_getpeername(sk, SA(sabuf), &mylen);
1953 if (rc >= 0) {
1954 D( fprintf(stderr, " -> converting...\n"); )
a62e4ece 1955 return_fake_peer(sk, SA(sabuf), mylen, sa, len);
0415c10e
MW
1956 D( fprintf(stderr, "noip(%d): ... GETPEERNAME", pid); )
1957 }
dc3956b3 1958 D( dump_addrresult(rc, sa, *len); )
e4976bb0 1959 return (0);
1960}
1961
1962int getsockopt(int sk, int lev, int opt, void *p, socklen_t *len)
1963{
1964 switch (lev) {
e32758ea 1965 case IPPROTO_IP:
f47a2b17 1966 case IPPROTO_IPV6:
e32758ea
MW
1967 case IPPROTO_TCP:
1968 case IPPROTO_UDP:
e4976bb0 1969 if (*len > 0)
1970 memset(p, 0, *len);
1971 return (0);
1972 }
9314b85a 1973 return (real_getsockopt(sk, lev, opt, p, len));
e4976bb0 1974}
1975
1976int setsockopt(int sk, int lev, int opt, const void *p, socklen_t len)
1977{
1978 switch (lev) {
e32758ea 1979 case IPPROTO_IP:
f47a2b17 1980 case IPPROTO_IPV6:
e32758ea
MW
1981 case IPPROTO_TCP:
1982 case IPPROTO_UDP:
e4976bb0 1983 return (0);
1984 }
1985 switch (opt) {
1986 case SO_BINDTODEVICE:
1987 case SO_ATTACH_FILTER:
1988 case SO_DETACH_FILTER:
1989 return (0);
1990 }
9314b85a 1991 return (real_setsockopt(sk, lev, opt, p, len));
e4976bb0 1992}
1993
658c1774
MW
1994int ioctl(int fd, unsigned long op, ...)
1995{
1996 va_list ap;
1997 void *arg;
1998 int sk;
1999 int rc;
2000
2001 va_start(ap, op);
2002 arg = va_arg(ap, void *);
2003
2004 switch (op) {
2005 case SIOCGIFADDR:
2006 case SIOCGIFBRDADDR:
2007 case SIOCGIFDSTADDR:
2008 case SIOCGIFNETMASK:
2009 PRESERVING_ERRNO({
2010 if (fixup_real_ip_socket(fd, AF_INET, &sk)) goto real;
2011 });
2012 rc = real_ioctl(sk, op, arg);
2013 PRESERVING_ERRNO({ close(sk); });
2014 break;
2015 default:
2016 real:
2017 rc = real_ioctl(fd, op, arg);
2018 break;
2019 }
2020 va_end(ap);
2021 return (rc);
2022}
2023
1d1ccf4f 2024/*----- Initialization ----------------------------------------------------*/
e4976bb0 2025
1d1ccf4f 2026/* Clean up the socket directory, deleting stale sockets. */
e4976bb0 2027static void cleanup_sockdir(void)
2028{
2029 DIR *dir;
2030 struct dirent *d;
9314b85a 2031 address addr;
e4976bb0 2032 struct sockaddr_un sun;
3ef1fec9 2033 struct stat st;
e397f0bd 2034 Dpid;
e4976bb0 2035
9314b85a 2036 if ((dir = opendir(sockdir)) == 0) return;
4ab301de 2037 sun.sun_family = AF_UNIX;
e4976bb0 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);
9314b85a 2042 if (decode_inet_addr(&addr.sa, 0, &sun, SUN_LEN(&sun)) ||
3ef1fec9 2043 stat(sun.sun_path, &st) ||
4ab301de 2044 !S_ISSOCK(st.st_mode)) {
e397f0bd
MW
2045 D( fprintf(stderr, "noip(%d): ignoring unknown socketdir entry `%s'\n",
2046 pid, sun.sun_path); )
3ef1fec9 2047 continue;
4ab301de 2048 }
e4976bb0 2049 if (unix_socket_status(&sun, 0) == STALE) {
e397f0bd
MW
2050 D( fprintf(stderr, "noip(%d): clearing away stale socket %s\n",
2051 pid, d->d_name); )
e4976bb0 2052 unlink(sun.sun_path);
2053 }
2054 }
2055 closedir(dir);
2056}
2057
1d1ccf4f
MW
2058/* Find the addresses attached to local network interfaces, and remember them
2059 * in a table.
2060 */
e4976bb0 2061static void get_local_ipaddrs(void)
2062{
9f1396d9 2063 struct ifaddrs *ifa_head, *ifa;
9314b85a 2064 ipaddr a;
e4976bb0 2065 int i;
e397f0bd 2066 Dpid;
e4976bb0 2067
e397f0bd 2068 D( fprintf(stderr, "noip(%d): fetching local addresses...\n", pid); )
9f1396d9
MW
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) {
9314b85a 2073 if (!ifa->ifa_addr || !family_known_p(ifa->ifa_addr->sa_family))
e4976bb0 2074 continue;
9314b85a
MW
2075 ipaddr_from_sockaddr(&a, ifa->ifa_addr);
2076 D({ char buf[ADDRBUFSZ];
e397f0bd
MW
2077 fprintf(stderr, "noip(%d): local addr %s = %s", pid,
2078 ifa->ifa_name,
9314b85a
MW
2079 inet_ntop(ifa->ifa_addr->sa_family, &a,
2080 buf, sizeof(buf))); })
9f1396d9 2081 for (i = 0; i < n_local_ipaddrs; i++) {
9314b85a
MW
2082 if (ifa->ifa_addr->sa_family == local_ipaddrs[i].af &&
2083 ipaddr_equal_p(local_ipaddrs[i].af, &a, &local_ipaddrs[i].addr)) {
9f1396d9
MW
2084 D( fprintf(stderr, " (duplicate)\n"); )
2085 goto skip;
2086 }
2087 }
2088 D( fprintf(stderr, "\n"); )
9314b85a
MW
2089 local_ipaddrs[n_local_ipaddrs].af = ifa->ifa_addr->sa_family;
2090 local_ipaddrs[n_local_ipaddrs].addr = a;
9f1396d9
MW
2091 n_local_ipaddrs++;
2092 skip:;
e4976bb0 2093 }
9f1396d9 2094 freeifaddrs(ifa_head);
e4976bb0 2095}
2096
1d1ccf4f 2097/* Print the given message to standard error. Avoids stdio. */
72d85cdb 2098static void printerr(const char *p)
65f3786c 2099 { if (write(STDERR_FILENO, p, strlen(p))) ; }
3ef1fec9 2100
1d1ccf4f 2101/* Create the socket directory, being careful about permissions. */
3ef1fec9 2102static void create_sockdir(void)
2103{
2104 struct stat st;
2105
b514afdd 2106 if (lstat(sockdir, &st)) {
3ef1fec9 2107 if (errno == ENOENT) {
2108 if (mkdir(sockdir, 0700)) {
2109 perror("noip: creating socketdir");
2110 exit(127);
2111 }
b514afdd 2112 if (!lstat(sockdir, &st))
3ef1fec9 2113 goto check;
2114 }
2115 perror("noip: checking socketdir");
2116 exit(127);
2117 }
2118check:
2119 if (!S_ISDIR(st.st_mode)) {
2120 printerr("noip: bad socketdir: not a directory\n");
2121 exit(127);
2122 }
2123 if (st.st_uid != uid) {
2124 printerr("noip: bad socketdir: not owner\n");
2125 exit(127);
2126 }
2127 if (st.st_mode & 077) {
2128 printerr("noip: bad socketdir: not private\n");
2129 exit(127);
2130 }
2131}
2132
1d1ccf4f
MW
2133/* Initialization function. */
2134static void setup(void) __attribute__((constructor));
e4976bb0 2135static void setup(void)
2136{
2137 PRESERVING_ERRNO({
2138 char *p;
2139
2140 import();
3ef1fec9 2141 uid = geteuid();
e4976bb0 2142 if ((p = getenv("NOIP_DEBUG")) && atoi(p))
2143 debug = 1;
2144 get_local_ipaddrs();
2145 readconfig();
3ef1fec9 2146 create_sockdir();
e4976bb0 2147 cleanup_sockdir();
2148 });
2149}
1d1ccf4f
MW
2150
2151/*----- That's all, folks -------------------------------------------------*/