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