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