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