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