chiark / gitweb /
noip.c: Fix some holdovers with hardcoded address families.
[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.
719  */
720 static int fixup_real_ip_socket(int sk, int af_hint)
721 {
722   int nsk;
723   int type;
724   int f, fd;
725   struct sockaddr_un sun;
726   address addr;
727   socklen_t len;
728
729 #define OPTS(_)                                                         \
730   _(DEBUG, int)                                                         \
731   _(REUSEADDR, int)                                                     \
732   _(DONTROUTE, int)                                                     \
733   _(BROADCAST, int)                                                     \
734   _(SNDBUF, int)                                                        \
735   _(RCVBUF, int)                                                        \
736   _(OOBINLINE, int)                                                     \
737   _(NO_CHECK, int)                                                      \
738   _(LINGER, struct linger)                                              \
739   _(BSDCOMPAT, int)                                                     \
740   _(RCVLOWAT, int)                                                      \
741   _(RCVTIMEO, struct timeval)                                           \
742   _(SNDTIMEO, struct timeval)
743
744   len = sizeof(sun);
745   if (real_getsockname(sk, SA(&sun), &len))
746     return (-1);
747   if (decode_inet_addr(&addr.sa, af_hint, &sun, len))
748     return (0); /* Not one of ours */
749   len = sizeof(type);
750   if (real_getsockopt(sk, SOL_SOCKET, SO_TYPE, &type, &len) < 0 ||
751       (nsk = real_socket(addr.sa.sa_family, type, 0)) < 0)
752     return (-1);
753 #define FIX(opt, ty) do {                                               \
754   ty ov_;                                                               \
755   len = sizeof(ov_);                                                    \
756   if (real_getsockopt(sk, SOL_SOCKET, SO_##opt, &ov_, &len) < 0 ||      \
757       real_setsockopt(nsk, SOL_SOCKET, SO_##opt, &ov_, len)) {          \
758     close(nsk);                                                         \
759     return (-1);                                                        \
760   }                                                                     \
761 } while (0);
762   OPTS(FIX)
763 #undef FIX
764   if ((f = fcntl(sk, F_GETFL)) < 0 ||
765       (fd = fcntl(sk, F_GETFD)) < 0 ||
766       fcntl(nsk, F_SETFL, f) < 0 ||
767       dup2(nsk, sk) < 0) {
768     close(nsk);
769     return (-1);
770   }
771   unlink(sun.sun_path);
772   close(nsk);
773   if (fcntl(sk, F_SETFD, fd) < 0) {
774     perror("noip: fixup_real_ip_socket F_SETFD");
775     abort();
776   }
777   return (0);
778 }
779
780 /* The socket SK is about to be used to communicate with the remote address
781  * SA.  Assign it a local address so that getpeername(2) does something
782  * useful.
783  */
784 static int do_implicit_bind(int sk, const struct sockaddr **sa,
785                             socklen_t *len, struct sockaddr_un *sun)
786 {
787   address addr;
788   socklen_t mylen = sizeof(*sun);
789
790   if (acl_allows_p(connect_real, *sa)) {
791     if (fixup_real_ip_socket(sk, (*sa)->sa_family)) return (-1);
792   } else {
793     if (real_getsockname(sk, SA(sun), &mylen) < 0) return (-1);
794     if (sun->sun_family == AF_UNIX) {
795       if (mylen < sizeof(*sun)) ((char *)sun)[mylen] = 0;
796       if (!sun->sun_path[0]) {
797         wildcard_address((*sa)->sa_family, &addr.sa);
798         encode_inet_addr(sun, &addr.sa, WANT_FRESH);
799         if (real_bind(sk, SA(sun), SUN_LEN(sun))) return (-1);
800       }
801       encode_inet_addr(sun, *sa, WANT_EXISTING);
802       *sa = SA(sun);
803       *len = SUN_LEN(sun);
804     }
805   }
806   return (0);
807 }
808
809 /* We found the real address SA, with length LEN; if it's a Unix-domain
810  * address corresponding to a fake socket, convert it to cover up the
811  * deception.  Whatever happens, put the result at FAKE and store its length
812  * at FAKELEN.
813  */
814 static void return_fake_name(struct sockaddr *sa, socklen_t len,
815                              struct sockaddr *fake, socklen_t *fakelen)
816 {
817   address addr;
818   socklen_t alen;
819
820   if (sa->sa_family == AF_UNIX &&
821       !decode_inet_addr(&addr.sa, 0, SUN(sa), len)) {
822     sa = &addr.sa;
823     len = family_socklen(addr.sa.sa_family);
824   }
825   alen = len;
826   if (len > *fakelen) len = *fakelen;
827   if (len > 0) memcpy(fake, sa, len);
828   *fakelen = alen;
829 }
830
831 /*----- Configuration -----------------------------------------------------*/
832
833 /* Return the process owner's home directory. */
834 static char *home(void)
835 {
836   char *p;
837   struct passwd *pw;
838
839   if (getuid() == uid &&
840       (p = getenv("HOME")) != 0)
841     return (p);
842   else if ((pw = getpwuid(uid)) != 0)
843     return (pw->pw_dir);
844   else
845     return "/notexist";
846 }
847
848 /* Return a good temporary directory to use. */
849 static char *tmpdir(void)
850 {
851   char *p;
852
853   if ((p = getenv("TMPDIR")) != 0) return (p);
854   else if ((p = getenv("TMP")) != 0) return (p);
855   else return ("/tmp");
856 }
857
858 /* Return the user's name, or at least something distinctive. */
859 static char *user(void)
860 {
861   static char buf[16];
862   char *p;
863   struct passwd *pw;
864
865   if ((p = getenv("USER")) != 0) return (p);
866   else if ((p = getenv("LOGNAME")) != 0) return (p);
867   else if ((pw = getpwuid(uid)) != 0) return (pw->pw_name);
868   else {
869     snprintf(buf, sizeof(buf), "uid-%lu", (unsigned long)uid);
870     return (buf);
871   }
872 }
873
874 /* Skip P over space characters. */
875 #define SKIPSPC do { while (*p && isspace(UC(*p))) p++; } while (0)
876
877 /* Set Q to point to the next word following P, null-terminate it, and step P
878  * past it. */
879 #define NEXTWORD(q) do {                                                \
880   SKIPSPC;                                                              \
881   q = p;                                                                \
882   while (*p && !isspace(UC(*p))) p++;                                   \
883   if (*p) *p++ = 0;                                                     \
884 } while (0)
885
886 /* Set Q to point to the next dotted-quad address, store the ending delimiter
887  * in DEL, null-terminate it, and step P past it. */
888 static void parse_nextaddr(char **pp, char **qq, int *del)
889 {
890   char *p = *pp;
891
892   SKIPSPC;
893   if (*p == '[') {
894     p++; SKIPSPC;
895     *qq = p;
896     p += strcspn(p, "]");
897     if (*p) *p++ = 0;
898     *del = 0;
899   } else {
900     *qq = p;
901     while (*p && (*p == '.' || isdigit(UC(*p)))) p++;
902     *del = *p;
903     if (*p) *p++ = 0;
904   }
905   *pp = p;
906 }
907
908 /* Set Q to point to the next decimal number, store the ending delimiter in
909  * DEL, null-terminate it, and step P past it. */
910 #define NEXTNUMBER(q, del) do {                                         \
911   SKIPSPC;                                                              \
912   q = p;                                                                \
913   while (*p && isdigit(UC(*p))) p++;                                    \
914   del = *p;                                                             \
915   if (*p) *p++ = 0;                                                     \
916 } while (0)
917
918 /* Push the character DEL back so we scan it again, unless it's zero
919  * (end-of-file). */
920 #define RESCAN(del) do { if (del) *--p = del; } while (0)
921
922 /* Evaluate true if P is pointing to the word KW (and not some longer string
923  * of which KW is a prefix). */
924
925 #define KWMATCHP(kw) (strncmp(p, kw, sizeof(kw) - 1) == 0 &&            \
926                       !isalnum(UC(p[sizeof(kw) - 1])) &&                \
927                       (p += sizeof(kw) - 1))
928
929 /* Parse a port list, starting at *PP.  Port lists have the form
930  * [:LOW[-HIGH]]: if omitted, all ports are included; if HIGH is omitted,
931  * it's as if HIGH = LOW.  Store LOW in *MIN, HIGH in *MAX and set *PP to the
932  * rest of the string.
933  */
934 static void parse_ports(char **pp, unsigned short *min, unsigned short *max)
935 {
936   char *p = *pp, *q;
937   int del;
938
939   SKIPSPC;
940   if (*p != ':')
941     { *min = 0; *max = 0xffff; }
942   else {
943     p++;
944     NEXTNUMBER(q, del); *min = strtoul(q, 0, 0); RESCAN(del);
945     SKIPSPC;
946     if (*p == '-')
947       { p++; NEXTNUMBER(q, del); *max = strtoul(q, 0, 0); RESCAN(del); }
948     else
949       *max = *min;
950   }
951   *pp = p;
952 }
953
954 /* Make a new ACL node.  ACT is the verdict; AF is the address family;
955  * MINADDR and MAXADDR are the ranges on IP addresses; MINPORT and MAXPORT
956  * are the ranges on port numbers; TAIL is the list tail to attach the new
957  * node to.
958  */
959 #define ACLNODE(tail_, act_,                                            \
960                 af_, minaddr_, maxaddr_, minport_, maxport_) do {       \
961   aclnode *a_;                                                          \
962   NEW(a_);                                                              \
963   a_->act = (act_);                                                     \
964   a_->af = (af_);                                                       \
965   a_->minaddr = (minaddr_); a_->maxaddr = (maxaddr_);                   \
966   a_->minport = (minport_); a_->maxport = (maxport_);                   \
967   *tail_ = a_; tail_ = &a_->next;                                       \
968 } while (0)
969
970 /* Parse an ACL line.  *PP points to the end of the line; *TAIL points to
971  * the list tail (i.e., the final link in the list).  An ACL entry has the
972  * form +|- [any | local | ADDR | ADDR - ADDR | ADDR/ADDR | ADDR/INT] PORTS
973  * where PORTS is parsed by parse_ports above; an ACL line consists of a
974  * comma-separated sequence of entries..
975  */
976 static void parse_acl_line(char **pp, aclnode ***tail)
977 {
978   ipaddr minaddr, maxaddr;
979   unsigned short minport, maxport;
980   int i, af, n;
981   int act;
982   int del;
983   char *p = *pp;
984   char *q;
985
986   for (;;) {
987     SKIPSPC;
988     if (*p == '+') act = ALLOW;
989     else if (*p == '-') act = DENY;
990     else goto bad;
991
992     p++;
993     SKIPSPC;
994     if (KWMATCHP("any")) {
995       parse_ports(&p, &minport, &maxport);
996       for (i = 0; address_families[i] >= 0; i++) {
997         af = address_families[i];
998         memset(&minaddr, 0, sizeof(minaddr));
999         maxaddr = minaddr; mask_address(af, &maxaddr, 0, 1);
1000         ACLNODE(*tail, act, af, minaddr, maxaddr, minport, maxport);
1001       }
1002     } else if (KWMATCHP("local")) {
1003       parse_ports(&p, &minport, &maxport);
1004       for (i = 0; address_families[i] >= 0; i++) {
1005         af = address_families[i];
1006         memset(&minaddr, 0, sizeof(minaddr));
1007         maxaddr = minaddr; mask_address(af, &maxaddr, 0, 1);
1008         ACLNODE(*tail, act, af, minaddr, minaddr, minport, maxport);
1009         ACLNODE(*tail, act, af, maxaddr, maxaddr, minport, maxport);
1010       }
1011       for (i = 0; i < n_local_ipaddrs; i++) {
1012         ACLNODE(*tail, act, local_ipaddrs[i].af,
1013                 local_ipaddrs[i].addr, local_ipaddrs[i].addr,
1014                 minport, maxport);
1015       }
1016     } else {
1017       parse_nextaddr(&p, &q, &del);
1018       af = guess_address_family(q);
1019       if (inet_pton(af, q, &minaddr) <= 0) goto bad;
1020       RESCAN(del);
1021       SKIPSPC;
1022       if (*p == '-') {
1023         p++;
1024         parse_nextaddr(&p, &q, &del);
1025         if (inet_pton(af, q, &maxaddr) <= 0) goto bad;
1026         RESCAN(del);
1027       } else if (*p == '/') {
1028         p++;
1029         NEXTNUMBER(q, del);
1030         n = strtoul(q, 0, 0);
1031         maxaddr = minaddr;
1032         mask_address(af, &minaddr, n, 0);
1033         mask_address(af, &maxaddr, n, 1);
1034       } else
1035         maxaddr = minaddr;
1036       parse_ports(&p, &minport, &maxport);
1037       ACLNODE(*tail, act, af, minaddr, maxaddr, minport, maxport);
1038     }
1039     SKIPSPC;
1040     if (*p != ',') break;
1041     if (*p) p++;
1042   }
1043   *pp = p;
1044   return;
1045
1046 bad:
1047   D( fprintf(stderr, "noip: bad acl spec (ignored)\n"); )
1048   return;
1049 }
1050
1051 /* Parse the autoports configuration directive.  Syntax is MIN - MAX. */
1052 static void parse_autoports(char **pp)
1053 {
1054   char *p = *pp, *q;
1055   unsigned x, y;
1056   int del;
1057
1058   SKIPSPC;
1059   NEXTNUMBER(q, del); x = strtoul(q, 0, 0); RESCAN(del);
1060   SKIPSPC;
1061   if (*p != '-') goto bad; p++;
1062   NEXTNUMBER(q, del); y = strtoul(q, 0, 0); RESCAN(del);
1063   minautoport = x; maxautoport = y;
1064   *pp = p;
1065   return;
1066
1067 bad:
1068   D( fprintf(stderr, "bad port range (ignored)\n"); )
1069   return;
1070 }
1071
1072 /* Parse an ACL from an environment variable VAR, attaching it to the list
1073  * TAIL. */
1074 static void parse_acl_env(const char *var, aclnode ***tail)
1075 {
1076   char *p, *q;
1077
1078   if ((p = getenv(var)) != 0) {
1079     p = q = xstrdup(p);
1080     parse_acl_line(&q, tail);
1081     free(p);
1082   }
1083 }
1084
1085 /* Read the configuration from the config file and environment. */
1086 static void readconfig(void)
1087 {
1088   FILE *fp;
1089   char buf[1024];
1090   size_t n;
1091   char *p, *q, *cmd;
1092
1093   parse_acl_env("NOIP_REALBIND_BEFORE", &bind_tail);
1094   parse_acl_env("NOIP_REALCONNECT_BEFORE", &connect_tail);
1095   if ((p = getenv("NOIP_AUTOPORTS")) != 0) {
1096     p = q = xstrdup(p);
1097     parse_autoports(&q);
1098     free(p);
1099   }
1100   if ((p = getenv("NOIP_CONFIG")) == 0)
1101     snprintf(p = buf, sizeof(buf), "%s/.noip", home());
1102   D( fprintf(stderr, "noip: config file: %s\n", p); )
1103
1104   if ((fp = fopen(p, "r")) == 0) {
1105     D( fprintf(stderr, "noip: couldn't read config: %s\n",
1106                strerror(errno)); )
1107     goto done;
1108   }
1109   while (fgets(buf, sizeof(buf), fp)) {
1110     n = strlen(buf);
1111     p = buf;
1112
1113     SKIPSPC;
1114     if (!*p || *p == '#') continue;
1115     while (n && isspace(UC(buf[n - 1]))) n--;
1116     buf[n] = 0;
1117     NEXTWORD(cmd);
1118     SKIPSPC;
1119
1120     if (strcmp(cmd, "socketdir") == 0)
1121       sockdir = xstrdup(p);
1122     else if (strcmp(cmd, "realbind") == 0)
1123       parse_acl_line(&p, &bind_tail);
1124     else if (strcmp(cmd, "realconnect") == 0)
1125       parse_acl_line(&p, &connect_tail);
1126     else if (strcmp(cmd, "autoports") == 0)
1127       parse_autoports(&p);
1128     else if (strcmp(cmd, "debug") == 0)
1129       debug = *p ? atoi(p) : 1;
1130     else
1131       D( fprintf(stderr, "noip: bad config command %s\n", cmd); )
1132   }
1133   fclose(fp);
1134
1135 done:
1136   parse_acl_env("NOIP_REALBIND", &bind_tail);
1137   parse_acl_env("NOIP_REALCONNECT", &connect_tail);
1138   parse_acl_env("NOIP_REALBIND_AFTER", &bind_tail);
1139   parse_acl_env("NOIP_REALCONNECT_AFTER", &connect_tail);
1140   *bind_tail = 0;
1141   *connect_tail = 0;
1142   if (!sockdir) sockdir = getenv("NOIP_SOCKETDIR");
1143   if (!sockdir) {
1144     snprintf(buf, sizeof(buf), "%s/noip-%s", tmpdir(), user());
1145     sockdir = xstrdup(buf);
1146   }
1147   D( fprintf(stderr, "noip: socketdir: %s\n", sockdir);
1148      fprintf(stderr, "noip: autoports: %u-%u\n",
1149              minautoport, maxautoport);
1150      fprintf(stderr, "noip: realbind acl:\n");
1151      dump_acl(bind_real);
1152      fprintf(stderr, "noip: realconnect acl:\n");
1153      dump_acl(connect_real); )
1154 }
1155
1156 /*----- Overridden system calls -------------------------------------------*/
1157
1158 int socket(int pf, int ty, int proto)
1159 {
1160   switch (pf) {
1161     default:
1162       if (!family_known_p(pf)) {
1163         errno = EAFNOSUPPORT;
1164         return (-1);
1165       }
1166       pf = PF_UNIX;
1167       proto = 0;
1168     case PF_UNIX:
1169 #ifdef PF_NETLINK
1170     case PF_NETLINK:
1171 #endif
1172       return (real_socket(pf, ty, proto));
1173   }
1174 }
1175
1176 int socketpair(int pf, int ty, int proto, int *sk)
1177 {
1178   if (family_known_p(pf)) {
1179     pf = PF_UNIX;
1180     proto = 0;
1181   }
1182   return (real_socketpair(pf, ty, proto, sk));
1183 }
1184
1185 int bind(int sk, const struct sockaddr *sa, socklen_t len)
1186 {
1187   struct sockaddr_un sun;
1188
1189   if (family_known_p(sa->sa_family)) {
1190     PRESERVING_ERRNO({
1191       if (acl_allows_p(bind_real, sa)) {
1192         if (fixup_real_ip_socket(sk, sa->sa_family))
1193           return (-1);
1194       } else {
1195         encode_inet_addr(&sun, sa, WANT_FRESH);
1196         sa = SA(&sun);
1197         len = SUN_LEN(&sun);
1198       }
1199     });
1200   }
1201   return (real_bind(sk, sa, len));
1202 }
1203
1204 int connect(int sk, const struct sockaddr *sa, socklen_t len)
1205 {
1206   struct sockaddr_un sun;
1207   int rc;
1208
1209   if (!family_known_p(sa->sa_family))
1210     rc = real_connect(sk, sa, len);
1211   else {
1212     PRESERVING_ERRNO({
1213       do_implicit_bind(sk, &sa, &len, &sun);
1214     });
1215     rc = real_connect(sk, sa, len);
1216     if (rc < 0) {
1217       switch (errno) {
1218         case ENOENT: errno = ECONNREFUSED; break;
1219       }
1220     }
1221   }
1222   return (rc);
1223 }
1224
1225 ssize_t sendto(int sk, const void *buf, size_t len, int flags,
1226                const struct sockaddr *to, socklen_t tolen)
1227 {
1228   struct sockaddr_un sun;
1229
1230   if (to && family_known_p(to->sa_family)) {
1231     PRESERVING_ERRNO({
1232       do_implicit_bind(sk, &to, &tolen, &sun);
1233     });
1234   }
1235   return (real_sendto(sk, buf, len, flags, to, tolen));
1236 }
1237
1238 ssize_t recvfrom(int sk, void *buf, size_t len, int flags,
1239                  struct sockaddr *from, socklen_t *fromlen)
1240 {
1241   char sabuf[1024];
1242   socklen_t mylen = sizeof(sabuf);
1243   ssize_t n;
1244
1245   if (!from)
1246     return real_recvfrom(sk, buf, len, flags, 0, 0);
1247   PRESERVING_ERRNO({
1248     n = real_recvfrom(sk, buf, len, flags, SA(sabuf), &mylen);
1249     if (n < 0)
1250       return (-1);
1251     return_fake_name(SA(sabuf), mylen, from, fromlen);
1252   });
1253   return (n);
1254 }
1255
1256 ssize_t sendmsg(int sk, const struct msghdr *msg, int flags)
1257 {
1258   struct sockaddr_un sun;
1259   const struct sockaddr *sa;
1260   struct msghdr mymsg;
1261
1262   if (msg->msg_name && family_known_p(SA(msg->msg_name)->sa_family)) {
1263     PRESERVING_ERRNO({
1264       sa = SA(msg->msg_name);
1265       mymsg = *msg;
1266       do_implicit_bind(sk, &sa, &mymsg.msg_namelen, &sun);
1267       mymsg.msg_name = SA(sa);
1268       msg = &mymsg;
1269     });
1270   }
1271   return (real_sendmsg(sk, msg, flags));
1272 }
1273
1274 ssize_t recvmsg(int sk, struct msghdr *msg, int flags)
1275 {
1276   char sabuf[1024];
1277   struct sockaddr *sa;
1278   socklen_t len;
1279   ssize_t n;
1280
1281   if (!msg->msg_name)
1282     return (real_recvmsg(sk, msg, flags));
1283   PRESERVING_ERRNO({
1284     sa = SA(msg->msg_name);
1285     len = msg->msg_namelen;
1286     msg->msg_name = sabuf;
1287     msg->msg_namelen = sizeof(sabuf);
1288     n = real_recvmsg(sk, msg, flags);
1289     if (n < 0)
1290       return (-1);
1291     return_fake_name(SA(sabuf), msg->msg_namelen, sa, &len);
1292     msg->msg_name = sa;
1293     msg->msg_namelen = len;
1294   });
1295   return (n);
1296 }
1297
1298 int accept(int sk, struct sockaddr *sa, socklen_t *len)
1299 {
1300   char sabuf[1024];
1301   socklen_t mylen = sizeof(sabuf);
1302   int nsk = real_accept(sk, SA(sabuf), &mylen);
1303
1304   if (nsk < 0)
1305     return (-1);
1306   return_fake_name(SA(sabuf), mylen, sa, len);
1307   return (nsk);
1308 }
1309
1310 int getsockname(int sk, struct sockaddr *sa, socklen_t *len)
1311 {
1312   PRESERVING_ERRNO({
1313     char sabuf[1024];
1314     socklen_t mylen = sizeof(sabuf);
1315     if (real_getsockname(sk, SA(sabuf), &mylen))
1316       return (-1);
1317     return_fake_name(SA(sabuf), mylen, sa, len);
1318   });
1319   return (0);
1320 }
1321
1322 int getpeername(int sk, struct sockaddr *sa, socklen_t *len)
1323 {
1324   PRESERVING_ERRNO({
1325     char sabuf[1024];
1326     socklen_t mylen = sizeof(sabuf);
1327     if (real_getpeername(sk, SA(sabuf), &mylen))
1328       return (-1);
1329     return_fake_name(SA(sabuf), mylen, sa, len);
1330   });
1331   return (0);
1332 }
1333
1334 int getsockopt(int sk, int lev, int opt, void *p, socklen_t *len)
1335 {
1336   switch (lev) {
1337     case SOL_IP:
1338     case SOL_TCP:
1339     case SOL_UDP:
1340       if (*len > 0)
1341         memset(p, 0, *len);
1342       return (0);
1343   }
1344   return (real_getsockopt(sk, lev, opt, p, len));
1345 }
1346
1347 int setsockopt(int sk, int lev, int opt, const void *p, socklen_t len)
1348 {
1349   switch (lev) {
1350     case SOL_IP:
1351     case SOL_TCP:
1352     case SOL_UDP:
1353       return (0);
1354   }
1355   switch (opt) {
1356     case SO_BINDTODEVICE:
1357     case SO_ATTACH_FILTER:
1358     case SO_DETACH_FILTER:
1359       return (0);
1360   }
1361   return (real_setsockopt(sk, lev, opt, p, len));
1362 }
1363
1364 /*----- Initialization ----------------------------------------------------*/
1365
1366 /* Clean up the socket directory, deleting stale sockets. */
1367 static void cleanup_sockdir(void)
1368 {
1369   DIR *dir;
1370   struct dirent *d;
1371   address addr;
1372   struct sockaddr_un sun;
1373   struct stat st;
1374
1375   if ((dir = opendir(sockdir)) == 0) return;
1376   sun.sun_family = AF_UNIX;
1377   while ((d = readdir(dir)) != 0) {
1378     if (d->d_name[0] == '.') continue;
1379     snprintf(sun.sun_path, sizeof(sun.sun_path),
1380              "%s/%s", sockdir, d->d_name);
1381     if (decode_inet_addr(&addr.sa, 0, &sun, SUN_LEN(&sun)) ||
1382         stat(sun.sun_path, &st) ||
1383         !S_ISSOCK(st.st_mode)) {
1384       D( fprintf(stderr, "noip: ignoring unknown socketdir entry `%s'\n",
1385                  sun.sun_path); )
1386       continue;
1387     }
1388     if (unix_socket_status(&sun, 0) == STALE) {
1389       D( fprintf(stderr, "noip: clearing away stale socket %s\n",
1390                  d->d_name); )
1391       unlink(sun.sun_path);
1392     }
1393   }
1394   closedir(dir);
1395 }
1396
1397 /* Find the addresses attached to local network interfaces, and remember them
1398  * in a table.
1399  */
1400 static void get_local_ipaddrs(void)
1401 {
1402   struct ifaddrs *ifa_head, *ifa;
1403   ipaddr a;
1404   int i;
1405
1406   if (getifaddrs(&ifa_head)) { perror("getifaddrs"); return; }
1407   for (n_local_ipaddrs = 0, ifa = ifa_head;
1408        n_local_ipaddrs < MAX_LOCAL_IPADDRS && ifa;
1409        ifa = ifa->ifa_next) {
1410     if (!ifa->ifa_addr || !family_known_p(ifa->ifa_addr->sa_family))
1411       continue;
1412     ipaddr_from_sockaddr(&a, ifa->ifa_addr);
1413     D({ char buf[ADDRBUFSZ];
1414         fprintf(stderr, "noip: local addr %s = %s", ifa->ifa_name,
1415                 inet_ntop(ifa->ifa_addr->sa_family, &a,
1416                           buf, sizeof(buf))); })
1417     for (i = 0; i < n_local_ipaddrs; i++) {
1418       if (ifa->ifa_addr->sa_family == local_ipaddrs[i].af &&
1419           ipaddr_equal_p(local_ipaddrs[i].af, &a, &local_ipaddrs[i].addr)) {
1420         D( fprintf(stderr, " (duplicate)\n"); )
1421         goto skip;
1422       }
1423     }
1424     D( fprintf(stderr, "\n"); )
1425     local_ipaddrs[n_local_ipaddrs].af = ifa->ifa_addr->sa_family;
1426     local_ipaddrs[n_local_ipaddrs].addr = a;
1427     n_local_ipaddrs++;
1428   skip:;
1429   }
1430   freeifaddrs(ifa_head);
1431 }
1432
1433 /* Print the given message to standard error.  Avoids stdio. */
1434 static void printerr(const char *p)
1435   { if (write(STDERR_FILENO, p, strlen(p))) ; }
1436
1437 /* Create the socket directory, being careful about permissions. */
1438 static void create_sockdir(void)
1439 {
1440   struct stat st;
1441
1442   if (lstat(sockdir, &st)) {
1443     if (errno == ENOENT) {
1444       if (mkdir(sockdir, 0700)) {
1445         perror("noip: creating socketdir");
1446         exit(127);
1447       }
1448       if (!lstat(sockdir, &st))
1449         goto check;
1450     }
1451     perror("noip: checking socketdir");
1452     exit(127);
1453   }
1454 check:
1455   if (!S_ISDIR(st.st_mode)) {
1456     printerr("noip: bad socketdir: not a directory\n");
1457     exit(127);
1458   }
1459   if (st.st_uid != uid) {
1460     printerr("noip: bad socketdir: not owner\n");
1461     exit(127);
1462   }
1463   if (st.st_mode & 077) {
1464     printerr("noip: bad socketdir: not private\n");
1465     exit(127);
1466   }
1467 }
1468
1469 /* Initialization function. */
1470 static void setup(void) __attribute__((constructor));
1471 static void setup(void)
1472 {
1473   PRESERVING_ERRNO({
1474     char *p;
1475
1476     import();
1477     uid = geteuid();
1478     if ((p = getenv("NOIP_DEBUG")) && atoi(p))
1479       debug = 1;
1480     get_local_ipaddrs();
1481     readconfig();
1482     create_sockdir();
1483     cleanup_sockdir();
1484   });
1485 }
1486
1487 /*----- That's all, folks -------------------------------------------------*/