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