chiark / gitweb /
noip.c (acl_allows_p): Check that the ACL node address family is right.
[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 (a->af == sa->sa_family &&
601         sockaddr_in_range_p(sa, &a->minaddr, &a->maxaddr) &&
602         a->minport <= port && port <= a->maxport) {
603       D( fprintf(stderr, "noip(%d): aha!  %s\n", pid,
604                  a->act ? "ALLOW" : "DENY"); )
605       return (a->act);
606     }
607     act = a->act;
608   }
609   D( fprintf(stderr, "noip(%d): nothing found: %s\n", pid,
610              act ? "DENY" : "ALLOW"); )
611   return (!act);
612 }
613
614 /*----- Socket address conversion -----------------------------------------*/
615
616 /* Return a uniformly distributed integer between MIN and MAX inclusive. */
617 static unsigned randrange(unsigned min, unsigned max)
618 {
619   unsigned mask, i;
620
621   /* It's so nice not to have to care about the quality of the generator
622    * much!
623    */
624   max -= min;
625   for (mask = 1; mask < max; mask = (mask << 1) | 1)
626     ;
627   do i = rand() & mask; while (i > max);
628   return (i + min);
629 }
630
631 /* Return the status of Unix-domain socket address SUN.  Returns: UNUSED if
632  * the socket doesn't exist; USED if the path refers to an active socket, or
633  * isn't really a socket at all, or we can't tell without a careful search
634  * and QUICKP is set; or STALE if the file refers to a socket which isn't
635  * being used any more.
636  */
637 static int unix_socket_status(struct sockaddr_un *sun, int quickp)
638 {
639   struct stat st;
640   FILE *fp = 0;
641   size_t len, n;
642   int rc;
643   char buf[256];
644
645   if (stat(sun->sun_path, &st))
646     return (errno == ENOENT ? UNUSED : USED);
647   if (!S_ISSOCK(st.st_mode) || quickp)
648     return (USED);
649   rc = USED;
650   if ((fp = fopen("/proc/net/unix", "r")) == 0)
651     goto done;
652   if (!fgets(buf, sizeof(buf), fp)) goto done; /* skip header */
653   len = strlen(sun->sun_path);
654   while (fgets(buf, sizeof(buf), fp)) {
655     n = strlen(buf);
656     if (n >= len + 2 && buf[n - len - 2] == ' ' && buf[n - 1] == '\n' &&
657         memcmp(buf + n - len - 1, sun->sun_path, len) == 0)
658       goto done;
659   }
660   if (ferror(fp))
661     goto done;
662   rc = STALE;
663 done:
664   if (fp) fclose(fp);
665   return (rc);
666 }
667
668 /* Convert the IP address SA to a Unix-domain address SUN.  Fail if the
669  * address seems already taken.  If DESPARATEP then try cleaning up stale old
670  * sockets.
671  */
672 static int encode_unused_inet_addr(struct sockaddr *sa,
673                                    struct sockaddr_un *sun,
674                                    int desperatep)
675 {
676   address waddr;
677   struct sockaddr_un wsun;
678   int rc;
679   char buf[ADDRBUFSZ];
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_from_sockaddr(sa));
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 WANT is
697  * WANT_FRESH, and SA's port number is zero, then we pick an arbitrary local
698  * port.  Otherwise we pick the port given.  There's an unpleasant hack to
699  * find servers bound to local wildcard addresses.  Returns zero on success;
700  * -1 on failure.
701  */
702 static int encode_inet_addr(struct sockaddr_un *sun,
703                             const struct sockaddr *sa,
704                             int want)
705 {
706   int i;
707   int desperatep = 0;
708   address addr;
709   char buf[ADDRBUFSZ];
710   int rc;
711
712   D( fprintf(stderr, "noip(%d): encode %s (%s)", getpid(),
713              present_sockaddr(sa, 0, buf, sizeof(buf)),
714              want == WANT_EXISTING ? "EXISTING" : "FRESH"); )
715   sun->sun_family = AF_UNIX;
716   if (port_from_sockaddr(sa) || want == WANT_EXISTING) {
717     snprintf(sun->sun_path, sizeof(sun->sun_path), "%s/%s", sockdir,
718              present_sockaddr(sa, 0, buf, sizeof(buf)));
719     rc = unix_socket_status(sun, 0);
720     if (rc == STALE) unlink(sun->sun_path);
721     if (rc != USED && want == WANT_EXISTING) {
722       wildcard_address(sa->sa_family, &addr.sa);
723       port_to_sockaddr(&addr.sa, port_from_sockaddr(sa));
724       snprintf(sun->sun_path, sizeof(sun->sun_path), "%s/%s", sockdir,
725                present_sockaddr(&addr.sa, 0, buf, sizeof(buf)));
726       if (unix_socket_status(sun, 0) == STALE) unlink(sun->sun_path);
727     }
728   } else {
729     copy_sockaddr(&addr.sa, sa);
730     for (i = 0; i < 10; i++) {
731       port_to_sockaddr(&addr.sa, randrange(minautoport, maxautoport));
732       if (!encode_unused_inet_addr(&addr.sa, sun, 0)) goto found;
733     }
734     for (desperatep = 0; desperatep < 2; desperatep++) {
735       for (i = minautoport; i <= maxautoport; i++) {
736         port_to_sockaddr(&addr.sa, i);
737         if (!encode_unused_inet_addr(&addr.sa, sun, 0)) goto found;
738       }
739     }
740     errno = EADDRINUSE;
741     D( fprintf(stderr, " -- can't resolve\n"); )
742     return (-1);
743   found:;
744   }
745   D( fprintf(stderr, " -> `%s'\n", sun->sun_path); )
746   return (0);
747 }
748
749 /* Decode the Unix address SUN to an Internet address SIN.  If AF_HINT is
750  * nonzero, an empty address (indicative of an unbound Unix-domain socket) is
751  * translated to a wildcard Internet address of the appropriate family.
752  * Returns zero on success; -1 on failure (e.g., it wasn't one of our
753  * addresses).
754  */
755 static int decode_inet_addr(struct sockaddr *sa, int af_hint,
756                             const struct sockaddr_un *sun,
757                             socklen_t len)
758 {
759   char buf[ADDRBUFSZ];
760   size_t n = strlen(sockdir), nn;
761   address addr;
762
763   if (!sa) sa = &addr.sa;
764   if (sun->sun_family != AF_UNIX) return (-1);
765   if (len > sizeof(*sun)) return (-1);
766   ((char *)sun)[len] = 0;
767   nn = strlen(sun->sun_path);
768   D( fprintf(stderr, "noip(%d): decode `%s'", getpid(), sun->sun_path); )
769   if (af_hint && !sun->sun_path[0]) {
770     wildcard_address(af_hint, sa);
771     D( fprintf(stderr, " -- unbound socket\n"); )
772     return (0);
773   }
774   if (nn < n + 1 || nn - n >= sizeof(buf) || sun->sun_path[n] != '/' ||
775       memcmp(sun->sun_path, sockdir, n) != 0) {
776     D( fprintf(stderr, " -- not one of ours\n"); )
777     return (-1);
778   }
779   if (parse_sockaddr(sa, sun->sun_path + n + 1)) return (-1);
780   D( fprintf(stderr, " -> %s\n",
781              present_sockaddr(sa, 0, buf, sizeof(buf))); )
782   return (0);
783 }
784
785 /* SK is (or at least might be) a Unix-domain socket we created when an
786  * Internet socket was asked for.  We've decided it should be an Internet
787  * socket after all, with family AF_HINT, so convert it.  If TMP is not null,
788  * then don't replace the existing descriptor: store the new socket in *TMP
789  * and return zero.
790  */
791 static int fixup_real_ip_socket(int sk, int af_hint, int *tmp)
792 {
793   int nsk;
794   int type;
795   int f, fd;
796   struct sockaddr_un sun;
797   address addr;
798   socklen_t len;
799
800 #define OPTS(_)                                                         \
801   _(DEBUG, int)                                                         \
802   _(REUSEADDR, int)                                                     \
803   _(DONTROUTE, int)                                                     \
804   _(BROADCAST, int)                                                     \
805   _(SNDBUF, int)                                                        \
806   _(RCVBUF, int)                                                        \
807   _(OOBINLINE, int)                                                     \
808   _(NO_CHECK, int)                                                      \
809   _(LINGER, struct linger)                                              \
810   _(BSDCOMPAT, int)                                                     \
811   _(RCVLOWAT, int)                                                      \
812   _(RCVTIMEO, struct timeval)                                           \
813   _(SNDTIMEO, struct timeval)
814
815   len = sizeof(sun);
816   if (real_getsockname(sk, SA(&sun), &len))
817     return (-1);
818   if (decode_inet_addr(&addr.sa, af_hint, &sun, len))
819     return (0); /* Not one of ours */
820   len = sizeof(type);
821   if (real_getsockopt(sk, SOL_SOCKET, SO_TYPE, &type, &len) < 0 ||
822       (nsk = real_socket(addr.sa.sa_family, type, 0)) < 0)
823     return (-1);
824 #define FIX(opt, ty) do {                                               \
825   ty ov_;                                                               \
826   len = sizeof(ov_);                                                    \
827   if (real_getsockopt(sk, SOL_SOCKET, SO_##opt, &ov_, &len) < 0 ||      \
828       real_setsockopt(nsk, SOL_SOCKET, SO_##opt, &ov_, len)) {          \
829     close(nsk);                                                         \
830     return (-1);                                                        \
831   }                                                                     \
832 } while (0);
833   OPTS(FIX)
834 #undef FIX
835   if (tmp)
836     *tmp = nsk;
837   else {
838     if ((f = fcntl(sk, F_GETFL)) < 0 ||
839         (fd = fcntl(sk, F_GETFD)) < 0 ||
840         fcntl(nsk, F_SETFL, f) < 0 ||
841         dup2(nsk, sk) < 0) {
842       close(nsk);
843       return (-1);
844     }
845     unlink(sun.sun_path);
846     close(nsk);
847     if (fcntl(sk, F_SETFD, fd) < 0) {
848       perror("noip: fixup_real_ip_socket F_SETFD");
849       abort();
850     }
851   }
852   return (0);
853 }
854
855 /* We found the real address SA, with length LEN; if it's a Unix-domain
856  * address corresponding to a fake socket, convert it to cover up the
857  * deception.  Whatever happens, put the result at FAKE and store its length
858  * at FAKELEN.
859  */
860 static void return_fake_name(struct sockaddr *sa, socklen_t len,
861                              struct sockaddr *fake, socklen_t *fakelen)
862 {
863   address addr;
864   socklen_t alen;
865
866   if (sa->sa_family == AF_UNIX &&
867       !decode_inet_addr(&addr.sa, 0, SUN(sa), len)) {
868     sa = &addr.sa;
869     len = family_socklen(addr.sa.sa_family);
870   }
871   alen = len;
872   if (len > *fakelen) len = *fakelen;
873   if (len > 0) memcpy(fake, sa, len);
874   *fakelen = alen;
875 }
876
877 /*----- Implicit binding --------------------------------------------------*/
878
879 #ifdef DEBUG
880
881 static void dump_impbind(const impbind *i)
882 {
883   char buf[ADDRBUFSZ];
884
885   fprintf(stderr, "noip(%d):   ", getpid());
886   dump_addrrange(i->af, &i->minaddr, &i->maxaddr);
887   switch (i->how) {
888     case SAME: fprintf(stderr, " <self>"); break;
889     case EXPLICIT:
890       fprintf(stderr, " %s", inet_ntop(i->af, &i->bindaddr,
891                                        buf, sizeof(buf)));
892       break;
893     default: abort();
894   }
895   fputc('\n', stderr);
896 }
897
898 static void dump_impbind_list(void)
899 {
900   const impbind *i;
901
902   for (i = impbinds; i; i = i->next) dump_impbind(i);
903 }
904
905 #endif
906
907 /* The socket SK is about to be used to communicate with the remote address
908  * SA.  Assign it a local address so that getpeername(2) does something
909  * useful.
910  */
911 static int do_implicit_bind(int sk, const struct sockaddr **sa,
912                             socklen_t *len, struct sockaddr_un *sun)
913 {
914   address addr;
915   socklen_t mylen = sizeof(*sun);
916   const impbind *i;
917   Dpid;
918
919   if (acl_allows_p(connect_real, *sa)) {
920     if (fixup_real_ip_socket(sk, (*sa)->sa_family, 0)) return (-1);
921   } else {
922     if (real_getsockname(sk, SA(sun), &mylen) < 0) return (-1);
923     if (sun->sun_family == AF_UNIX) {
924       if (mylen < sizeof(*sun)) ((char *)sun)[mylen] = 0;
925       if (!sun->sun_path[0]) {
926         D( fprintf(stderr, "noip(%d): checking impbind list...\n", pid); )
927         for (i = impbinds; i; i = i->next) {
928           D( dump_impbind(i); )
929           if ((*sa)->sa_family == i->af &&
930               sockaddr_in_range_p(*sa, &i->minaddr, &i->maxaddr)) {
931             D( fprintf(stderr, "noip(%d): match!\n", pid); )
932             addr.sa.sa_family = (*sa)->sa_family;
933             ipaddr_to_sockaddr(&addr.sa, &i->bindaddr);
934             goto found;
935           }
936         }
937         D( fprintf(stderr, "noip(%d): no match; using wildcard\n", pid); )
938         wildcard_address((*sa)->sa_family, &addr.sa);
939       found:
940         encode_inet_addr(sun, &addr.sa, WANT_FRESH);
941         if (real_bind(sk, SA(sun), SUN_LEN(sun))) return (-1);
942       }
943       encode_inet_addr(sun, *sa, WANT_EXISTING);
944       *sa = SA(sun);
945       *len = SUN_LEN(sun);
946     }
947   }
948   return (0);
949 }
950
951 /*----- Configuration -----------------------------------------------------*/
952
953 /* Return the process owner's home directory. */
954 static char *home(void)
955 {
956   char *p;
957   struct passwd *pw;
958
959   if (getuid() == uid &&
960       (p = getenv("HOME")) != 0)
961     return (p);
962   else if ((pw = getpwuid(uid)) != 0)
963     return (pw->pw_dir);
964   else
965     return "/notexist";
966 }
967
968 /* Return a good temporary directory to use. */
969 static char *tmpdir(void)
970 {
971   char *p;
972
973   if ((p = getenv("TMPDIR")) != 0) return (p);
974   else if ((p = getenv("TMP")) != 0) return (p);
975   else return ("/tmp");
976 }
977
978 /* Return the user's name, or at least something distinctive. */
979 static char *user(void)
980 {
981   static char buf[16];
982   char *p;
983   struct passwd *pw;
984
985   if ((p = getenv("USER")) != 0) return (p);
986   else if ((p = getenv("LOGNAME")) != 0) return (p);
987   else if ((pw = getpwuid(uid)) != 0) return (pw->pw_name);
988   else {
989     snprintf(buf, sizeof(buf), "uid-%lu", (unsigned long)uid);
990     return (buf);
991   }
992 }
993
994 /* Skip P over space characters. */
995 #define SKIPSPC do { while (*p && isspace(UC(*p))) p++; } while (0)
996
997 /* Set Q to point to the next word following P, null-terminate it, and step P
998  * past it. */
999 #define NEXTWORD(q) do {                                                \
1000   SKIPSPC;                                                              \
1001   q = p;                                                                \
1002   while (*p && !isspace(UC(*p))) p++;                                   \
1003   if (*p) *p++ = 0;                                                     \
1004 } while (0)
1005
1006 /* Set Q to point to the next dotted-quad address, store the ending delimiter
1007  * in DEL, null-terminate it, and step P past it. */
1008 static void parse_nextaddr(char **pp, char **qq, int *del)
1009 {
1010   char *p = *pp;
1011
1012   SKIPSPC;
1013   if (*p == '[') {
1014     p++; SKIPSPC;
1015     *qq = p;
1016     p += strcspn(p, "]");
1017     if (*p) *p++ = 0;
1018     *del = 0;
1019   } else {
1020     *qq = p;
1021     while (*p && (*p == '.' || isdigit(UC(*p)))) p++;
1022     *del = *p;
1023     if (*p) *p++ = 0;
1024   }
1025   *pp = p;
1026 }
1027
1028 /* Set Q to point to the next decimal number, store the ending delimiter in
1029  * DEL, null-terminate it, and step P past it. */
1030 #define NEXTNUMBER(q, del) do {                                         \
1031   SKIPSPC;                                                              \
1032   q = p;                                                                \
1033   while (*p && isdigit(UC(*p))) p++;                                    \
1034   del = *p;                                                             \
1035   if (*p) *p++ = 0;                                                     \
1036 } while (0)
1037
1038 /* Push the character DEL back so we scan it again, unless it's zero
1039  * (end-of-file). */
1040 #define RESCAN(del) do { if (del) *--p = del; } while (0)
1041
1042 /* Evaluate true if P is pointing to the word KW (and not some longer string
1043  * of which KW is a prefix). */
1044
1045 #define KWMATCHP(kw) (strncmp(p, kw, sizeof(kw) - 1) == 0 &&            \
1046                       !isalnum(UC(p[sizeof(kw) - 1])) &&                \
1047                       (p += sizeof(kw) - 1))
1048
1049 /* Parse a port list, starting at *PP.  Port lists have the form
1050  * [:LOW[-HIGH]]: if omitted, all ports are included; if HIGH is omitted,
1051  * it's as if HIGH = LOW.  Store LOW in *MIN, HIGH in *MAX and set *PP to the
1052  * rest of the string.
1053  */
1054 static void parse_ports(char **pp, unsigned short *min, unsigned short *max)
1055 {
1056   char *p = *pp, *q;
1057   int del;
1058
1059   SKIPSPC;
1060   if (*p != ':')
1061     { *min = 0; *max = 0xffff; }
1062   else {
1063     p++;
1064     NEXTNUMBER(q, del); *min = strtoul(q, 0, 0); RESCAN(del);
1065     SKIPSPC;
1066     if (*p == '-')
1067       { p++; NEXTNUMBER(q, del); *max = strtoul(q, 0, 0); RESCAN(del); }
1068     else
1069       *max = *min;
1070   }
1071   *pp = p;
1072 }
1073
1074 /* Parse an address range designator starting at PP and store a
1075  * representation of it in R.  An address range designator has the form:
1076  *
1077  *      any | local | ADDR | ADDR - ADDR | ADDR/ADDR | ADDR/INT
1078  */
1079 static int parse_addrrange(char **pp, addrrange *r)
1080 {
1081   char *p = *pp, *q;
1082   int n;
1083   int del;
1084   int af;
1085
1086   SKIPSPC;
1087   if (KWMATCHP("any")) r->type = ANY;
1088   else if (KWMATCHP("local")) r->type = LOCAL;
1089   else {
1090     parse_nextaddr(&p, &q, &del);
1091     af = guess_address_family(q);
1092     if (inet_pton(af, q, &r->u.range.min) <= 0) goto bad;
1093     RESCAN(del);
1094     SKIPSPC;
1095     if (*p == '-') {
1096       p++;
1097       parse_nextaddr(&p, &q, &del);
1098       if (inet_pton(af, q, &r->u.range.max) <= 0) goto bad;
1099       RESCAN(del);
1100     } else if (*p == '/') {
1101       p++;
1102       NEXTNUMBER(q, del);
1103       n = strtoul(q, 0, 0);
1104       r->u.range.max = r->u.range.min;
1105       mask_address(af, &r->u.range.min, n, 0);
1106       mask_address(af, &r->u.range.max, n, 1);
1107       RESCAN(del);
1108     } else
1109       r->u.range.max = r->u.range.min;
1110     r->type = RANGE;
1111     r->u.range.af = af;
1112   }
1113   *pp = p;
1114   return (0);
1115
1116 bad:
1117   return (-1);
1118 }
1119
1120 /* Call FUNC on each individual address range in R. */
1121 static void foreach_addrrange(const addrrange *r,
1122                               void (*func)(int af,
1123                                            const ipaddr *min,
1124                                            const ipaddr *max,
1125                                            void *p),
1126                               void *p)
1127 {
1128   ipaddr minaddr, maxaddr;
1129   int i, af;
1130
1131   switch (r->type) {
1132     case EMPTY:
1133       break;
1134     case ANY:
1135       for (i = 0; address_families[i] >= 0; i++) {
1136         af = address_families[i];
1137         memset(&minaddr, 0, sizeof(minaddr));
1138         maxaddr = minaddr; mask_address(af, &maxaddr, 0, 1);
1139         func(af, &minaddr, &maxaddr, p);
1140       }
1141       break;
1142     case LOCAL:
1143       for (i = 0; address_families[i] >= 0; i++) {
1144         af = address_families[i];
1145         memset(&minaddr, 0, sizeof(minaddr));
1146         maxaddr = minaddr; mask_address(af, &maxaddr, 0, 1);
1147         func(af, &minaddr, &minaddr, p);
1148         func(af, &maxaddr, &maxaddr, p);
1149       }
1150       for (i = 0; i < n_local_ipaddrs; i++) {
1151         func(local_ipaddrs[i].af,
1152              &local_ipaddrs[i].addr, &local_ipaddrs[i].addr,
1153              p);
1154       }
1155       break;
1156     case RANGE:
1157       func(r->u.range.af, &r->u.range.min, &r->u.range.max, p);
1158       break;
1159     default:
1160       abort();
1161   }
1162 }
1163
1164 struct add_aclnode_ctx {
1165   int act;
1166   unsigned short minport, maxport;
1167   aclnode ***tail;
1168 };
1169
1170 static void add_aclnode(int af, const ipaddr *min, const ipaddr *max,
1171                         void *p)
1172 {
1173   struct add_aclnode_ctx *ctx = p;
1174   aclnode *a;
1175
1176   NEW(a);
1177   a->act = ctx->act;
1178   a->af = af;
1179   a->minaddr = *min; a->maxaddr = *max;
1180   a->minport = ctx->minport; a->maxport = ctx->maxport;
1181   **ctx->tail = a; *ctx->tail = &a->next;
1182 }
1183
1184 /* Parse an ACL line.  *PP points to the end of the line; *TAIL points to
1185  * the list tail (i.e., the final link in the list).  An ACL entry has the
1186  * form +|- ADDR-RANGE PORTS
1187  * where PORTS is parsed by parse_ports above; an ACL line consists of a
1188  * comma-separated sequence of entries..
1189  */
1190 static void parse_acl_line(char **pp, aclnode ***tail)
1191 {
1192   struct add_aclnode_ctx ctx;
1193   addrrange r;
1194   char *p = *pp;
1195
1196   ctx.tail = tail;
1197   for (;;) {
1198     SKIPSPC;
1199     if (*p == '+') ctx.act = ALLOW;
1200     else if (*p == '-') ctx.act = DENY;
1201     else goto bad;
1202
1203     p++;
1204     if (parse_addrrange(&p, &r)) goto bad;
1205     parse_ports(&p, &ctx.minport, &ctx.maxport);
1206     foreach_addrrange(&r, add_aclnode, &ctx);
1207     SKIPSPC;
1208     if (*p != ',') break;
1209     if (*p) p++;
1210   }
1211   if (*p) goto bad;
1212   *pp = p;
1213   return;
1214
1215 bad:
1216   D( fprintf(stderr, "noip(%d): bad acl spec (ignored)\n", getpid()); )
1217   return;
1218 }
1219
1220 /* Parse an ACL from an environment variable VAR, attaching it to the list
1221  * TAIL.
1222  */
1223 static void parse_acl_env(const char *var, aclnode ***tail)
1224 {
1225   char *p, *q;
1226
1227   if ((p = getenv(var)) != 0) {
1228     p = q = xstrdup(p);
1229     parse_acl_line(&q, tail);
1230     free(p);
1231   }
1232 }
1233
1234 struct add_impbind_ctx {
1235   int af, how;
1236   ipaddr addr;
1237 };
1238
1239 static void add_impbind(int af, const ipaddr *min, const ipaddr *max,
1240                         void *p)
1241 {
1242   struct add_impbind_ctx *ctx = p;
1243   impbind *i;
1244
1245   if (ctx->af && af != ctx->af) return;
1246   NEW(i);
1247   i->af = af;
1248   i->how = ctx->how;
1249   i->minaddr = *min; i->maxaddr = *max;
1250   switch (ctx->how) {
1251     case EXPLICIT: i->bindaddr = ctx->addr;
1252     case SAME: break;
1253     default: abort();
1254   }
1255   *impbind_tail = i; impbind_tail = &i->next;
1256 }
1257
1258 /* Parse an implicit-bind line.  An implicit-bind entry has the form
1259  * ADDR-RANGE {ADDR | same}
1260  */
1261 static void parse_impbind_line(char **pp)
1262 {
1263   struct add_impbind_ctx ctx;
1264   char *p = *pp, *q;
1265   addrrange r;
1266   int del;
1267
1268   for (;;) {
1269     if (parse_addrrange(&p, &r)) goto bad;
1270     SKIPSPC;
1271     if (KWMATCHP("same")) {
1272       ctx.how = SAME;
1273       ctx.af = 0;
1274     } else {
1275       ctx.how = EXPLICIT;
1276       parse_nextaddr(&p, &q, &del);
1277       ctx.af = guess_address_family(q);
1278       if (inet_pton(ctx.af, q, &ctx.addr) < 0) goto bad;
1279       RESCAN(del);
1280     }
1281     foreach_addrrange(&r, add_impbind, &ctx);
1282     SKIPSPC;
1283     if (*p != ',') break;
1284     if (*p) p++;
1285   }
1286   if (*p) goto bad;
1287   *pp = p;
1288   return;
1289
1290 bad:
1291   D( fprintf(stderr, "noip(%d): bad implicit-bind spec (ignored)\n",
1292              getpid()); )
1293   return;
1294 }
1295
1296 /* Parse implicit-bind instructions from an environment variable VAR,
1297  * attaching it to the list.
1298  */
1299 static void parse_impbind_env(const char *var)
1300 {
1301   char *p, *q;
1302
1303   if ((p = getenv(var)) != 0) {
1304     p = q = xstrdup(p);
1305     parse_impbind_line(&q);
1306     free(p);
1307   }
1308 }
1309
1310 /* Parse the autoports configuration directive.  Syntax is MIN - MAX. */
1311 static void parse_autoports(char **pp)
1312 {
1313   char *p = *pp, *q;
1314   unsigned x, y;
1315   int del;
1316
1317   SKIPSPC;
1318   NEXTNUMBER(q, del); x = strtoul(q, 0, 0); RESCAN(del);
1319   SKIPSPC;
1320   if (*p != '-') goto bad;
1321   p++;
1322   NEXTNUMBER(q, del); y = strtoul(q, 0, 0); RESCAN(del);
1323   minautoport = x; maxautoport = y;
1324   SKIPSPC; if (*p) goto bad;
1325   *pp = p;
1326   return;
1327
1328 bad:
1329   D( fprintf(stderr, "noip(%d): bad port range (ignored)\n", getpid()); )
1330   return;
1331 }
1332
1333 /* Read the configuration from the config file and environment. */
1334 static void readconfig(void)
1335 {
1336   FILE *fp;
1337   char buf[1024];
1338   size_t n;
1339   char *p, *q, *cmd;
1340   Dpid;
1341
1342   parse_acl_env("NOIP_REALBIND_BEFORE", &bind_tail);
1343   parse_acl_env("NOIP_REALCONNECT_BEFORE", &connect_tail);
1344   parse_impbind_env("NOIP_IMPBIND_BEFORE");
1345   if ((p = getenv("NOIP_AUTOPORTS")) != 0) {
1346     p = q = xstrdup(p);
1347     parse_autoports(&q);
1348     free(p);
1349   }
1350   if ((p = getenv("NOIP_CONFIG")) == 0)
1351     snprintf(p = buf, sizeof(buf), "%s/.noip", home());
1352   D( fprintf(stderr, "noip(%d): config file: %s\n", pid, p); )
1353
1354   if ((fp = fopen(p, "r")) == 0) {
1355     D( fprintf(stderr, "noip(%d): couldn't read config: %s\n",
1356                pid, strerror(errno)); )
1357     goto done;
1358   }
1359   while (fgets(buf, sizeof(buf), fp)) {
1360     n = strlen(buf);
1361     p = buf;
1362
1363     SKIPSPC;
1364     if (!*p || *p == '#') continue;
1365     while (n && isspace(UC(buf[n - 1]))) n--;
1366     buf[n] = 0;
1367     NEXTWORD(cmd);
1368     SKIPSPC;
1369
1370     if (strcmp(cmd, "socketdir") == 0)
1371       sockdir = xstrdup(p);
1372     else if (strcmp(cmd, "realbind") == 0)
1373       parse_acl_line(&p, &bind_tail);
1374     else if (strcmp(cmd, "realconnect") == 0)
1375       parse_acl_line(&p, &connect_tail);
1376     else if (strcmp(cmd, "impbind") == 0)
1377       parse_impbind_line(&p);
1378     else if (strcmp(cmd, "autoports") == 0)
1379       parse_autoports(&p);
1380     else if (strcmp(cmd, "debug") == 0)
1381       debug = *p ? atoi(p) : 1;
1382     else
1383       D( fprintf(stderr, "noip(%d): bad config command %s\n", pid, cmd); )
1384   }
1385   fclose(fp);
1386
1387 done:
1388   parse_acl_env("NOIP_REALBIND", &bind_tail);
1389   parse_acl_env("NOIP_REALCONNECT", &connect_tail);
1390   parse_impbind_env("NOIP_IMPBIND");
1391   parse_acl_env("NOIP_REALBIND_AFTER", &bind_tail);
1392   parse_acl_env("NOIP_REALCONNECT_AFTER", &connect_tail);
1393   parse_impbind_env("NOIP_IMPBIND_AFTER");
1394   *bind_tail = 0;
1395   *connect_tail = 0;
1396   *impbind_tail = 0;
1397   if (!sockdir) sockdir = getenv("NOIP_SOCKETDIR");
1398   if (!sockdir) {
1399     snprintf(buf, sizeof(buf), "%s/noip-%s", tmpdir(), user());
1400     sockdir = xstrdup(buf);
1401   }
1402   D( fprintf(stderr, "noip(%d): socketdir: %s\n", pid, sockdir);
1403      fprintf(stderr, "noip(%d): autoports: %u-%u\n",
1404              pid, minautoport, maxautoport);
1405      fprintf(stderr, "noip(%d): realbind acl:\n", pid);
1406      dump_acl(bind_real);
1407      fprintf(stderr, "noip(%d): realconnect acl:\n", pid);
1408      dump_acl(connect_real);
1409      fprintf(stderr, "noip(%d): impbind list:\n", pid);
1410      dump_impbind_list(); )
1411 }
1412
1413 /*----- Overridden system calls -------------------------------------------*/
1414
1415 static void dump_syserr(long rc)
1416   { fprintf(stderr, " => %ld (E%d)\n", rc, errno); }
1417
1418 static void dump_sysresult(long rc)
1419 {
1420   if (rc < 0) dump_syserr(rc);
1421   else fprintf(stderr, " => %ld\n", rc);
1422 }
1423
1424 static void dump_addrresult(long rc, const struct sockaddr *sa,
1425                             socklen_t len)
1426 {
1427   char addrbuf[ADDRBUFSZ];
1428
1429   if (rc < 0) dump_syserr(rc);
1430   else {
1431     fprintf(stderr, " => %ld [%s]\n", rc,
1432             present_sockaddr(sa, len, addrbuf, sizeof(addrbuf)));
1433   }
1434 }
1435
1436 int socket(int pf, int ty, int proto)
1437 {
1438   int sk;
1439
1440   D( fprintf(stderr, "noip(%d): SOCKET pf=%d, type=%d, proto=%d",
1441              getpid(), pf, ty, proto); )
1442
1443   switch (pf) {
1444     default:
1445       if (!family_known_p(pf)) {
1446         D( fprintf(stderr, " -> unknown; refuse\n"); )
1447         errno = EAFNOSUPPORT;
1448         sk = -1;
1449       }
1450       D( fprintf(stderr, " -> inet; substitute"); )
1451       pf = PF_UNIX;
1452       proto = 0;
1453       break;
1454     case PF_UNIX:
1455 #ifdef PF_NETLINK
1456     case PF_NETLINK:
1457 #endif
1458       D( fprintf(stderr, " -> safe; permit"); )
1459       break;
1460   }
1461   sk = real_socket(pf, ty, proto);
1462   D( dump_sysresult(sk); )
1463   return (sk);
1464 }
1465
1466 int socketpair(int pf, int ty, int proto, int *sk)
1467 {
1468   int rc;
1469
1470   D( fprintf(stderr, "noip(%d): SOCKETPAIR pf=%d, type=%d, proto=%d",
1471              getpid(), pf, ty, proto); )
1472   if (!family_known_p(pf))
1473     D( fprintf(stderr, " -> unknown; permit"); )
1474   else {
1475     D( fprintf(stderr, " -> inet; substitute"); )
1476     pf = PF_UNIX;
1477     proto = 0;
1478   }
1479   rc = real_socketpair(pf, ty, proto, sk);
1480   D( if (rc < 0) dump_syserr(rc);
1481      else fprintf(stderr, " => %d (%d, %d)\n", rc, sk[0], sk[1]); )
1482   return (rc);
1483 }
1484
1485 int bind(int sk, const struct sockaddr *sa, socklen_t len)
1486 {
1487   struct sockaddr_un sun;
1488   int rc;
1489   Dpid;
1490
1491   D({ char buf[ADDRBUFSZ];
1492       fprintf(stderr, "noip(%d): BIND sk=%d, sa[%d]=%s", pid,
1493               sk, len, present_sockaddr(sa, len, buf, sizeof(buf))); })
1494
1495   if (!family_known_p(sa->sa_family))
1496     D( fprintf(stderr, " -> unknown af; pass through"); )
1497   else {
1498     D( fprintf(stderr, " -> checking...\n"); )
1499     PRESERVING_ERRNO({
1500       if (acl_allows_p(bind_real, sa)) {
1501         if (fixup_real_ip_socket(sk, sa->sa_family, 0))
1502           return (-1);
1503       } else {
1504         encode_inet_addr(&sun, sa, WANT_FRESH);
1505         sa = SA(&sun);
1506         len = SUN_LEN(&sun);
1507       }
1508     });
1509     D( fprintf(stderr, "noip(%d): BIND ...", pid); )
1510   }
1511   rc = real_bind(sk, sa, len);
1512   D( dump_sysresult(rc); )
1513   return (rc);
1514 }
1515
1516 int connect(int sk, const struct sockaddr *sa, socklen_t len)
1517 {
1518   struct sockaddr_un sun;
1519   int rc;
1520   Dpid;
1521
1522   D({ char buf[ADDRBUFSZ];
1523       fprintf(stderr, "noip(%d): CONNECT sk=%d, sa[%d]=%s", pid,
1524               sk, len, present_sockaddr(sa, len, buf, sizeof(buf))); })
1525
1526   if (!family_known_p(sa->sa_family)) {
1527     D( fprintf(stderr, " -> unknown af; pass through"); )
1528     rc = real_connect(sk, sa, len);
1529   } else {
1530     D( fprintf(stderr, " -> checking...\n"); )
1531     PRESERVING_ERRNO({
1532       do_implicit_bind(sk, &sa, &len, &sun);
1533     });
1534     D( fprintf(stderr, "noip(%d): CONNECT ...", pid); )
1535     rc = real_connect(sk, sa, len);
1536     if (rc < 0) {
1537       switch (errno) {
1538         case ENOENT: errno = ECONNREFUSED; break;
1539       }
1540     }
1541   }
1542   D( dump_sysresult(rc); )
1543   return (rc);
1544 }
1545
1546 ssize_t sendto(int sk, const void *buf, size_t len, int flags,
1547                const struct sockaddr *to, socklen_t tolen)
1548 {
1549   struct sockaddr_un sun;
1550   ssize_t n;
1551   Dpid;
1552
1553   D({ char addrbuf[ADDRBUFSZ];
1554       fprintf(stderr, "noip(%d): SENDTO sk=%d, len=%lu, flags=%d, to[%d]=%s",
1555               pid, sk, (unsigned long)len, flags, tolen,
1556               present_sockaddr(to, tolen, addrbuf, sizeof(addrbuf))); })
1557
1558   if (!to)
1559     D( fprintf(stderr, " -> null address; leaving"); )
1560   else if (!family_known_p(to->sa_family))
1561     D( fprintf(stderr, " -> unknown af; pass through"); )
1562   else {
1563     D( fprintf(stderr, " -> checking...\n"); )
1564     PRESERVING_ERRNO({
1565       do_implicit_bind(sk, &to, &tolen, &sun);
1566     });
1567     D( fprintf(stderr, "noip(%d): SENDTO ...", pid); )
1568   }
1569   n = real_sendto(sk, buf, len, flags, to, tolen);
1570   D( dump_sysresult(n); )
1571   return (n);
1572 }
1573
1574 ssize_t recvfrom(int sk, void *buf, size_t len, int flags,
1575                  struct sockaddr *from, socklen_t *fromlen)
1576 {
1577   char sabuf[1024];
1578   socklen_t mylen = sizeof(sabuf);
1579   ssize_t n;
1580   Dpid;
1581
1582   D( fprintf(stderr, "noip(%d): RECVFROM sk=%d, len=%lu, flags=%d",
1583              pid, sk, (unsigned long)len, flags); )
1584
1585   if (!from) {
1586     D( fprintf(stderr, " -> null addr; pass through"); )
1587     n = real_recvfrom(sk, buf, len, flags, 0, 0);
1588   } else {
1589     PRESERVING_ERRNO({
1590       n = real_recvfrom(sk, buf, len, flags, SA(sabuf), &mylen);
1591       if (n >= 0) {
1592         D( fprintf(stderr, " -> converting...\n"); )
1593         return_fake_name(SA(sabuf), mylen, from, fromlen);
1594         D( fprintf(stderr, "noip(%d): ... RECVFROM", pid); )
1595       }
1596     });
1597   }
1598   D( dump_addrresult(n, from, fromlen ? *fromlen : 0); )
1599   return (n);
1600 }
1601
1602 ssize_t sendmsg(int sk, const struct msghdr *msg, int flags)
1603 {
1604   struct sockaddr_un sun;
1605   const struct sockaddr *sa = SA(msg->msg_name);
1606   struct msghdr mymsg;
1607   ssize_t n;
1608   Dpid;
1609
1610   D({ char addrbuf[ADDRBUFSZ];
1611       fprintf(stderr, "noip(%d): SENDMSG sk=%d, "
1612                       "msg_flags=%d, msg_name[%d]=%s, ...",
1613               pid, sk, msg->msg_flags, msg->msg_namelen,
1614               present_sockaddr(sa, msg->msg_namelen,
1615                                addrbuf, sizeof(addrbuf))); })
1616
1617   if (!sa)
1618     D( fprintf(stderr, " -> null address; leaving"); )
1619   else if (!family_known_p(sa->sa_family))
1620     D( fprintf(stderr, " -> unknown af; pass through"); )
1621   else {
1622     D( fprintf(stderr, " -> checking...\n"); )
1623     PRESERVING_ERRNO({
1624       mymsg = *msg;
1625       do_implicit_bind(sk, &sa, &mymsg.msg_namelen, &sun);
1626       mymsg.msg_name = SA(sa);
1627       msg = &mymsg;
1628     });
1629     D( fprintf(stderr, "noip(%d): SENDMSG ...", pid); )
1630   }
1631   n = real_sendmsg(sk, msg, flags);
1632   D( dump_sysresult(n); )
1633   return (n);
1634 }
1635
1636 ssize_t recvmsg(int sk, struct msghdr *msg, int flags)
1637 {
1638   char sabuf[1024];
1639   struct sockaddr *sa = SA(msg->msg_name);
1640   socklen_t len = msg->msg_namelen;
1641   ssize_t n;
1642   Dpid;
1643
1644   D( fprintf(stderr, "noip(%d): RECVMSG sk=%d msg_flags=%d, ...",
1645              pid, sk, msg->msg_flags); )
1646
1647   if (!msg->msg_name) {
1648     D( fprintf(stderr, " -> null addr; pass through"); )
1649     return (real_recvmsg(sk, msg, flags));
1650   } else {
1651     PRESERVING_ERRNO({
1652       msg->msg_name = sabuf;
1653       msg->msg_namelen = sizeof(sabuf);
1654       n = real_recvmsg(sk, msg, flags);
1655       if (n >= 0) {
1656         D( fprintf(stderr, " -> converting...\n"); )
1657         return_fake_name(SA(sabuf), msg->msg_namelen, sa, &len);
1658         D( fprintf(stderr, "noip(%d): ... RECVMSG", pid); )
1659       }
1660       msg->msg_name = sa;
1661       msg->msg_namelen = len;
1662     });
1663   }
1664   D( dump_addrresult(n, sa, len); )
1665   return (n);
1666 }
1667
1668 int accept(int sk, struct sockaddr *sa, socklen_t *len)
1669 {
1670   char sabuf[1024];
1671   socklen_t mylen = sizeof(sabuf);
1672   int nsk;
1673   Dpid;
1674
1675   D( fprintf(stderr, "noip(%d): ACCEPT sk=%d", pid, sk); )
1676
1677   nsk = real_accept(sk, SA(sabuf), &mylen);
1678   if (nsk < 0) /* failed */;
1679   else if (!sa) D( fprintf(stderr, " -> address not wanted"); )
1680   else {
1681     D( fprintf(stderr, " -> converting...\n"); )
1682     return_fake_name(SA(sabuf), mylen, sa, len);
1683     D( fprintf(stderr, "noip(%d): ... ACCEPT", pid); )
1684   }
1685   D( dump_addrresult(nsk, sa, len ? *len : 0); )
1686   return (nsk);
1687 }
1688
1689 int getsockname(int sk, struct sockaddr *sa, socklen_t *len)
1690 {
1691   int rc;
1692   Dpid;
1693
1694   D( fprintf(stderr, "noip(%d): GETSOCKNAME sk=%d", pid, sk); )
1695   PRESERVING_ERRNO({
1696     char sabuf[1024];
1697     socklen_t mylen = sizeof(sabuf);
1698     rc = real_getsockname(sk, SA(sabuf), &mylen);
1699     if (rc >= 0) {
1700       D( fprintf(stderr, " -> converting...\n"); )
1701       return_fake_name(SA(sabuf), mylen, sa, len);
1702       D( fprintf(stderr, "noip(%d): ... GETSOCKNAME", pid); )
1703     }
1704   });
1705   D( dump_addrresult(rc, sa, *len); )
1706   return (rc);
1707 }
1708
1709 int getpeername(int sk, struct sockaddr *sa, socklen_t *len)
1710 {
1711   int rc;
1712   Dpid;
1713
1714   D( fprintf(stderr, "noip(%d): GETPEERNAME sk=%d", pid, sk); )
1715   PRESERVING_ERRNO({
1716     char sabuf[1024];
1717     socklen_t mylen = sizeof(sabuf);
1718     rc = real_getpeername(sk, SA(sabuf), &mylen);
1719     if (rc >= 0) {
1720       D( fprintf(stderr, " -> converting...\n"); )
1721       return_fake_name(SA(sabuf), mylen, sa, len);
1722       D( fprintf(stderr, "noip(%d): ... GETPEERNAME", pid); )
1723     }
1724   });
1725   D( dump_addrresult(rc, sa, *len); )
1726   return (0);
1727 }
1728
1729 int getsockopt(int sk, int lev, int opt, void *p, socklen_t *len)
1730 {
1731   switch (lev) {
1732     case SOL_IP:
1733     case SOL_TCP:
1734     case SOL_UDP:
1735       if (*len > 0)
1736         memset(p, 0, *len);
1737       return (0);
1738   }
1739   return (real_getsockopt(sk, lev, opt, p, len));
1740 }
1741
1742 int setsockopt(int sk, int lev, int opt, const void *p, socklen_t len)
1743 {
1744   switch (lev) {
1745     case SOL_IP:
1746     case SOL_TCP:
1747     case SOL_UDP:
1748       return (0);
1749   }
1750   switch (opt) {
1751     case SO_BINDTODEVICE:
1752     case SO_ATTACH_FILTER:
1753     case SO_DETACH_FILTER:
1754       return (0);
1755   }
1756   return (real_setsockopt(sk, lev, opt, p, len));
1757 }
1758
1759 int ioctl(int fd, unsigned long op, ...)
1760 {
1761   va_list ap;
1762   void *arg;
1763   int sk;
1764   int rc;
1765
1766   va_start(ap, op);
1767   arg = va_arg(ap, void *);
1768
1769   switch (op) {
1770     case SIOCGIFADDR:
1771     case SIOCGIFBRDADDR:
1772     case SIOCGIFDSTADDR:
1773     case SIOCGIFNETMASK:
1774       PRESERVING_ERRNO({
1775         if (fixup_real_ip_socket(fd, AF_INET, &sk)) goto real;
1776       });
1777       rc = real_ioctl(sk, op, arg);
1778       PRESERVING_ERRNO({ close(sk); });
1779       break;
1780     default:
1781     real:
1782       rc = real_ioctl(fd, op, arg);
1783       break;
1784   }
1785   va_end(ap);
1786   return (rc);
1787 }
1788
1789 /*----- Initialization ----------------------------------------------------*/
1790
1791 /* Clean up the socket directory, deleting stale sockets. */
1792 static void cleanup_sockdir(void)
1793 {
1794   DIR *dir;
1795   struct dirent *d;
1796   address addr;
1797   struct sockaddr_un sun;
1798   struct stat st;
1799   Dpid;
1800
1801   if ((dir = opendir(sockdir)) == 0) return;
1802   sun.sun_family = AF_UNIX;
1803   while ((d = readdir(dir)) != 0) {
1804     if (d->d_name[0] == '.') continue;
1805     snprintf(sun.sun_path, sizeof(sun.sun_path),
1806              "%s/%s", sockdir, d->d_name);
1807     if (decode_inet_addr(&addr.sa, 0, &sun, SUN_LEN(&sun)) ||
1808         stat(sun.sun_path, &st) ||
1809         !S_ISSOCK(st.st_mode)) {
1810       D( fprintf(stderr, "noip(%d): ignoring unknown socketdir entry `%s'\n",
1811                  pid, sun.sun_path); )
1812       continue;
1813     }
1814     if (unix_socket_status(&sun, 0) == STALE) {
1815       D( fprintf(stderr, "noip(%d): clearing away stale socket %s\n",
1816                  pid, d->d_name); )
1817       unlink(sun.sun_path);
1818     }
1819   }
1820   closedir(dir);
1821 }
1822
1823 /* Find the addresses attached to local network interfaces, and remember them
1824  * in a table.
1825  */
1826 static void get_local_ipaddrs(void)
1827 {
1828   struct ifaddrs *ifa_head, *ifa;
1829   ipaddr a;
1830   int i;
1831   Dpid;
1832
1833   D( fprintf(stderr, "noip(%d): fetching local addresses...\n", pid); )
1834   if (getifaddrs(&ifa_head)) { perror("getifaddrs"); return; }
1835   for (n_local_ipaddrs = 0, ifa = ifa_head;
1836        n_local_ipaddrs < MAX_LOCAL_IPADDRS && ifa;
1837        ifa = ifa->ifa_next) {
1838     if (!ifa->ifa_addr || !family_known_p(ifa->ifa_addr->sa_family))
1839       continue;
1840     ipaddr_from_sockaddr(&a, ifa->ifa_addr);
1841     D({ char buf[ADDRBUFSZ];
1842         fprintf(stderr, "noip(%d):   local addr %s = %s", pid,
1843                 ifa->ifa_name,
1844                 inet_ntop(ifa->ifa_addr->sa_family, &a,
1845                           buf, sizeof(buf))); })
1846     for (i = 0; i < n_local_ipaddrs; i++) {
1847       if (ifa->ifa_addr->sa_family == local_ipaddrs[i].af &&
1848           ipaddr_equal_p(local_ipaddrs[i].af, &a, &local_ipaddrs[i].addr)) {
1849         D( fprintf(stderr, " (duplicate)\n"); )
1850         goto skip;
1851       }
1852     }
1853     D( fprintf(stderr, "\n"); )
1854     local_ipaddrs[n_local_ipaddrs].af = ifa->ifa_addr->sa_family;
1855     local_ipaddrs[n_local_ipaddrs].addr = a;
1856     n_local_ipaddrs++;
1857   skip:;
1858   }
1859   freeifaddrs(ifa_head);
1860 }
1861
1862 /* Print the given message to standard error.  Avoids stdio. */
1863 static void printerr(const char *p)
1864   { if (write(STDERR_FILENO, p, strlen(p))) ; }
1865
1866 /* Create the socket directory, being careful about permissions. */
1867 static void create_sockdir(void)
1868 {
1869   struct stat st;
1870
1871   if (lstat(sockdir, &st)) {
1872     if (errno == ENOENT) {
1873       if (mkdir(sockdir, 0700)) {
1874         perror("noip: creating socketdir");
1875         exit(127);
1876       }
1877       if (!lstat(sockdir, &st))
1878         goto check;
1879     }
1880     perror("noip: checking socketdir");
1881     exit(127);
1882   }
1883 check:
1884   if (!S_ISDIR(st.st_mode)) {
1885     printerr("noip: bad socketdir: not a directory\n");
1886     exit(127);
1887   }
1888   if (st.st_uid != uid) {
1889     printerr("noip: bad socketdir: not owner\n");
1890     exit(127);
1891   }
1892   if (st.st_mode & 077) {
1893     printerr("noip: bad socketdir: not private\n");
1894     exit(127);
1895   }
1896 }
1897
1898 /* Initialization function. */
1899 static void setup(void) __attribute__((constructor));
1900 static void setup(void)
1901 {
1902   PRESERVING_ERRNO({
1903     char *p;
1904
1905     import();
1906     uid = geteuid();
1907     if ((p = getenv("NOIP_DEBUG")) && atoi(p))
1908       debug = 1;
1909     get_local_ipaddrs();
1910     readconfig();
1911     create_sockdir();
1912     cleanup_sockdir();
1913   });
1914 }
1915
1916 /*----- That's all, folks -------------------------------------------------*/