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