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