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