chiark / gitweb /
noip.c (encode_single_inet_addr): Make the logic less weird.
[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 /* Unix socket status values. */
63 #define UNUSED 0u                       /* No sign of anyone using it */
64 #define STALE 1u                        /* Socket exists, but is abandoned */
65 #define USED 16u                        /* Socket is in active use */
66
67 enum { DENY, ALLOW };                   /* ACL verdicts */
68
69 static int address_families[] = { AF_INET, AF_INET6, -1 };
70
71 #define ADDRBUFSZ 64
72
73 /* Address representations. */
74 typedef union ipaddr {
75   struct in_addr v4;
76   struct in6_addr v6;
77 } ipaddr;
78
79 /* Convenient socket address hacking. */
80 typedef union address {
81   struct sockaddr sa;
82   struct sockaddr_in sin;
83   struct sockaddr_in6 sin6;
84 } address;
85
86 /* Access control list nodes */
87 typedef struct aclnode {
88   struct aclnode *next;
89   int act;
90   int af;
91   ipaddr minaddr, maxaddr;
92   unsigned short minport, maxport;
93 } aclnode;
94
95 /* Implicit bind records */
96 typedef struct impbind {
97   struct impbind *next;
98   int af, how;
99   ipaddr minaddr, maxaddr, bindaddr;
100 } impbind;
101 enum { EXPLICIT, SAME };
102
103 /* A type for an address range */
104 typedef struct addrrange {
105   int type;
106   union {
107     struct { int af; ipaddr min, max; } range;
108   } u;
109 } addrrange;
110 enum { EMPTY, ANY, LOCAL, RANGE };
111
112 /* Local address records */
113 typedef struct full_ipaddr {
114   int af;
115   ipaddr addr;
116 } full_ipaddr;
117 #define MAX_LOCAL_IPADDRS 64
118 static full_ipaddr local_ipaddrs[MAX_LOCAL_IPADDRS];
119 static int n_local_ipaddrs;
120
121 /* General configuration */
122 static uid_t uid;
123 static char *sockdir = 0;
124 static int debug = 0;
125 static unsigned minautoport = 16384, maxautoport = 65536;
126
127 /* Access control lists */
128 static aclnode *bind_real, **bind_tail = &bind_real;
129 static aclnode *connect_real,  **connect_tail = &connect_real;
130 static impbind *impbinds, **impbind_tail = &impbinds;
131
132 /*----- Import the real versions of functions -----------------------------*/
133
134 /* The list of functions to immport. */
135 #define IMPORTS(_)                                                      \
136   _(socket, int, (int, int, int))                                       \
137   _(socketpair, int, (int, int, int, int *))                            \
138   _(connect, int, (int, const struct sockaddr *, socklen_t))            \
139   _(bind, int, (int, const struct sockaddr *, socklen_t))               \
140   _(accept, int, (int, struct sockaddr *, socklen_t *))                 \
141   _(getsockname, int, (int, struct sockaddr *, socklen_t *))            \
142   _(getpeername, int, (int, struct sockaddr *, socklen_t *))            \
143   _(getsockopt, int, (int, int, int, void *, socklen_t *))              \
144   _(setsockopt, int, (int, int, int, const void *, socklen_t))          \
145   _(sendto, ssize_t, (int, const void *buf, size_t, int,                \
146                       const struct sockaddr *to, socklen_t tolen))      \
147   _(recvfrom, ssize_t, (int, void *buf, size_t, int,                    \
148                         struct sockaddr *from, socklen_t *fromlen))     \
149   _(sendmsg, ssize_t, (int, const struct msghdr *, int))                \
150   _(recvmsg, ssize_t, (int, struct msghdr *, int))                      \
151   _(ioctl, int, (int, unsigned long, ...))
152
153 /* Function pointers to set up. */
154 #define DECL(imp, ret, args) static ret (*real_##imp) args;
155 IMPORTS(DECL)
156 #undef DECL
157
158 /* Import the system calls. */
159 static void import(void)
160 {
161 #define IMPORT(imp, ret, args)                                          \
162     real_##imp = (ret (*)args)dlsym(RTLD_NEXT, #imp);
163   IMPORTS(IMPORT)
164 #undef IMPORT
165 }
166
167 /*----- Utilities ---------------------------------------------------------*/
168
169 /* Socket address casts */
170 #define SA(sa) ((struct sockaddr *)(sa))
171 #define SIN(sa) ((struct sockaddr_in *)(sa))
172 #define SIN6(sa) ((struct sockaddr_in6 *)(sa))
173 #define SUN(sa) ((struct sockaddr_un *)(sa))
174
175 /* Raw bytes */
176 #define UC(ch) ((unsigned char)(ch))
177
178 /* Memory allocation */
179 #define NEW(x) ((x) = xmalloc(sizeof(*x)))
180 #define NEWV(x, n) ((x) = xmalloc(sizeof(*x) * (n)))
181
182 /* Debugging */
183 #ifdef DEBUG
184 #  define D(body) { if (debug) { body } }
185 #  define Dpid pid_t pid = debug ? getpid() : -1
186 #else
187 #  define D(body) ;
188 #  define Dpid
189 #endif
190
191 /* Preservation of error status */
192 #define PRESERVING_ERRNO(body) do {                                     \
193   int _err = errno; { body } errno = _err;                              \
194 } while (0)
195
196 /* Allocate N bytes of memory; abort on failure. */
197 static void *xmalloc(size_t n)
198 {
199   void *p;
200   if (!n) return (0);
201   if ((p = malloc(n)) == 0) { perror("malloc"); exit(127); }
202   return (p);
203 }
204
205 /* Allocate a copy of the null-terminated string P; abort on failure. */
206 static char *xstrdup(const char *p)
207 {
208   size_t n = strlen(p) + 1;
209   char *q = xmalloc(n);
210   memcpy(q, p, n);
211   return (q);
212 }
213
214 /*----- Address-type hacking ----------------------------------------------*/
215
216 /* If M is a simple mask, i.e., consists of a sequence of zero bits followed
217  * by a sequence of one bits, then return the length of the latter sequence
218  * (which may be zero); otherwise return -1.
219  */
220 static int simple_mask_length(unsigned long m)
221 {
222   int n = 0;
223
224   while (m & 1) { n++; m >>= 1; }
225   return (m ? -1 : n);
226 }
227
228 /* Answer whether AF is an interesting address family. */
229 static int family_known_p(int af)
230 {
231   switch (af) {
232     case AF_INET:
233     case AF_INET6:
234       return (1);
235     default:
236       return (0);
237   }
238 }
239
240 /* Return the socket address length for address family AF. */
241 static socklen_t family_socklen(int af)
242 {
243   switch (af) {
244     case AF_INET: return (sizeof(struct sockaddr_in));
245     case AF_INET6: return (sizeof(struct sockaddr_in6));
246     default: abort();
247   }
248 }
249
250 /* Return the width of addresses of kind AF. */
251 static int address_width(int af)
252 {
253   switch (af) {
254     case AF_INET: return 32;
255     case AF_INET6: return 128;
256     default: abort();
257   }
258 }
259
260 /* If addresses A and B share a common prefix then return its length;
261  * otherwise return -1.
262  */
263 static int common_prefix_length(int af, const ipaddr *a, const ipaddr *b)
264 {
265   switch (af) {
266     case AF_INET: {
267       unsigned long aa = ntohl(a->v4.s_addr), bb = ntohl(b->v4.s_addr);
268       unsigned long m = aa^bb;
269       if ((aa&m) == 0 && (bb&m) == m) return (32 - simple_mask_length(m));
270       else return (-1);
271     } break;
272     case AF_INET6: {
273       const uint8_t *aa = a->v6.s6_addr, *bb = b->v6.s6_addr;
274       unsigned m;
275       unsigned n;
276       int i;
277
278       for (i = 0; i < 16 && aa[i] == bb[i]; i++);
279       n = 8*i;
280       if (i < 16) {
281         m = aa[i]^bb[i];
282         if ((aa[i]&m) != 0 || (bb[i]&m) != m) return (-1);
283         n += 8 - simple_mask_length(m);
284         for (i++; i < 16; i++)
285           if (aa[i] || bb[i] != 0xff) return (-1);
286       }
287       return (n);
288     } break;
289     default:
290       abort();
291   }
292 }
293
294 /* Extract the port number (in host byte-order) from SA. */
295 static int port_from_sockaddr(const struct sockaddr *sa)
296 {
297   switch (sa->sa_family) {
298     case AF_INET: return (ntohs(SIN(sa)->sin_port));
299     case AF_INET6: return (ntohs(SIN6(sa)->sin6_port));
300     default: abort();
301   }
302 }
303
304 /* Store the port number PORT (in host byte-order) in SA. */
305 static void port_to_sockaddr(struct sockaddr *sa, int port)
306 {
307   switch (sa->sa_family) {
308     case AF_INET: SIN(sa)->sin_port = htons(port); break;
309     case AF_INET6: SIN6(sa)->sin6_port = htons(port); break;
310     default: abort();
311   }
312 }
313
314 /* Extract the address part from SA and store it in A. */
315 static void ipaddr_from_sockaddr(ipaddr *a, const struct sockaddr *sa)
316 {
317   switch (sa->sa_family) {
318     case AF_INET: a->v4 = SIN(sa)->sin_addr; break;
319     case AF_INET6: a->v6 = SIN6(sa)->sin6_addr; break;
320     default: abort();
321   }
322 }
323
324 /* Store the address A in SA. */
325 static void ipaddr_to_sockaddr(struct sockaddr *sa, const ipaddr *a)
326 {
327   switch (sa->sa_family) {
328     case AF_INET:
329       SIN(sa)->sin_addr = a->v4;
330       break;
331     case AF_INET6:
332       SIN6(sa)->sin6_addr = a->v6;
333       SIN6(sa)->sin6_scope_id = 0;
334       SIN6(sa)->sin6_flowinfo = 0;
335       break;
336     default:
337       abort();
338   }
339 }
340
341 /* Copy a whole socket address about. */
342 static void copy_sockaddr(struct sockaddr *sa_dst,
343                           const struct sockaddr *sa_src)
344   { memcpy(sa_dst, sa_src, family_socklen(sa_src->sa_family)); }
345
346 /* Convert an AF_INET socket address into the equivalent IPv4-mapped AF_INET6
347  * address.
348  */
349 static void map_ipv4_sockaddr(struct sockaddr_in6 *a6,
350                               const struct sockaddr_in *a4)
351 {
352   size_t i;
353   in_addr_t a = ntohl(a4->sin_addr.s_addr);
354
355   a6->sin6_family = AF_INET6;
356   a6->sin6_port = a4->sin_port;
357   a6->sin6_scope_id = 0;
358   a6->sin6_flowinfo = 0;
359   for (i = 0; i < 10; i++) a6->sin6_addr.s6_addr[i] = 0;
360   for (i = 10; i < 12; i++) a6->sin6_addr.s6_addr[i] = 0xff;
361   for (i = 0; i < 4; i++) a6->sin6_addr.s6_addr[15 - i] = (a >> 8*i)&0xff;
362 }
363
364 /* Convert an AF_INET6 socket address containing an IPv4-mapped IPv6 address
365  * into the equivalent AF_INET4 address.  Return zero on success, or -1 if
366  * the address has the wrong form.
367  */
368 static int unmap_ipv4_sockaddr(struct sockaddr_in *a4,
369                                const struct sockaddr_in6 *a6)
370 {
371   size_t i;
372   in_addr_t a;
373
374   for (i = 0; i < 10; i++) if (a6->sin6_addr.s6_addr[i] != 0) return (-1);
375   for (i = 10; i < 12; i++) if (a6->sin6_addr.s6_addr[i] != 0xff) return (-1);
376   for (i = 0, a = 0; i < 4; i++) a |= a6->sin6_addr.s6_addr[15 - i] << 8*i;
377   a4->sin_family = AF_INET;
378   a4->sin_port = a6->sin6_port;
379   a4->sin_addr.s_addr = htonl(a);
380   return (0);
381 }
382
383 /* Answer whether two addresses are equal. */
384 static int ipaddr_equal_p(int af, const ipaddr *a, const ipaddr *b)
385 {
386   switch (af) {
387     case AF_INET: return (a->v4.s_addr == b->v4.s_addr);
388     case AF_INET6: return (memcmp(a->v6.s6_addr, b->v6.s6_addr, 16) == 0);
389     default: abort();
390   }
391 }
392
393 /* Answer whether the address part of SA is between A and B (inclusive).  We
394  * assume that SA has the correct address family.
395  */
396 static int sockaddr_in_range_p(const struct sockaddr *sa,
397                                const ipaddr *a, const ipaddr *b)
398 {
399   switch (sa->sa_family) {
400     case AF_INET: {
401       unsigned long addr = ntohl(SIN(sa)->sin_addr.s_addr);
402       return (ntohl(a->v4.s_addr) <= addr &&
403               addr <= ntohl(b->v4.s_addr));
404     } break;
405     case AF_INET6: {
406       const uint8_t *ss = SIN6(sa)->sin6_addr.s6_addr;
407       const uint8_t *aa = a->v6.s6_addr, *bb = b->v6.s6_addr;
408       int h = 1, l = 1;
409       int i;
410
411       for (i = 0; h && l && i < 16; i++, ss++, aa++, bb++) {
412         if (*ss < *aa || *bb < *ss) return (0);
413         if (*aa < *ss) l = 0;
414         if (*ss < *bb) h = 0;
415       }
416       return (1);
417     } break;
418     default:
419       abort();
420   }
421 }
422
423 /* Fill in SA with the appropriate wildcard address. */
424 static void wildcard_address(int af, struct sockaddr *sa)
425 {
426   switch (af) {
427     case AF_INET: {
428       struct sockaddr_in *sin = SIN(sa);
429       memset(sin, 0, sizeof(*sin));
430       sin->sin_family = AF_INET;
431       sin->sin_port = 0;
432       sin->sin_addr.s_addr = INADDR_ANY;
433     } break;
434     case AF_INET6: {
435       struct sockaddr_in6 *sin6 = SIN6(sa);
436       memset(sin6, 0, sizeof(*sin6));
437       sin6->sin6_family = AF_INET6;
438       sin6->sin6_port = 0;
439       sin6->sin6_addr = in6addr_any;
440       sin6->sin6_scope_id = 0;
441       sin6->sin6_flowinfo = 0;
442     } break;
443     default:
444       abort();
445   }
446 }
447
448 /* Mask the address A, forcing all but the top PLEN bits to zero or one
449  * according to HIGHP.
450  */
451 static void mask_address(int af, ipaddr *a, int plen, int highp)
452 {
453   switch (af) {
454     case AF_INET: {
455       unsigned long addr = ntohl(a->v4.s_addr);
456       unsigned long mask = plen ? ~0ul << (32 - plen) : 0;
457       addr &= mask;
458       if (highp) addr |= ~mask;
459       a->v4.s_addr = htonl(addr & 0xffffffff);
460     } break;
461     case AF_INET6: {
462       int i = plen/8;
463       unsigned m = (0xff << (8 - plen%8)) & 0xff;
464       unsigned s = highp ? 0xff : 0;
465       if (m) {
466         a->v6.s6_addr[i] = (a->v6.s6_addr[i] & m) | (s & ~m);
467         i++;
468       }
469       for (; i < 16; i++) a->v6.s6_addr[i] = s;
470     } break;
471     default:
472       abort();
473   }
474 }
475
476 /* Write a presentation form of SA to BUF, a buffer of length SZ.  LEN is the
477  * address length; if it's zero, look it up based on the address family.
478  * Return a pointer to the string (which might, in an emergency, be a static
479  * string rather than your buffer).
480  */
481 static char *present_sockaddr(const struct sockaddr *sa, socklen_t len,
482                               char *buf, size_t sz)
483 {
484 #define WANT(n_) do { if (sz < (n_)) goto nospace; } while (0)
485 #define PUTC(c_) do { *buf++ = (c_); sz--; } while (0)
486
487   if (!sa) return "<null-address>";
488   if (!sz) return "<no-space-in-buffer>";
489   if (!len) len = family_socklen(sa->sa_family);
490
491   switch (sa->sa_family) {
492     case AF_UNIX: {
493       struct sockaddr_un *sun = SUN(sa);
494       char *p = sun->sun_path;
495       size_t n = len - offsetof(struct sockaddr_un, sun_path);
496
497       assert(n);
498       if (*p == 0) {
499         WANT(1); PUTC('@');
500         p++; n--;
501         while (n) {
502           switch (*p) {
503             case 0: WANT(2); PUTC('\\'); PUTC('0'); break;
504             case '\a': WANT(2); PUTC('\\'); PUTC('a'); break;
505             case '\n': WANT(2); PUTC('\\'); PUTC('n'); break;
506             case '\r': WANT(2); PUTC('\\'); PUTC('r'); break;
507             case '\t': WANT(2); PUTC('\\'); PUTC('t'); break;
508             case '\v': WANT(2); PUTC('\\'); PUTC('v'); break;
509             case '\\': WANT(2); PUTC('\\'); PUTC('\\'); break;
510             default:
511               if (*p > ' ' && *p <= '~')
512                 { WANT(1); PUTC(*p); }
513               else {
514                 WANT(4); PUTC('\\'); PUTC('x');
515                 PUTC((*p >> 4)&0xf); PUTC((*p >> 0)&0xf);
516               }
517               break;
518           }
519           p++; n--;
520         }
521       } else {
522         if (*p != '/') { WANT(2); PUTC('.'); PUTC('/'); }
523         while (n && *p) { WANT(1); PUTC(*p); p++; n--; }
524       }
525       WANT(1); PUTC(0);
526     } break;
527     case AF_INET: case AF_INET6: {
528       char addrbuf[NI_MAXHOST], portbuf[NI_MAXSERV];
529       int err = getnameinfo(sa, len,
530                             addrbuf, sizeof(addrbuf),
531                             portbuf, sizeof(portbuf),
532                             NI_NUMERICHOST | NI_NUMERICSERV);
533       assert(!err);
534       snprintf(buf, sz, strchr(addrbuf, ':') ? "[%s]:%s" : "%s:%s",
535                addrbuf, portbuf);
536     } break;
537     default:
538       snprintf(buf, sz, "<unknown-address-family %d>", sa->sa_family);
539       break;
540   }
541   return (buf);
542
543 nospace:
544   buf[sz - 1] = 0;
545   return (buf);
546 }
547
548 /* Guess the family of a textual socket address. */
549 static int guess_address_family(const char *p)
550   { return (strchr(p, ':') ? AF_INET6 : AF_INET); }
551
552 /* Parse a socket address P and write the result to SA. */
553 static int parse_sockaddr(struct sockaddr *sa, const char *p)
554 {
555   char buf[ADDRBUFSZ];
556   char *q;
557   struct addrinfo *ai, ai_hint = { 0 };
558
559   if (strlen(p) >= sizeof(buf) - 1) return (-1);
560   strcpy(buf, p); p = buf;
561   if (*p != '[') {
562     if ((q = strchr(p, ':')) == 0) return (-1);
563     *q++ = 0;
564   } else {
565     p++;
566     if ((q = strchr(p, ']')) == 0) return (-1);
567     *q++ = 0;
568     if (*q != ':') return (-1);
569     q++;
570   }
571
572   ai_hint.ai_family = AF_UNSPEC;
573   ai_hint.ai_socktype = SOCK_DGRAM;
574   ai_hint.ai_flags = AI_NUMERICHOST | AI_NUMERICSERV;
575   if (getaddrinfo(p, q, &ai_hint, &ai)) return (-1);
576   memcpy(sa, ai->ai_addr, ai->ai_addrlen);
577   freeaddrinfo(ai);
578   return (0);
579 }
580
581 /*----- Access control lists ----------------------------------------------*/
582
583 #ifdef DEBUG
584
585 static void dump_addrrange(int af, const ipaddr *min, const ipaddr *max)
586 {
587   char buf[ADDRBUFSZ];
588   const char *p;
589   int plen;
590
591   plen = common_prefix_length(af, min, max);
592   p = inet_ntop(af, min, buf, sizeof(buf));
593   fprintf(stderr, strchr(p, ':') ? "[%s]" : "%s", p);
594   if (plen < 0) {
595     p = inet_ntop(af, &max, buf, sizeof(buf));
596     fprintf(stderr, strchr(p, ':') ? "-[%s]" : "-%s", p);
597   } else if (plen < address_width(af))
598     fprintf(stderr, "/%d", plen);
599 }
600
601 /* Write to standard error a description of the ACL node A. */
602 static void dump_aclnode(const aclnode *a)
603 {
604   fprintf(stderr, "noip(%d):   %c ", getpid(), a->act ? '+' : '-');
605   dump_addrrange(a->af, &a->minaddr, &a->maxaddr);
606   if (a->minport != 0 || a->maxport != 0xffff) {
607     fprintf(stderr, ":%u", (unsigned)a->minport);
608     if (a->minport != a->maxport)
609       fprintf(stderr, "-%u", (unsigned)a->maxport);
610   }
611   fputc('\n', stderr);
612 }
613
614 static void dump_acl(const aclnode *a)
615 {
616   int act = ALLOW;
617
618   for (; a; a = a->next) {
619     dump_aclnode(a);
620     act = a->act;
621   }
622   fprintf(stderr, "noip(%d):   [default policy: %s]\n", getpid(),
623           act == ALLOW ? "DENY" : "ALLOW");
624 }
625
626 #endif
627
628 /* Returns nonzero if the ACL A allows the socket address SA. */
629 static int acl_allows_p(const aclnode *a, const struct sockaddr *sa)
630 {
631   unsigned short port = port_from_sockaddr(sa);
632   int act = ALLOW;
633   Dpid;
634
635   D({ char buf[ADDRBUFSZ];
636       fprintf(stderr, "noip(%d): check %s\n", pid,
637               present_sockaddr(sa, 0, buf, sizeof(buf))); })
638   for (; a; a = a->next) {
639     D( dump_aclnode(a); )
640     if (a->af == sa->sa_family &&
641         sockaddr_in_range_p(sa, &a->minaddr, &a->maxaddr) &&
642         a->minport <= port && port <= a->maxport) {
643       D( fprintf(stderr, "noip(%d): aha!  %s\n", pid,
644                  a->act ? "ALLOW" : "DENY"); )
645       return (a->act);
646     }
647     act = a->act;
648   }
649   D( fprintf(stderr, "noip(%d): nothing found: %s\n", pid,
650              act ? "DENY" : "ALLOW"); )
651   return (!act);
652 }
653
654 /*----- Socket address conversion -----------------------------------------*/
655
656 /* Return a uniformly distributed integer between MIN and MAX inclusive. */
657 static unsigned randrange(unsigned min, unsigned max)
658 {
659   unsigned mask, i;
660
661   /* It's so nice not to have to care about the quality of the generator
662    * much!
663    */
664   max -= min;
665   for (mask = 1; mask < max; mask = (mask << 1) | 1)
666     ;
667   do i = rand() & mask; while (i > max);
668   return (i + min);
669 }
670
671 /* Return the status of Unix-domain socket address SUN.  Returns: UNUSED if
672  * the socket doesn't exist; USED if the path refers to an active socket, or
673  * isn't really a socket at all, or we can't tell without a careful search
674  * and QUICKP is set; or STALE if the file refers to a socket which isn't
675  * being used any more.
676  */
677 static int unix_socket_status(struct sockaddr_un *sun, int quickp)
678 {
679   struct stat st;
680   FILE *fp = 0;
681   size_t len, n;
682   int rc;
683   char buf[256];
684
685   /* If we can't find the socket node, then it's definitely not in use.  If
686    * we get some other error, then this socket is weird.
687    */
688   if (stat(sun->sun_path, &st))
689     return (errno == ENOENT ? UNUSED : USED);
690
691   /* If it's not a socket, then something weird is going on.  If we're just
692    * probing quickly to find a spare port, then existence is sufficient to
693    * discourage us now.
694    */
695   if (!S_ISSOCK(st.st_mode) || quickp)
696     return (USED);
697
698   /* The socket's definitely there, but is anyone actually still holding it
699    * open?  The only way I know to discover this is to trundle through
700    * `/proc/net/unix'.  If there's no entry, then the socket must be stale.
701    */
702   rc = USED;
703   if ((fp = fopen("/proc/net/unix", "r")) == 0)
704     goto done;
705   if (!fgets(buf, sizeof(buf), fp)) goto done; /* skip header */
706   len = strlen(sun->sun_path);
707   rc = 0;
708   while (fgets(buf, sizeof(buf), fp)) {
709     n = strlen(buf);
710     if (n >= len + 2 && buf[n - len - 2] == ' ' && buf[n - 1] == '\n' &&
711         memcmp(buf + n - len - 1, sun->sun_path, len) == 0) {
712       rc |= USED;
713     }
714   }
715   if (ferror(fp))
716     goto done;
717   if (!rc) rc = STALE;
718 done:
719   if (fp) fclose(fp);
720
721   /* All done. */
722   return (rc);
723 }
724
725 /* Encode SA as a Unix-domain address SUN, and return whether it's currently
726  * in use.
727  */
728 static int encode_single_inet_addr(const struct sockaddr *sa,
729                                    struct sockaddr_un *sun,
730                                    int quickp)
731 {
732   char buf[ADDRBUFSZ];
733   int rc;
734
735   snprintf(sun->sun_path, sizeof(sun->sun_path), "%s/%s", sockdir,
736            present_sockaddr(sa, 0, buf, sizeof(buf)));
737   rc = unix_socket_status(sun, quickp);
738   if (rc == STALE) unlink(sun->sun_path);
739   return (rc);
740 }
741
742 /* Convert the IP address SA to a Unix-domain address SUN.  Fail if the
743  * address seems already taken.  If DESPARATEP then try cleaning up stale old
744  * sockets.
745  */
746 static int encode_unused_inet_addr(struct sockaddr *sa,
747                                    struct sockaddr_un *sun,
748                                    int desperatep)
749 {
750   address waddr, maddr;
751   struct sockaddr_un wsun;
752   int port = port_from_sockaddr(sa);
753
754   /* First, look for an exact match.  Only look quickly unless we're
755    * desperate.  If the socket is in use, we fail here.  (This could get
756    * racy.  Let's not worry about that for now.)
757    */
758   if (encode_single_inet_addr(sa, sun, !desperatep)&USED)
759     return (-1);
760
761   /* Next, check the corresponding wildcard address, so as to avoid
762    * inadvertant collisions with listeners.  Do this in the same way.
763    */
764   wildcard_address(sa->sa_family, &waddr.sa);
765   port_to_sockaddr(&waddr.sa, port);
766   if (encode_single_inet_addr(&waddr.sa, &wsun, !desperatep)&USED)
767     return (-1);
768
769   /* We're not done yet.  If this is an IPv4 address, then /also/ check (a)
770    * the v6-mapped version, (b) the v6-mapped v4 wildcard, /and/ (c) the v6
771    * wildcard.  Ugh!
772    */
773   if (sa->sa_family == AF_INET) {
774     map_ipv4_sockaddr(&maddr.sin6, SIN(&sa));
775     if (encode_single_inet_addr(&maddr.sa, &wsun, !desperatep)&USED)
776       return (-1);
777
778     map_ipv4_sockaddr(&maddr.sin6, &waddr.sin);
779     if (encode_single_inet_addr(&maddr.sa, &wsun, !desperatep)&USED)
780       return (-1);
781
782     wildcard_address(AF_INET6, &waddr.sa);
783     port_to_sockaddr(&waddr.sa, port);
784     if (encode_single_inet_addr(&waddr.sa, &wsun, !desperatep)&USED)
785       return (-1);
786   }
787
788   /* All is well. */
789   return (0);
790 }
791
792 /* Encode the Internet address SA as a Unix-domain address SUN.  If the flag
793  * `ENCF_FRESH' is set, and SA's port number is zero, then we pick an
794  * arbitrary local port.  Otherwise we pick the port given.  There's an
795  * unpleasant hack to find servers bound to local wildcard addresses.
796  * Returns zero on success; -1 on failure.
797  */
798 #define ENCF_FRESH 1u
799 static int encode_inet_addr(struct sockaddr_un *sun,
800                             const struct sockaddr *sa,
801                             unsigned f)
802 {
803   int i;
804   int desperatep = 0;
805   address addr;
806   struct sockaddr_in6 sin6;
807   int port = port_from_sockaddr(sa);
808   int rc;
809   char buf[ADDRBUFSZ];
810
811   D( fprintf(stderr, "noip(%d): encode %s (%s)", getpid(),
812              present_sockaddr(sa, 0, buf, sizeof(buf)),
813              (f&ENCF_FRESH) ? "FRESH" : "EXISTING"); )
814
815   /* Start making the Unix-domain address. */
816   sun->sun_family = AF_UNIX;
817
818   if (port || !(f&ENCF_FRESH)) {
819
820     /* Try the address as given.  If it's in use, or we don't necessarily
821      * want an existing socket, then we're done.
822      */
823     rc = encode_single_inet_addr(sa, sun, 0);
824     if ((rc&USED) || (f&ENCF_FRESH)) goto found;
825
826     /* We're looking for a socket which already exists.  This is
827      * unfortunately difficult, because we must deal both with wildcards and
828      * v6-mapped IPv4 addresses.
829      *
830      *   * We've just tried searching for a socket whose name is an exact
831      *     match for our remote address.  If the remote address is IPv4, then
832      *     we should try again with the v6-mapped equivalent.
833      *
834      *   * Failing that, we try again with the wildcard address for the
835      *     appropriate address family.
836      *
837      *   * Failing /that/, if the remote address is IPv4, then we try
838      *     /again/, increasingly desperately, first with the v6-mapped IPv4
839      *     wildcard address, and then with the IPv6 wildcard address.  This
840      *     will cause magic v6-mapping to occur when the connection is
841      *     accepted, which we hope won't cause too much trouble.
842      */
843
844     if (sa->sa_family == AF_INET) {
845       map_ipv4_sockaddr(&addr.sin6, SIN(sa));
846       if (encode_single_inet_addr(&addr.sa, sun, 0)&USED) goto found;
847     }
848
849     wildcard_address(sa->sa_family, &addr.sa);
850     port_to_sockaddr(&addr.sa, port);
851     if (encode_single_inet_addr(&addr.sa, sun, 0)&USED) goto found;
852
853     if (sa->sa_family == AF_INET) {
854       map_ipv4_sockaddr(&sin6, &addr.sin);
855       if (encode_single_inet_addr(SA(&sin6), sun, 0)&USED) goto found;
856       wildcard_address(AF_INET6, &addr.sa);
857       port_to_sockaddr(&addr.sa, port);
858       if (encode_single_inet_addr(&addr.sa, sun, 0)&USED) goto found;
859     }
860
861     /* Well, this isn't going to work (unless a miraculous race is lost), but
862      * we might as well try.
863      */
864     encode_single_inet_addr(sa, sun, 1);
865
866   } else {
867     /* We want a fresh new socket. */
868
869     /* Make a copy of the given address, because we're going to mangle it. */
870     copy_sockaddr(&addr.sa, sa);
871
872     /* Try a few random-ish port numbers to see if any of them is spare. */
873     for (i = 0; i < 10; i++) {
874       port_to_sockaddr(&addr.sa, randrange(minautoport, maxautoport));
875       if (!encode_unused_inet_addr(&addr.sa, sun, 0)) goto found;
876     }
877
878     /* Things must be getting tight.  Work through all of the autoport range
879      * to see if we can find a spare one.  The first time, just do it the
880      * quick way; if that doesn't work, then check harder for stale sockets.
881      */
882     for (desperatep = 0; desperatep < 2; desperatep++) {
883       for (i = minautoport; i <= maxautoport; i++) {
884         port_to_sockaddr(&addr.sa, i);
885         if (!encode_unused_inet_addr(&addr.sa, sun, 0)) goto found;
886       }
887     }
888
889     /* We failed to find any free ports. */
890     errno = EADDRINUSE;
891     D( fprintf(stderr, " -- can't resolve\n"); )
892     return (-1);
893   }
894
895   /* Success. */
896 found:
897   D( fprintf(stderr, " -> `%s'\n", sun->sun_path); )
898   return (0);
899 }
900
901 /* Decode the Unix address SUN to an Internet address SIN.  If AF_HINT is
902  * nonzero, an empty address (indicative of an unbound Unix-domain socket) is
903  * translated to a wildcard Internet address of the appropriate family.
904  * Returns zero on success; -1 on failure (e.g., it wasn't one of our
905  * addresses).
906  */
907 static int decode_inet_addr(struct sockaddr *sa, int af_hint,
908                             const struct sockaddr_un *sun,
909                             socklen_t len)
910 {
911   char buf[ADDRBUFSZ];
912   size_t n = strlen(sockdir), nn;
913   address addr;
914
915   if (!sa) sa = &addr.sa;
916   if (sun->sun_family != AF_UNIX) return (-1);
917   if (len > sizeof(*sun)) return (-1);
918   ((char *)sun)[len] = 0;
919   nn = strlen(sun->sun_path);
920   D( fprintf(stderr, "noip(%d): decode `%s'", getpid(), sun->sun_path); )
921   if (af_hint && !sun->sun_path[0]) {
922     wildcard_address(af_hint, sa);
923     D( fprintf(stderr, " -- unbound socket\n"); )
924     return (0);
925   }
926   if (nn < n + 1 || nn - n >= sizeof(buf) || sun->sun_path[n] != '/' ||
927       memcmp(sun->sun_path, sockdir, n) != 0) {
928     D( fprintf(stderr, " -- not one of ours\n"); )
929     return (-1);
930   }
931   if (parse_sockaddr(sa, sun->sun_path + n + 1)) return (-1);
932   D( fprintf(stderr, " -> %s\n",
933              present_sockaddr(sa, 0, buf, sizeof(buf))); )
934   return (0);
935 }
936
937 /* SK is (or at least might be) a Unix-domain socket we created when an
938  * Internet socket was asked for.  We've decided it should be an Internet
939  * socket after all, with family AF_HINT, so convert it.  If TMP is not null,
940  * then don't replace the existing descriptor: store the new socket in *TMP
941  * and return zero.
942  */
943 static int fixup_real_ip_socket(int sk, int af_hint, int *tmp)
944 {
945   int nsk;
946   int type;
947   int f, fd;
948   struct sockaddr_un sun;
949   address addr;
950   socklen_t len;
951
952 #define OPTS(_)                                                         \
953   _(DEBUG, int)                                                         \
954   _(REUSEADDR, int)                                                     \
955   _(DONTROUTE, int)                                                     \
956   _(BROADCAST, int)                                                     \
957   _(SNDBUF, int)                                                        \
958   _(RCVBUF, int)                                                        \
959   _(OOBINLINE, int)                                                     \
960   _(NO_CHECK, int)                                                      \
961   _(LINGER, struct linger)                                              \
962   _(BSDCOMPAT, int)                                                     \
963   _(RCVLOWAT, int)                                                      \
964   _(RCVTIMEO, struct timeval)                                           \
965   _(SNDTIMEO, struct timeval)
966
967   len = sizeof(sun);
968   if (real_getsockname(sk, SA(&sun), &len))
969     return (-1);
970   if (decode_inet_addr(&addr.sa, af_hint, &sun, len))
971     return (0); /* Not one of ours */
972   len = sizeof(type);
973   if (real_getsockopt(sk, SOL_SOCKET, SO_TYPE, &type, &len) < 0 ||
974       (nsk = real_socket(addr.sa.sa_family, type, 0)) < 0)
975     return (-1);
976 #define FIX(opt, ty) do {                                               \
977   ty ov_;                                                               \
978   len = sizeof(ov_);                                                    \
979   if (real_getsockopt(sk, SOL_SOCKET, SO_##opt, &ov_, &len) < 0 ||      \
980       real_setsockopt(nsk, SOL_SOCKET, SO_##opt, &ov_, len)) {          \
981     close(nsk);                                                         \
982     return (-1);                                                        \
983   }                                                                     \
984 } while (0);
985   OPTS(FIX)
986 #undef FIX
987   if (tmp)
988     *tmp = nsk;
989   else {
990     if ((f = fcntl(sk, F_GETFL)) < 0 ||
991         (fd = fcntl(sk, F_GETFD)) < 0 ||
992         fcntl(nsk, F_SETFL, f) < 0 ||
993         dup2(nsk, sk) < 0) {
994       close(nsk);
995       return (-1);
996     }
997     unlink(sun.sun_path);
998     close(nsk);
999     if (fcntl(sk, F_SETFD, fd) < 0) {
1000       perror("noip: fixup_real_ip_socket F_SETFD");
1001       abort();
1002     }
1003   }
1004   return (0);
1005 }
1006
1007 /* We found the real address SA, with length LEN; if it's a Unix-domain
1008  * address corresponding to a fake socket, convert it to cover up the
1009  * deception.  Whatever happens, put the result at FAKE and store its length
1010  * at FAKELEN.
1011  */
1012 #define FNF_V6MAPPED 1u
1013 static void return_fake_name(struct sockaddr *sa, socklen_t len,
1014                              struct sockaddr *fake, socklen_t *fakelen,
1015                              unsigned f)
1016 {
1017   address addr;
1018   struct sockaddr_in6 sin6;
1019   socklen_t alen;
1020
1021   if (sa->sa_family == AF_UNIX &&
1022       !decode_inet_addr(&addr.sa, 0, SUN(sa), len)) {
1023     if (addr.sa.sa_family != AF_INET || !(f&FNF_V6MAPPED)) {
1024       sa = &addr.sa;
1025       len = family_socklen(addr.sa.sa_family);
1026     } else {
1027       map_ipv4_sockaddr(&sin6, &addr.sin);
1028       sa = SA(&sin6);
1029       len = family_socklen(AF_INET6);
1030     }
1031   }
1032   alen = len;
1033   if (len > *fakelen) len = *fakelen;
1034   if (len > 0) memcpy(fake, sa, len);
1035   *fakelen = alen;
1036 }
1037
1038 /* Variant of `return_fake_name' above, specifically handling the weirdness
1039  * of remote v6-mapped IPv4 addresses.  If SK's fake local address is IPv6,
1040  * and the remote address is IPv4, then return a v6-mapped version of the
1041  * remote address.
1042  */
1043 static void return_fake_peer(int sk, struct sockaddr *sa, socklen_t len,
1044                              struct sockaddr *fake, socklen_t *fakelen)
1045 {
1046   char sabuf[1024];
1047   socklen_t mylen = sizeof(sabuf);
1048   unsigned fnf = 0;
1049   address addr;
1050   int rc;
1051
1052   PRESERVING_ERRNO({
1053     rc = real_getsockname(sk, SA(sabuf), &mylen);
1054     if (!rc && sa->sa_family == AF_UNIX &&
1055         !decode_inet_addr(&addr.sa, 0, SUN(sabuf), mylen) &&
1056         addr.sa.sa_family == AF_INET6)
1057       fnf |= FNF_V6MAPPED;
1058   });
1059   return_fake_name(sa, len, fake, fakelen, fnf);
1060 }
1061
1062 /*----- Implicit binding --------------------------------------------------*/
1063
1064 #ifdef DEBUG
1065
1066 static void dump_impbind(const impbind *i)
1067 {
1068   char buf[ADDRBUFSZ];
1069
1070   fprintf(stderr, "noip(%d):   ", getpid());
1071   dump_addrrange(i->af, &i->minaddr, &i->maxaddr);
1072   switch (i->how) {
1073     case SAME: fprintf(stderr, " <self>"); break;
1074     case EXPLICIT:
1075       fprintf(stderr, " %s", inet_ntop(i->af, &i->bindaddr,
1076                                        buf, sizeof(buf)));
1077       break;
1078     default: abort();
1079   }
1080   fputc('\n', stderr);
1081 }
1082
1083 static void dump_impbind_list(void)
1084 {
1085   const impbind *i;
1086
1087   for (i = impbinds; i; i = i->next) dump_impbind(i);
1088 }
1089
1090 #endif
1091
1092 /* The socket SK is about to be used to communicate with the remote address
1093  * SA.  Assign it a local address so that getpeername(2) does something
1094  * useful.
1095  *
1096  * If the flag `IBF_V6MAPPED' is set then, then SA must be an `AF_INET'
1097  * address; after deciding on the appropriate local address, convert it to be
1098  * an IPv4-mapped IPv6 address before final conversion to a Unix-domain
1099  * socket address and actually binding.  Note that this could well mean that
1100  * the socket ends up bound to the v6-mapped v4 wildcard address
1101  * ::ffff:0.0.0.0, which looks very strange but is meaningful.
1102  */
1103 #define IBF_V6MAPPED 1u
1104 static int do_implicit_bind(int sk, const struct sockaddr *sa, unsigned f)
1105 {
1106   address addr;
1107   struct sockaddr_in6 sin6;
1108   struct sockaddr_un sun;
1109   const impbind *i;
1110   Dpid;
1111
1112   D( fprintf(stderr, "noip(%d): checking impbind list...\n", pid); )
1113   for (i = impbinds; i; i = i->next) {
1114     D( dump_impbind(i); )
1115     if (sa->sa_family == i->af &&
1116         sockaddr_in_range_p(sa, &i->minaddr, &i->maxaddr)) {
1117       D( fprintf(stderr, "noip(%d): match!\n", pid); )
1118       addr.sa.sa_family = sa->sa_family;
1119       ipaddr_to_sockaddr(&addr.sa, &i->bindaddr);
1120       goto found;
1121     }
1122   }
1123   D( fprintf(stderr, "noip(%d): no match; using wildcard\n", pid); )
1124   wildcard_address(sa->sa_family, &addr.sa);
1125 found:
1126   if (addr.sa.sa_family != AF_INET || !(f&IBF_V6MAPPED)) sa = &addr.sa;
1127   else { map_ipv4_sockaddr(&sin6, &addr.sin); sa = SA(&sin6); }
1128   encode_inet_addr(&sun, sa, ENCF_FRESH);
1129   D( fprintf(stderr, "noip(%d): implicitly binding to %s\n",
1130              pid, sun.sun_path); )
1131   if (real_bind(sk, SA(&sun), SUN_LEN(&sun))) return (-1);
1132   return (0);
1133 }
1134
1135 /* The socket SK is about to communicate with the remote address *SA.  Ensure
1136  * that the socket has a local address, and adjust *SA to refer to the real
1137  * remote endpoint.
1138  *
1139  * If we need to translate the remote address, then the Unix-domain endpoint
1140  * address will end in *SUN, and *SA will be adjusted to point to it.
1141  */
1142 static int fixup_client_socket(int sk, const struct sockaddr **sa_r,
1143                                socklen_t *len_r, struct sockaddr_un *sun)
1144 {
1145   struct sockaddr_in sin;
1146   socklen_t mylen = sizeof(*sun);
1147   const struct sockaddr *sa = *sa_r;
1148   unsigned ibf = 0;
1149
1150   /* If this isn't a Unix-domain socket then there's nothing to do. */
1151   if (real_getsockname(sk, SA(sun), &mylen) < 0) return (-1);
1152   if (sun->sun_family != AF_UNIX) return (0);
1153   if (mylen < sizeof(*sun)) ((char *)sun)[mylen] = 0;
1154
1155   /* If the remote address is v6-mapped IPv4, then unmap it so as to search
1156    * for IPv4 servers.  Also remember to v6-map the local address when we
1157    * autobind.
1158    */
1159   if (sa->sa_family == AF_INET6 && !(unmap_ipv4_sockaddr(&sin, SIN6(sa)))) {
1160     sa = SA(&sin);
1161     ibf |= IBF_V6MAPPED;
1162   }
1163
1164   /* If we're allowed to talk to a real remote endpoint, then fix things up
1165    * as necessary and proceed.
1166    */
1167   if (acl_allows_p(connect_real, sa)) {
1168     if (fixup_real_ip_socket(sk, (*sa_r)->sa_family, 0)) return (-1);
1169     return (0);
1170   }
1171
1172   /* Speaking of which, if we don't have a local address, then we should
1173    * arrange one now.
1174    */
1175   if (!sun->sun_path[0] && do_implicit_bind(sk, sa, ibf)) return (-1);
1176
1177   /* And then come up with a remote address. */
1178   encode_inet_addr(sun, sa, 0);
1179   *sa_r = SA(sun);
1180   *len_r = SUN_LEN(sun);
1181   return (0);
1182 }
1183
1184 /*----- Configuration -----------------------------------------------------*/
1185
1186 /* Return the process owner's home directory. */
1187 static char *home(void)
1188 {
1189   char *p;
1190   struct passwd *pw;
1191
1192   if (getuid() == uid &&
1193       (p = getenv("HOME")) != 0)
1194     return (p);
1195   else if ((pw = getpwuid(uid)) != 0)
1196     return (pw->pw_dir);
1197   else
1198     return "/notexist";
1199 }
1200
1201 /* Return a good temporary directory to use. */
1202 static char *tmpdir(void)
1203 {
1204   char *p;
1205
1206   if ((p = getenv("TMPDIR")) != 0) return (p);
1207   else if ((p = getenv("TMP")) != 0) return (p);
1208   else return ("/tmp");
1209 }
1210
1211 /* Return the user's name, or at least something distinctive. */
1212 static char *user(void)
1213 {
1214   static char buf[16];
1215   char *p;
1216   struct passwd *pw;
1217
1218   if ((p = getenv("USER")) != 0) return (p);
1219   else if ((p = getenv("LOGNAME")) != 0) return (p);
1220   else if ((pw = getpwuid(uid)) != 0) return (pw->pw_name);
1221   else {
1222     snprintf(buf, sizeof(buf), "uid-%lu", (unsigned long)uid);
1223     return (buf);
1224   }
1225 }
1226
1227 /* Skip P over space characters. */
1228 #define SKIPSPC do { while (*p && isspace(UC(*p))) p++; } while (0)
1229
1230 /* Set Q to point to the next word following P, null-terminate it, and step P
1231  * past it. */
1232 #define NEXTWORD(q) do {                                                \
1233   SKIPSPC;                                                              \
1234   q = p;                                                                \
1235   while (*p && !isspace(UC(*p))) p++;                                   \
1236   if (*p) *p++ = 0;                                                     \
1237 } while (0)
1238
1239 /* Set Q to point to the next dotted-quad address, store the ending delimiter
1240  * in DEL, null-terminate it, and step P past it. */
1241 static void parse_nextaddr(char **pp, char **qq, int *del)
1242 {
1243   char *p = *pp;
1244
1245   SKIPSPC;
1246   if (*p == '[') {
1247     p++; SKIPSPC;
1248     *qq = p;
1249     p += strcspn(p, "]");
1250     if (*p) *p++ = 0;
1251     *del = 0;
1252   } else {
1253     *qq = p;
1254     while (*p && (*p == '.' || isdigit(UC(*p)))) p++;
1255     *del = *p;
1256     if (*p) *p++ = 0;
1257   }
1258   *pp = p;
1259 }
1260
1261 /* Set Q to point to the next decimal number, store the ending delimiter in
1262  * DEL, null-terminate it, and step P past it. */
1263 #define NEXTNUMBER(q, del) do {                                         \
1264   SKIPSPC;                                                              \
1265   q = p;                                                                \
1266   while (*p && isdigit(UC(*p))) p++;                                    \
1267   del = *p;                                                             \
1268   if (*p) *p++ = 0;                                                     \
1269 } while (0)
1270
1271 /* Push the character DEL back so we scan it again, unless it's zero
1272  * (end-of-file). */
1273 #define RESCAN(del) do { if (del) *--p = del; } while (0)
1274
1275 /* Evaluate true if P is pointing to the word KW (and not some longer string
1276  * of which KW is a prefix). */
1277
1278 #define KWMATCHP(kw) (strncmp(p, kw, sizeof(kw) - 1) == 0 &&            \
1279                       !isalnum(UC(p[sizeof(kw) - 1])) &&                \
1280                       (p += sizeof(kw) - 1))
1281
1282 /* Parse a port list, starting at *PP.  Port lists have the form
1283  * [:LOW[-HIGH]]: if omitted, all ports are included; if HIGH is omitted,
1284  * it's as if HIGH = LOW.  Store LOW in *MIN, HIGH in *MAX and set *PP to the
1285  * rest of the string.
1286  */
1287 static void parse_ports(char **pp, unsigned short *min, unsigned short *max)
1288 {
1289   char *p = *pp, *q;
1290   int del;
1291
1292   SKIPSPC;
1293   if (*p != ':')
1294     { *min = 0; *max = 0xffff; }
1295   else {
1296     p++;
1297     NEXTNUMBER(q, del); *min = strtoul(q, 0, 0); RESCAN(del);
1298     SKIPSPC;
1299     if (*p == '-')
1300       { p++; NEXTNUMBER(q, del); *max = strtoul(q, 0, 0); RESCAN(del); }
1301     else
1302       *max = *min;
1303   }
1304   *pp = p;
1305 }
1306
1307 /* Parse an address range designator starting at PP and store a
1308  * representation of it in R.  An address range designator has the form:
1309  *
1310  *      any | local | ADDR | ADDR - ADDR | ADDR/ADDR | ADDR/INT
1311  */
1312 static int parse_addrrange(char **pp, addrrange *r)
1313 {
1314   char *p = *pp, *q;
1315   int n;
1316   int del;
1317   int af;
1318
1319   SKIPSPC;
1320   if (KWMATCHP("any")) r->type = ANY;
1321   else if (KWMATCHP("local")) r->type = LOCAL;
1322   else {
1323     parse_nextaddr(&p, &q, &del);
1324     af = guess_address_family(q);
1325     if (inet_pton(af, q, &r->u.range.min) <= 0) goto bad;
1326     RESCAN(del);
1327     SKIPSPC;
1328     if (*p == '-') {
1329       p++;
1330       parse_nextaddr(&p, &q, &del);
1331       if (inet_pton(af, q, &r->u.range.max) <= 0) goto bad;
1332       RESCAN(del);
1333     } else if (*p == '/') {
1334       p++;
1335       NEXTNUMBER(q, del);
1336       n = strtoul(q, 0, 0);
1337       r->u.range.max = r->u.range.min;
1338       mask_address(af, &r->u.range.min, n, 0);
1339       mask_address(af, &r->u.range.max, n, 1);
1340       RESCAN(del);
1341     } else
1342       r->u.range.max = r->u.range.min;
1343     r->type = RANGE;
1344     r->u.range.af = af;
1345   }
1346   *pp = p;
1347   return (0);
1348
1349 bad:
1350   return (-1);
1351 }
1352
1353 /* Call FUNC on each individual address range in R. */
1354 static void foreach_addrrange(const addrrange *r,
1355                               void (*func)(int af,
1356                                            const ipaddr *min,
1357                                            const ipaddr *max,
1358                                            void *p),
1359                               void *p)
1360 {
1361   ipaddr minaddr, maxaddr;
1362   int i, af;
1363
1364   switch (r->type) {
1365     case EMPTY:
1366       break;
1367     case ANY:
1368       for (i = 0; address_families[i] >= 0; i++) {
1369         af = address_families[i];
1370         memset(&minaddr, 0, sizeof(minaddr));
1371         maxaddr = minaddr; mask_address(af, &maxaddr, 0, 1);
1372         func(af, &minaddr, &maxaddr, p);
1373       }
1374       break;
1375     case LOCAL:
1376       for (i = 0; address_families[i] >= 0; i++) {
1377         af = address_families[i];
1378         memset(&minaddr, 0, sizeof(minaddr));
1379         maxaddr = minaddr; mask_address(af, &maxaddr, 0, 1);
1380         func(af, &minaddr, &minaddr, p);
1381         func(af, &maxaddr, &maxaddr, p);
1382       }
1383       for (i = 0; i < n_local_ipaddrs; i++) {
1384         func(local_ipaddrs[i].af,
1385              &local_ipaddrs[i].addr, &local_ipaddrs[i].addr,
1386              p);
1387       }
1388       break;
1389     case RANGE:
1390       func(r->u.range.af, &r->u.range.min, &r->u.range.max, p);
1391       break;
1392     default:
1393       abort();
1394   }
1395 }
1396
1397 struct add_aclnode_ctx {
1398   int act;
1399   unsigned short minport, maxport;
1400   aclnode ***tail;
1401 };
1402
1403 static void add_aclnode(int af, const ipaddr *min, const ipaddr *max,
1404                         void *p)
1405 {
1406   struct add_aclnode_ctx *ctx = p;
1407   aclnode *a;
1408
1409   NEW(a);
1410   a->act = ctx->act;
1411   a->af = af;
1412   a->minaddr = *min; a->maxaddr = *max;
1413   a->minport = ctx->minport; a->maxport = ctx->maxport;
1414   **ctx->tail = a; *ctx->tail = &a->next;
1415 }
1416
1417 /* Parse an ACL line.  *PP points to the end of the line; *TAIL points to
1418  * the list tail (i.e., the final link in the list).  An ACL entry has the
1419  * form +|- ADDR-RANGE PORTS
1420  * where PORTS is parsed by parse_ports above; an ACL line consists of a
1421  * comma-separated sequence of entries..
1422  */
1423 static void parse_acl_line(char **pp, aclnode ***tail)
1424 {
1425   struct add_aclnode_ctx ctx;
1426   addrrange r;
1427   char *p = *pp;
1428
1429   ctx.tail = tail;
1430   for (;;) {
1431     SKIPSPC;
1432     if (*p == '+') ctx.act = ALLOW;
1433     else if (*p == '-') ctx.act = DENY;
1434     else goto bad;
1435
1436     p++;
1437     if (parse_addrrange(&p, &r)) goto bad;
1438     parse_ports(&p, &ctx.minport, &ctx.maxport);
1439     foreach_addrrange(&r, add_aclnode, &ctx);
1440     SKIPSPC;
1441     if (*p != ',') break;
1442     if (*p) p++;
1443   }
1444   if (*p) goto bad;
1445   *pp = p;
1446   return;
1447
1448 bad:
1449   D( fprintf(stderr, "noip(%d): bad acl spec (ignored)\n", getpid()); )
1450   return;
1451 }
1452
1453 /* Parse an ACL from an environment variable VAR, attaching it to the list
1454  * TAIL.
1455  */
1456 static void parse_acl_env(const char *var, aclnode ***tail)
1457 {
1458   char *p, *q;
1459
1460   if ((p = getenv(var)) != 0) {
1461     p = q = xstrdup(p);
1462     parse_acl_line(&q, tail);
1463     free(p);
1464   }
1465 }
1466
1467 struct add_impbind_ctx {
1468   int af, how;
1469   ipaddr addr;
1470 };
1471
1472 static void add_impbind(int af, const ipaddr *min, const ipaddr *max,
1473                         void *p)
1474 {
1475   struct add_impbind_ctx *ctx = p;
1476   impbind *i;
1477
1478   if (ctx->af && af != ctx->af) return;
1479   NEW(i);
1480   i->af = af;
1481   i->how = ctx->how;
1482   i->minaddr = *min; i->maxaddr = *max;
1483   switch (ctx->how) {
1484     case EXPLICIT: i->bindaddr = ctx->addr;
1485     case SAME: break;
1486     default: abort();
1487   }
1488   *impbind_tail = i; impbind_tail = &i->next;
1489 }
1490
1491 /* Parse an implicit-bind line.  An implicit-bind entry has the form
1492  * ADDR-RANGE {ADDR | same}
1493  */
1494 static void parse_impbind_line(char **pp)
1495 {
1496   struct add_impbind_ctx ctx;
1497   char *p = *pp, *q;
1498   addrrange r;
1499   int del;
1500
1501   for (;;) {
1502     if (parse_addrrange(&p, &r)) goto bad;
1503     SKIPSPC;
1504     if (KWMATCHP("same")) {
1505       ctx.how = SAME;
1506       ctx.af = 0;
1507     } else {
1508       ctx.how = EXPLICIT;
1509       parse_nextaddr(&p, &q, &del);
1510       ctx.af = guess_address_family(q);
1511       if (inet_pton(ctx.af, q, &ctx.addr) < 0) goto bad;
1512       RESCAN(del);
1513     }
1514     foreach_addrrange(&r, add_impbind, &ctx);
1515     SKIPSPC;
1516     if (*p != ',') break;
1517     if (*p) p++;
1518   }
1519   if (*p) goto bad;
1520   *pp = p;
1521   return;
1522
1523 bad:
1524   D( fprintf(stderr, "noip(%d): bad implicit-bind spec (ignored)\n",
1525              getpid()); )
1526   return;
1527 }
1528
1529 /* Parse implicit-bind instructions from an environment variable VAR,
1530  * attaching it to the list.
1531  */
1532 static void parse_impbind_env(const char *var)
1533 {
1534   char *p, *q;
1535
1536   if ((p = getenv(var)) != 0) {
1537     p = q = xstrdup(p);
1538     parse_impbind_line(&q);
1539     free(p);
1540   }
1541 }
1542
1543 /* Parse the autoports configuration directive.  Syntax is MIN - MAX. */
1544 static void parse_autoports(char **pp)
1545 {
1546   char *p = *pp, *q;
1547   unsigned x, y;
1548   int del;
1549
1550   SKIPSPC;
1551   NEXTNUMBER(q, del); x = strtoul(q, 0, 0); RESCAN(del);
1552   SKIPSPC;
1553   if (*p != '-') goto bad;
1554   p++;
1555   NEXTNUMBER(q, del); y = strtoul(q, 0, 0); RESCAN(del);
1556   minautoport = x; maxautoport = y;
1557   SKIPSPC; if (*p) goto bad;
1558   *pp = p;
1559   return;
1560
1561 bad:
1562   D( fprintf(stderr, "noip(%d): bad port range (ignored)\n", getpid()); )
1563   return;
1564 }
1565
1566 /* Read the configuration from the config file and environment. */
1567 static void readconfig(void)
1568 {
1569   FILE *fp;
1570   char buf[1024];
1571   size_t n;
1572   char *p, *q, *cmd;
1573   Dpid;
1574
1575   parse_acl_env("NOIP_REALBIND_BEFORE", &bind_tail);
1576   parse_acl_env("NOIP_REALCONNECT_BEFORE", &connect_tail);
1577   parse_impbind_env("NOIP_IMPBIND_BEFORE");
1578   if ((p = getenv("NOIP_AUTOPORTS")) != 0) {
1579     p = q = xstrdup(p);
1580     parse_autoports(&q);
1581     free(p);
1582   }
1583   if ((p = getenv("NOIP_CONFIG")) == 0)
1584     snprintf(p = buf, sizeof(buf), "%s/.noip", home());
1585   D( fprintf(stderr, "noip(%d): config file: %s\n", pid, p); )
1586
1587   if ((fp = fopen(p, "r")) == 0) {
1588     D( fprintf(stderr, "noip(%d): couldn't read config: %s\n",
1589                pid, strerror(errno)); )
1590     goto done;
1591   }
1592   while (fgets(buf, sizeof(buf), fp)) {
1593     n = strlen(buf);
1594     p = buf;
1595
1596     SKIPSPC;
1597     if (!*p || *p == '#') continue;
1598     while (n && isspace(UC(buf[n - 1]))) n--;
1599     buf[n] = 0;
1600     NEXTWORD(cmd);
1601     SKIPSPC;
1602
1603     if (strcmp(cmd, "socketdir") == 0)
1604       sockdir = xstrdup(p);
1605     else if (strcmp(cmd, "realbind") == 0)
1606       parse_acl_line(&p, &bind_tail);
1607     else if (strcmp(cmd, "realconnect") == 0)
1608       parse_acl_line(&p, &connect_tail);
1609     else if (strcmp(cmd, "impbind") == 0)
1610       parse_impbind_line(&p);
1611     else if (strcmp(cmd, "autoports") == 0)
1612       parse_autoports(&p);
1613     else if (strcmp(cmd, "debug") == 0)
1614       debug = *p ? atoi(p) : 1;
1615     else
1616       D( fprintf(stderr, "noip(%d): bad config command %s\n", pid, cmd); )
1617   }
1618   fclose(fp);
1619
1620 done:
1621   parse_acl_env("NOIP_REALBIND", &bind_tail);
1622   parse_acl_env("NOIP_REALCONNECT", &connect_tail);
1623   parse_impbind_env("NOIP_IMPBIND");
1624   parse_acl_env("NOIP_REALBIND_AFTER", &bind_tail);
1625   parse_acl_env("NOIP_REALCONNECT_AFTER", &connect_tail);
1626   parse_impbind_env("NOIP_IMPBIND_AFTER");
1627   *bind_tail = 0;
1628   *connect_tail = 0;
1629   *impbind_tail = 0;
1630   if (!sockdir) sockdir = getenv("NOIP_SOCKETDIR");
1631   if (!sockdir) {
1632     snprintf(buf, sizeof(buf), "%s/noip-%s", tmpdir(), user());
1633     sockdir = xstrdup(buf);
1634   }
1635   D( fprintf(stderr, "noip(%d): socketdir: %s\n", pid, sockdir);
1636      fprintf(stderr, "noip(%d): autoports: %u-%u\n",
1637              pid, minautoport, maxautoport);
1638      fprintf(stderr, "noip(%d): realbind acl:\n", pid);
1639      dump_acl(bind_real);
1640      fprintf(stderr, "noip(%d): realconnect acl:\n", pid);
1641      dump_acl(connect_real);
1642      fprintf(stderr, "noip(%d): impbind list:\n", pid);
1643      dump_impbind_list(); )
1644 }
1645
1646 /*----- Overridden system calls -------------------------------------------*/
1647
1648 static void dump_syserr(long rc)
1649   { fprintf(stderr, " => %ld (E%d)\n", rc, errno); }
1650
1651 static void dump_sysresult(long rc)
1652 {
1653   if (rc < 0) dump_syserr(rc);
1654   else fprintf(stderr, " => %ld\n", rc);
1655 }
1656
1657 static void dump_addrresult(long rc, const struct sockaddr *sa,
1658                             socklen_t len)
1659 {
1660   char addrbuf[ADDRBUFSZ];
1661
1662   if (rc < 0) dump_syserr(rc);
1663   else {
1664     fprintf(stderr, " => %ld [%s]\n", rc,
1665             present_sockaddr(sa, len, addrbuf, sizeof(addrbuf)));
1666   }
1667 }
1668
1669 int socket(int pf, int ty, int proto)
1670 {
1671   int sk;
1672
1673   D( fprintf(stderr, "noip(%d): SOCKET pf=%d, type=%d, proto=%d",
1674              getpid(), pf, ty, proto); )
1675
1676   switch (pf) {
1677     default:
1678       if (!family_known_p(pf)) {
1679         D( fprintf(stderr, " -> unknown; refuse\n"); )
1680         errno = EAFNOSUPPORT;
1681         sk = -1;
1682       }
1683       D( fprintf(stderr, " -> inet; substitute"); )
1684       pf = PF_UNIX;
1685       proto = 0;
1686       break;
1687     case PF_UNIX:
1688 #ifdef PF_NETLINK
1689     case PF_NETLINK:
1690 #endif
1691       D( fprintf(stderr, " -> safe; permit"); )
1692       break;
1693   }
1694   sk = real_socket(pf, ty, proto);
1695   D( dump_sysresult(sk); )
1696   return (sk);
1697 }
1698
1699 int socketpair(int pf, int ty, int proto, int *sk)
1700 {
1701   int rc;
1702
1703   D( fprintf(stderr, "noip(%d): SOCKETPAIR pf=%d, type=%d, proto=%d",
1704              getpid(), pf, ty, proto); )
1705   if (!family_known_p(pf))
1706     D( fprintf(stderr, " -> unknown; permit"); )
1707   else {
1708     D( fprintf(stderr, " -> inet; substitute"); )
1709     pf = PF_UNIX;
1710     proto = 0;
1711   }
1712   rc = real_socketpair(pf, ty, proto, sk);
1713   D( if (rc < 0) dump_syserr(rc);
1714      else fprintf(stderr, " => %d (%d, %d)\n", rc, sk[0], sk[1]); )
1715   return (rc);
1716 }
1717
1718 int bind(int sk, const struct sockaddr *sa, socklen_t len)
1719 {
1720   struct sockaddr_un sun;
1721   int rc;
1722   Dpid;
1723
1724   D({ char buf[ADDRBUFSZ];
1725       fprintf(stderr, "noip(%d): BIND sk=%d, sa[%d]=%s", pid,
1726               sk, len, present_sockaddr(sa, len, buf, sizeof(buf))); })
1727
1728   if (!family_known_p(sa->sa_family))
1729     D( fprintf(stderr, " -> unknown af; pass through"); )
1730   else {
1731     D( fprintf(stderr, " -> checking...\n"); )
1732     PRESERVING_ERRNO({
1733       if (acl_allows_p(bind_real, sa)) {
1734         if (fixup_real_ip_socket(sk, sa->sa_family, 0))
1735           return (-1);
1736       } else {
1737         encode_inet_addr(&sun, sa, ENCF_FRESH);
1738         sa = SA(&sun);
1739         len = SUN_LEN(&sun);
1740       }
1741     });
1742     D( fprintf(stderr, "noip(%d): BIND ...", pid); )
1743   }
1744   rc = real_bind(sk, sa, len);
1745   D( dump_sysresult(rc); )
1746   return (rc);
1747 }
1748
1749 int connect(int sk, const struct sockaddr *sa, socklen_t len)
1750 {
1751   struct sockaddr_un sun;
1752   int rc;
1753   Dpid;
1754
1755   D({ char buf[ADDRBUFSZ];
1756       fprintf(stderr, "noip(%d): CONNECT sk=%d, sa[%d]=%s", pid,
1757               sk, len, present_sockaddr(sa, len, buf, sizeof(buf))); })
1758
1759   if (!family_known_p(sa->sa_family)) {
1760     D( fprintf(stderr, " -> unknown af; pass through"); )
1761     rc = real_connect(sk, sa, len);
1762   } else {
1763     D( fprintf(stderr, " -> checking...\n"); )
1764     PRESERVING_ERRNO({
1765       fixup_client_socket(sk, &sa, &len, &sun);
1766     });
1767     D( fprintf(stderr, "noip(%d): CONNECT ...", pid); )
1768     rc = real_connect(sk, sa, len);
1769     if (rc < 0) {
1770       switch (errno) {
1771         case ENOENT: errno = ECONNREFUSED; break;
1772       }
1773     }
1774   }
1775   D( dump_sysresult(rc); )
1776   return (rc);
1777 }
1778
1779 ssize_t sendto(int sk, const void *buf, size_t len, int flags,
1780                const struct sockaddr *to, socklen_t tolen)
1781 {
1782   struct sockaddr_un sun;
1783   ssize_t n;
1784   Dpid;
1785
1786   D({ char addrbuf[ADDRBUFSZ];
1787       fprintf(stderr, "noip(%d): SENDTO sk=%d, len=%lu, flags=%d, to[%d]=%s",
1788               pid, sk, (unsigned long)len, flags, tolen,
1789               present_sockaddr(to, tolen, addrbuf, sizeof(addrbuf))); })
1790
1791   if (!to)
1792     D( fprintf(stderr, " -> null address; leaving"); )
1793   else if (!family_known_p(to->sa_family))
1794     D( fprintf(stderr, " -> unknown af; pass through"); )
1795   else {
1796     D( fprintf(stderr, " -> checking...\n"); )
1797     PRESERVING_ERRNO({
1798       fixup_client_socket(sk, &to, &tolen, &sun);
1799     });
1800     D( fprintf(stderr, "noip(%d): SENDTO ...", pid); )
1801   }
1802   n = real_sendto(sk, buf, len, flags, to, tolen);
1803   D( dump_sysresult(n); )
1804   return (n);
1805 }
1806
1807 ssize_t recvfrom(int sk, void *buf, size_t len, int flags,
1808                  struct sockaddr *from, socklen_t *fromlen)
1809 {
1810   char sabuf[1024];
1811   socklen_t mylen = sizeof(sabuf);
1812   ssize_t n;
1813   Dpid;
1814
1815   D( fprintf(stderr, "noip(%d): RECVFROM sk=%d, len=%lu, flags=%d",
1816              pid, sk, (unsigned long)len, flags); )
1817
1818   if (!from) {
1819     D( fprintf(stderr, " -> null addr; pass through"); )
1820     n = real_recvfrom(sk, buf, len, flags, 0, 0);
1821   } else {
1822     n = real_recvfrom(sk, buf, len, flags, SA(sabuf), &mylen);
1823     if (n >= 0) {
1824       D( fprintf(stderr, " -> converting...\n"); )
1825       PRESERVING_ERRNO({
1826         return_fake_peer(sk, SA(sabuf), mylen, from, fromlen);
1827       });
1828       D( fprintf(stderr, "noip(%d): ... RECVFROM", pid); )
1829     }
1830   }
1831   D( dump_addrresult(n, from, fromlen ? *fromlen : 0); )
1832   return (n);
1833 }
1834
1835 ssize_t sendmsg(int sk, const struct msghdr *msg, int flags)
1836 {
1837   struct sockaddr_un sun;
1838   const struct sockaddr *sa = SA(msg->msg_name);
1839   struct msghdr mymsg;
1840   ssize_t n;
1841   Dpid;
1842
1843   D({ char addrbuf[ADDRBUFSZ];
1844       fprintf(stderr, "noip(%d): SENDMSG sk=%d, "
1845                       "msg_flags=%d, msg_name[%d]=%s, ...",
1846               pid, sk, msg->msg_flags, msg->msg_namelen,
1847               present_sockaddr(sa, msg->msg_namelen,
1848                                addrbuf, sizeof(addrbuf))); })
1849
1850   if (!sa)
1851     D( fprintf(stderr, " -> null address; leaving"); )
1852   else if (!family_known_p(sa->sa_family))
1853     D( fprintf(stderr, " -> unknown af; pass through"); )
1854   else {
1855     D( fprintf(stderr, " -> checking...\n"); )
1856     PRESERVING_ERRNO({
1857       mymsg = *msg;
1858       fixup_client_socket(sk, &sa, &mymsg.msg_namelen, &sun);
1859       mymsg.msg_name = SA(sa);
1860       msg = &mymsg;
1861     });
1862     D( fprintf(stderr, "noip(%d): SENDMSG ...", pid); )
1863   }
1864   n = real_sendmsg(sk, msg, flags);
1865   D( dump_sysresult(n); )
1866   return (n);
1867 }
1868
1869 ssize_t recvmsg(int sk, struct msghdr *msg, int flags)
1870 {
1871   char sabuf[1024];
1872   struct sockaddr *sa = SA(msg->msg_name);
1873   socklen_t len = msg->msg_namelen;
1874   ssize_t n;
1875   Dpid;
1876
1877   D( fprintf(stderr, "noip(%d): RECVMSG sk=%d msg_flags=%d, ...",
1878              pid, sk, msg->msg_flags); )
1879
1880   if (!msg->msg_name) {
1881     D( fprintf(stderr, " -> null addr; pass through"); )
1882     return (real_recvmsg(sk, msg, flags));
1883   } else {
1884     msg->msg_name = sabuf;
1885     msg->msg_namelen = sizeof(sabuf);
1886     n = real_recvmsg(sk, msg, flags);
1887     if (n >= 0) {
1888       D( fprintf(stderr, " -> converting...\n"); )
1889       PRESERVING_ERRNO({
1890         return_fake_peer(sk, SA(sabuf), msg->msg_namelen, sa, &len);
1891       });
1892     }
1893     D( fprintf(stderr, "noip(%d): ... RECVMSG", pid); )
1894     msg->msg_name = sa;
1895     msg->msg_namelen = len;
1896   }
1897   D( dump_addrresult(n, sa, len); )
1898   return (n);
1899 }
1900
1901 int accept(int sk, struct sockaddr *sa, socklen_t *len)
1902 {
1903   char sabuf[1024];
1904   socklen_t mylen = sizeof(sabuf);
1905   int nsk;
1906   Dpid;
1907
1908   D( fprintf(stderr, "noip(%d): ACCEPT sk=%d", pid, sk); )
1909
1910   nsk = real_accept(sk, SA(sabuf), &mylen);
1911   if (nsk < 0) /* failed */;
1912   else if (!sa) D( fprintf(stderr, " -> address not wanted"); )
1913   else {
1914     D( fprintf(stderr, " -> converting...\n"); )
1915     return_fake_peer(sk, SA(sabuf), mylen, sa, len);
1916     D( fprintf(stderr, "noip(%d): ... ACCEPT", pid); )
1917   }
1918   D( dump_addrresult(nsk, sa, len ? *len : 0); )
1919   return (nsk);
1920 }
1921
1922 int getsockname(int sk, struct sockaddr *sa, socklen_t *len)
1923 {
1924   char sabuf[1024];
1925   socklen_t mylen = sizeof(sabuf);
1926   int rc;
1927   Dpid;
1928
1929   D( fprintf(stderr, "noip(%d): GETSOCKNAME sk=%d", pid, sk); )
1930   rc = real_getsockname(sk, SA(sabuf), &mylen);
1931   if (rc >= 0) {
1932     D( fprintf(stderr, " -> converting...\n"); )
1933     return_fake_name(SA(sabuf), mylen, sa, len, 0);
1934     D( fprintf(stderr, "noip(%d): ... GETSOCKNAME", pid); )
1935   }
1936   D( dump_addrresult(rc, sa, *len); )
1937   return (rc);
1938 }
1939
1940 int getpeername(int sk, struct sockaddr *sa, socklen_t *len)
1941 {
1942   char sabuf[1024];
1943   socklen_t mylen = sizeof(sabuf);
1944   int rc;
1945   Dpid;
1946
1947   D( fprintf(stderr, "noip(%d): GETPEERNAME sk=%d", pid, sk); )
1948   rc = real_getpeername(sk, SA(sabuf), &mylen);
1949   if (rc >= 0) {
1950     D( fprintf(stderr, " -> converting...\n"); )
1951     return_fake_peer(sk, SA(sabuf), mylen, sa, len);
1952     D( fprintf(stderr, "noip(%d): ... GETPEERNAME", pid); )
1953   }
1954   D( dump_addrresult(rc, sa, *len); )
1955   return (0);
1956 }
1957
1958 int getsockopt(int sk, int lev, int opt, void *p, socklen_t *len)
1959 {
1960   switch (lev) {
1961     case IPPROTO_IP:
1962     case IPPROTO_IPV6:
1963     case IPPROTO_TCP:
1964     case IPPROTO_UDP:
1965       if (*len > 0)
1966         memset(p, 0, *len);
1967       return (0);
1968   }
1969   return (real_getsockopt(sk, lev, opt, p, len));
1970 }
1971
1972 int setsockopt(int sk, int lev, int opt, const void *p, socklen_t len)
1973 {
1974   switch (lev) {
1975     case IPPROTO_IP:
1976     case IPPROTO_IPV6:
1977     case IPPROTO_TCP:
1978     case IPPROTO_UDP:
1979       return (0);
1980   }
1981   switch (opt) {
1982     case SO_BINDTODEVICE:
1983     case SO_ATTACH_FILTER:
1984     case SO_DETACH_FILTER:
1985       return (0);
1986   }
1987   return (real_setsockopt(sk, lev, opt, p, len));
1988 }
1989
1990 int ioctl(int fd, unsigned long op, ...)
1991 {
1992   va_list ap;
1993   void *arg;
1994   int sk;
1995   int rc;
1996
1997   va_start(ap, op);
1998   arg = va_arg(ap, void *);
1999
2000   switch (op) {
2001     case SIOCGIFADDR:
2002     case SIOCGIFBRDADDR:
2003     case SIOCGIFDSTADDR:
2004     case SIOCGIFNETMASK:
2005       PRESERVING_ERRNO({
2006         if (fixup_real_ip_socket(fd, AF_INET, &sk)) goto real;
2007       });
2008       rc = real_ioctl(sk, op, arg);
2009       PRESERVING_ERRNO({ close(sk); });
2010       break;
2011     default:
2012     real:
2013       rc = real_ioctl(fd, op, arg);
2014       break;
2015   }
2016   va_end(ap);
2017   return (rc);
2018 }
2019
2020 /*----- Initialization ----------------------------------------------------*/
2021
2022 /* Clean up the socket directory, deleting stale sockets. */
2023 static void cleanup_sockdir(void)
2024 {
2025   DIR *dir;
2026   struct dirent *d;
2027   address addr;
2028   struct sockaddr_un sun;
2029   struct stat st;
2030   Dpid;
2031
2032   if ((dir = opendir(sockdir)) == 0) return;
2033   sun.sun_family = AF_UNIX;
2034   while ((d = readdir(dir)) != 0) {
2035     if (d->d_name[0] == '.') continue;
2036     snprintf(sun.sun_path, sizeof(sun.sun_path),
2037              "%s/%s", sockdir, d->d_name);
2038     if (decode_inet_addr(&addr.sa, 0, &sun, SUN_LEN(&sun)) ||
2039         stat(sun.sun_path, &st) ||
2040         !S_ISSOCK(st.st_mode)) {
2041       D( fprintf(stderr, "noip(%d): ignoring unknown socketdir entry `%s'\n",
2042                  pid, sun.sun_path); )
2043       continue;
2044     }
2045     if (unix_socket_status(&sun, 0) == STALE) {
2046       D( fprintf(stderr, "noip(%d): clearing away stale socket %s\n",
2047                  pid, d->d_name); )
2048       unlink(sun.sun_path);
2049     }
2050   }
2051   closedir(dir);
2052 }
2053
2054 /* Find the addresses attached to local network interfaces, and remember them
2055  * in a table.
2056  */
2057 static void get_local_ipaddrs(void)
2058 {
2059   struct ifaddrs *ifa_head, *ifa;
2060   ipaddr a;
2061   int i;
2062   Dpid;
2063
2064   D( fprintf(stderr, "noip(%d): fetching local addresses...\n", pid); )
2065   if (getifaddrs(&ifa_head)) { perror("getifaddrs"); return; }
2066   for (n_local_ipaddrs = 0, ifa = ifa_head;
2067        n_local_ipaddrs < MAX_LOCAL_IPADDRS && ifa;
2068        ifa = ifa->ifa_next) {
2069     if (!ifa->ifa_addr || !family_known_p(ifa->ifa_addr->sa_family))
2070       continue;
2071     ipaddr_from_sockaddr(&a, ifa->ifa_addr);
2072     D({ char buf[ADDRBUFSZ];
2073         fprintf(stderr, "noip(%d):   local addr %s = %s", pid,
2074                 ifa->ifa_name,
2075                 inet_ntop(ifa->ifa_addr->sa_family, &a,
2076                           buf, sizeof(buf))); })
2077     for (i = 0; i < n_local_ipaddrs; i++) {
2078       if (ifa->ifa_addr->sa_family == local_ipaddrs[i].af &&
2079           ipaddr_equal_p(local_ipaddrs[i].af, &a, &local_ipaddrs[i].addr)) {
2080         D( fprintf(stderr, " (duplicate)\n"); )
2081         goto skip;
2082       }
2083     }
2084     D( fprintf(stderr, "\n"); )
2085     local_ipaddrs[n_local_ipaddrs].af = ifa->ifa_addr->sa_family;
2086     local_ipaddrs[n_local_ipaddrs].addr = a;
2087     n_local_ipaddrs++;
2088   skip:;
2089   }
2090   freeifaddrs(ifa_head);
2091 }
2092
2093 /* Print the given message to standard error.  Avoids stdio. */
2094 static void printerr(const char *p)
2095   { if (write(STDERR_FILENO, p, strlen(p))) ; }
2096
2097 /* Create the socket directory, being careful about permissions. */
2098 static void create_sockdir(void)
2099 {
2100   struct stat st;
2101
2102   if (lstat(sockdir, &st)) {
2103     if (errno == ENOENT) {
2104       if (mkdir(sockdir, 0700)) {
2105         perror("noip: creating socketdir");
2106         exit(127);
2107       }
2108       if (!lstat(sockdir, &st))
2109         goto check;
2110     }
2111     perror("noip: checking socketdir");
2112     exit(127);
2113   }
2114 check:
2115   if (!S_ISDIR(st.st_mode)) {
2116     printerr("noip: bad socketdir: not a directory\n");
2117     exit(127);
2118   }
2119   if (st.st_uid != uid) {
2120     printerr("noip: bad socketdir: not owner\n");
2121     exit(127);
2122   }
2123   if (st.st_mode & 077) {
2124     printerr("noip: bad socketdir: not private\n");
2125     exit(127);
2126   }
2127 }
2128
2129 /* Initialization function. */
2130 static void setup(void) __attribute__((constructor));
2131 static void setup(void)
2132 {
2133   PRESERVING_ERRNO({
2134     char *p;
2135
2136     import();
2137     uid = geteuid();
2138     if ((p = getenv("NOIP_DEBUG")) && atoi(p))
2139       debug = 1;
2140     get_local_ipaddrs();
2141     readconfig();
2142     create_sockdir();
2143     cleanup_sockdir();
2144   });
2145 }
2146
2147 /*----- That's all, folks -------------------------------------------------*/