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