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