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