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