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