chiark / gitweb /
noip.c: Make the `unix_socket_status' return a bitfield.
[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   while (fgets(buf, sizeof(buf), fp)) {
708     n = strlen(buf);
709     if (n >= len + 2 && buf[n - len - 2] == ' ' && buf[n - 1] == '\n' &&
710         memcmp(buf + n - len - 1, sun->sun_path, len) == 0)
711       goto done;
712   }
713   if (ferror(fp))
714     goto done;
715   rc = STALE;
716 done:
717   if (fp) fclose(fp);
718
719   /* All done. */
720   return (rc);
721 }
722
723 /* Encode SA as a Unix-domain address SUN, and return whether it's currently
724  * in use.
725  */
726 static int encode_single_inet_addr(const struct sockaddr *sa,
727                                    struct sockaddr_un *sun,
728                                    int quickp)
729 {
730   char buf[ADDRBUFSZ];
731   int rc;
732
733   snprintf(sun->sun_path, sizeof(sun->sun_path), "%s/%s", sockdir,
734            present_sockaddr(sa, 0, buf, sizeof(buf)));
735   if ((rc = unix_socket_status(sun, quickp)) == USED) return (USED);
736   else if (rc == STALE) unlink(sun->sun_path);
737   return (UNUSED);
738 }
739
740 /* Convert the IP address SA to a Unix-domain address SUN.  Fail if the
741  * address seems already taken.  If DESPARATEP then try cleaning up stale old
742  * sockets.
743  */
744 static int encode_unused_inet_addr(struct sockaddr *sa,
745                                    struct sockaddr_un *sun,
746                                    int desperatep)
747 {
748   address waddr, maddr;
749   struct sockaddr_un wsun;
750   int port = port_from_sockaddr(sa);
751
752   /* First, look for an exact match.  Only look quickly unless we're
753    * desperate.  If the socket is in use, we fail here.  (This could get
754    * racy.  Let's not worry about that for now.)
755    */
756   if (encode_single_inet_addr(sa, sun, !desperatep)&USED)
757     return (-1);
758
759   /* Next, check the corresponding wildcard address, so as to avoid
760    * inadvertant collisions with listeners.  Do this in the same way.
761    */
762   wildcard_address(sa->sa_family, &waddr.sa);
763   port_to_sockaddr(&waddr.sa, port);
764   if (encode_single_inet_addr(&waddr.sa, &wsun, !desperatep)&USED)
765     return (-1);
766
767   /* We're not done yet.  If this is an IPv4 address, then /also/ check (a)
768    * the v6-mapped version, (b) the v6-mapped v4 wildcard, /and/ (c) the v6
769    * wildcard.  Ugh!
770    */
771   if (sa->sa_family == AF_INET) {
772     map_ipv4_sockaddr(&maddr.sin6, SIN(&sa));
773     if (encode_single_inet_addr(&maddr.sa, &wsun, !desperatep)&USED)
774       return (-1);
775
776     map_ipv4_sockaddr(&maddr.sin6, &waddr.sin);
777     if (encode_single_inet_addr(&maddr.sa, &wsun, !desperatep)&USED)
778       return (-1);
779
780     wildcard_address(AF_INET6, &waddr.sa);
781     port_to_sockaddr(&waddr.sa, port);
782     if (encode_single_inet_addr(&waddr.sa, &wsun, !desperatep)&USED)
783       return (-1);
784   }
785
786   /* All is well. */
787   return (0);
788 }
789
790 /* Encode the Internet address SA as a Unix-domain address SUN.  If the flag
791  * `ENCF_FRESH' is set, and SA's port number is zero, then we pick an
792  * arbitrary local port.  Otherwise we pick the port given.  There's an
793  * unpleasant hack to find servers bound to local wildcard addresses.
794  * Returns zero on success; -1 on failure.
795  */
796 #define ENCF_FRESH 1u
797 static int encode_inet_addr(struct sockaddr_un *sun,
798                             const struct sockaddr *sa,
799                             unsigned f)
800 {
801   int i;
802   int desperatep = 0;
803   address addr;
804   struct sockaddr_in6 sin6;
805   int port = port_from_sockaddr(sa);
806   int rc;
807   char buf[ADDRBUFSZ];
808
809   D( fprintf(stderr, "noip(%d): encode %s (%s)", getpid(),
810              present_sockaddr(sa, 0, buf, sizeof(buf)),
811              (f&ENCF_FRESH) ? "FRESH" : "EXISTING"); )
812
813   /* Start making the Unix-domain address. */
814   sun->sun_family = AF_UNIX;
815
816   if (port || !(f&ENCF_FRESH)) {
817
818     /* Try the address as given.  If it's in use, or we don't necessarily
819      * want an existing socket, then we're done.
820      */
821     rc = encode_single_inet_addr(sa, sun, 0);
822     if ((rc&USED) || (f&ENCF_FRESH)) goto found;
823
824     /* We're looking for a socket which already exists.  This is
825      * unfortunately difficult, because we must deal both with wildcards and
826      * v6-mapped IPv4 addresses.
827      *
828      *   * We've just tried searching for a socket whose name is an exact
829      *     match for our remote address.  If the remote address is IPv4, then
830      *     we should try again with the v6-mapped equivalent.
831      *
832      *   * Failing that, we try again with the wildcard address for the
833      *     appropriate address family.
834      *
835      *   * Failing /that/, if the remote address is IPv4, then we try
836      *     /again/, increasingly desperately, first with the v6-mapped IPv4
837      *     wildcard address, and then with the IPv6 wildcard address.  This
838      *     will cause magic v6-mapping to occur when the connection is
839      *     accepted, which we hope won't cause too much trouble.
840      */
841
842     if (sa->sa_family == AF_INET) {
843       map_ipv4_sockaddr(&addr.sin6, SIN(sa));
844       if (encode_single_inet_addr(&addr.sa, sun, 0)&USED) goto found;
845     }
846
847     wildcard_address(sa->sa_family, &addr.sa);
848     port_to_sockaddr(&addr.sa, port);
849     if (encode_single_inet_addr(&addr.sa, sun, 0)&USED) goto found;
850
851     if (sa->sa_family == AF_INET) {
852       map_ipv4_sockaddr(&sin6, &addr.sin);
853       if (encode_single_inet_addr(SA(&sin6), sun, 0)&USED) goto found;
854       wildcard_address(AF_INET6, &addr.sa);
855       port_to_sockaddr(&addr.sa, port);
856       if (encode_single_inet_addr(&addr.sa, sun, 0)&USED) goto found;
857     }
858
859     /* Well, this isn't going to work (unless a miraculous race is lost), but
860      * we might as well try.
861      */
862     encode_single_inet_addr(sa, sun, 1);
863
864   } else {
865     /* We want a fresh new socket. */
866
867     /* Make a copy of the given address, because we're going to mangle it. */
868     copy_sockaddr(&addr.sa, sa);
869
870     /* Try a few random-ish port numbers to see if any of them is spare. */
871     for (i = 0; i < 10; i++) {
872       port_to_sockaddr(&addr.sa, randrange(minautoport, maxautoport));
873       if (!encode_unused_inet_addr(&addr.sa, sun, 0)) goto found;
874     }
875
876     /* Things must be getting tight.  Work through all of the autoport range
877      * to see if we can find a spare one.  The first time, just do it the
878      * quick way; if that doesn't work, then check harder for stale sockets.
879      */
880     for (desperatep = 0; desperatep < 2; desperatep++) {
881       for (i = minautoport; i <= maxautoport; i++) {
882         port_to_sockaddr(&addr.sa, i);
883         if (!encode_unused_inet_addr(&addr.sa, sun, 0)) goto found;
884       }
885     }
886
887     /* We failed to find any free ports. */
888     errno = EADDRINUSE;
889     D( fprintf(stderr, " -- can't resolve\n"); )
890     return (-1);
891   }
892
893   /* Success. */
894 found:
895   D( fprintf(stderr, " -> `%s'\n", sun->sun_path); )
896   return (0);
897 }
898
899 /* Decode the Unix address SUN to an Internet address SIN.  If AF_HINT is
900  * nonzero, an empty address (indicative of an unbound Unix-domain socket) is
901  * translated to a wildcard Internet address of the appropriate family.
902  * Returns zero on success; -1 on failure (e.g., it wasn't one of our
903  * addresses).
904  */
905 static int decode_inet_addr(struct sockaddr *sa, int af_hint,
906                             const struct sockaddr_un *sun,
907                             socklen_t len)
908 {
909   char buf[ADDRBUFSZ];
910   size_t n = strlen(sockdir), nn;
911   address addr;
912
913   if (!sa) sa = &addr.sa;
914   if (sun->sun_family != AF_UNIX) return (-1);
915   if (len > sizeof(*sun)) return (-1);
916   ((char *)sun)[len] = 0;
917   nn = strlen(sun->sun_path);
918   D( fprintf(stderr, "noip(%d): decode `%s'", getpid(), sun->sun_path); )
919   if (af_hint && !sun->sun_path[0]) {
920     wildcard_address(af_hint, sa);
921     D( fprintf(stderr, " -- unbound socket\n"); )
922     return (0);
923   }
924   if (nn < n + 1 || nn - n >= sizeof(buf) || sun->sun_path[n] != '/' ||
925       memcmp(sun->sun_path, sockdir, n) != 0) {
926     D( fprintf(stderr, " -- not one of ours\n"); )
927     return (-1);
928   }
929   if (parse_sockaddr(sa, sun->sun_path + n + 1)) return (-1);
930   D( fprintf(stderr, " -> %s\n",
931              present_sockaddr(sa, 0, buf, sizeof(buf))); )
932   return (0);
933 }
934
935 /* SK is (or at least might be) a Unix-domain socket we created when an
936  * Internet socket was asked for.  We've decided it should be an Internet
937  * socket after all, with family AF_HINT, so convert it.  If TMP is not null,
938  * then don't replace the existing descriptor: store the new socket in *TMP
939  * and return zero.
940  */
941 static int fixup_real_ip_socket(int sk, int af_hint, int *tmp)
942 {
943   int nsk;
944   int type;
945   int f, fd;
946   struct sockaddr_un sun;
947   address addr;
948   socklen_t len;
949
950 #define OPTS(_)                                                         \
951   _(DEBUG, int)                                                         \
952   _(REUSEADDR, int)                                                     \
953   _(DONTROUTE, int)                                                     \
954   _(BROADCAST, int)                                                     \
955   _(SNDBUF, int)                                                        \
956   _(RCVBUF, int)                                                        \
957   _(OOBINLINE, int)                                                     \
958   _(NO_CHECK, int)                                                      \
959   _(LINGER, struct linger)                                              \
960   _(BSDCOMPAT, int)                                                     \
961   _(RCVLOWAT, int)                                                      \
962   _(RCVTIMEO, struct timeval)                                           \
963   _(SNDTIMEO, struct timeval)
964
965   len = sizeof(sun);
966   if (real_getsockname(sk, SA(&sun), &len))
967     return (-1);
968   if (decode_inet_addr(&addr.sa, af_hint, &sun, len))
969     return (0); /* Not one of ours */
970   len = sizeof(type);
971   if (real_getsockopt(sk, SOL_SOCKET, SO_TYPE, &type, &len) < 0 ||
972       (nsk = real_socket(addr.sa.sa_family, type, 0)) < 0)
973     return (-1);
974 #define FIX(opt, ty) do {                                               \
975   ty ov_;                                                               \
976   len = sizeof(ov_);                                                    \
977   if (real_getsockopt(sk, SOL_SOCKET, SO_##opt, &ov_, &len) < 0 ||      \
978       real_setsockopt(nsk, SOL_SOCKET, SO_##opt, &ov_, len)) {          \
979     close(nsk);                                                         \
980     return (-1);                                                        \
981   }                                                                     \
982 } while (0);
983   OPTS(FIX)
984 #undef FIX
985   if (tmp)
986     *tmp = nsk;
987   else {
988     if ((f = fcntl(sk, F_GETFL)) < 0 ||
989         (fd = fcntl(sk, F_GETFD)) < 0 ||
990         fcntl(nsk, F_SETFL, f) < 0 ||
991         dup2(nsk, sk) < 0) {
992       close(nsk);
993       return (-1);
994     }
995     unlink(sun.sun_path);
996     close(nsk);
997     if (fcntl(sk, F_SETFD, fd) < 0) {
998       perror("noip: fixup_real_ip_socket F_SETFD");
999       abort();
1000     }
1001   }
1002   return (0);
1003 }
1004
1005 /* We found the real address SA, with length LEN; if it's a Unix-domain
1006  * address corresponding to a fake socket, convert it to cover up the
1007  * deception.  Whatever happens, put the result at FAKE and store its length
1008  * at FAKELEN.
1009  */
1010 #define FNF_V6MAPPED 1u
1011 static void return_fake_name(struct sockaddr *sa, socklen_t len,
1012                              struct sockaddr *fake, socklen_t *fakelen,
1013                              unsigned f)
1014 {
1015   address addr;
1016   struct sockaddr_in6 sin6;
1017   socklen_t alen;
1018
1019   if (sa->sa_family == AF_UNIX &&
1020       !decode_inet_addr(&addr.sa, 0, SUN(sa), len)) {
1021     if (addr.sa.sa_family != AF_INET || !(f&FNF_V6MAPPED)) {
1022       sa = &addr.sa;
1023       len = family_socklen(addr.sa.sa_family);
1024     } else {
1025       map_ipv4_sockaddr(&sin6, &addr.sin);
1026       sa = SA(&sin6);
1027       len = family_socklen(AF_INET6);
1028     }
1029   }
1030   alen = len;
1031   if (len > *fakelen) len = *fakelen;
1032   if (len > 0) memcpy(fake, sa, len);
1033   *fakelen = alen;
1034 }
1035
1036 /* Variant of `return_fake_name' above, specifically handling the weirdness
1037  * of remote v6-mapped IPv4 addresses.  If SK's fake local address is IPv6,
1038  * and the remote address is IPv4, then return a v6-mapped version of the
1039  * remote address.
1040  */
1041 static void return_fake_peer(int sk, struct sockaddr *sa, socklen_t len,
1042                              struct sockaddr *fake, socklen_t *fakelen)
1043 {
1044   char sabuf[1024];
1045   socklen_t mylen = sizeof(sabuf);
1046   unsigned fnf = 0;
1047   address addr;
1048   int rc;
1049
1050   PRESERVING_ERRNO({
1051     rc = real_getsockname(sk, SA(sabuf), &mylen);
1052     if (!rc && sa->sa_family == AF_UNIX &&
1053         !decode_inet_addr(&addr.sa, 0, SUN(sabuf), mylen) &&
1054         addr.sa.sa_family == AF_INET6)
1055       fnf |= FNF_V6MAPPED;
1056   });
1057   return_fake_name(sa, len, fake, fakelen, fnf);
1058 }
1059
1060 /*----- Implicit binding --------------------------------------------------*/
1061
1062 #ifdef DEBUG
1063
1064 static void dump_impbind(const impbind *i)
1065 {
1066   char buf[ADDRBUFSZ];
1067
1068   fprintf(stderr, "noip(%d):   ", getpid());
1069   dump_addrrange(i->af, &i->minaddr, &i->maxaddr);
1070   switch (i->how) {
1071     case SAME: fprintf(stderr, " <self>"); break;
1072     case EXPLICIT:
1073       fprintf(stderr, " %s", inet_ntop(i->af, &i->bindaddr,
1074                                        buf, sizeof(buf)));
1075       break;
1076     default: abort();
1077   }
1078   fputc('\n', stderr);
1079 }
1080
1081 static void dump_impbind_list(void)
1082 {
1083   const impbind *i;
1084
1085   for (i = impbinds; i; i = i->next) dump_impbind(i);
1086 }
1087
1088 #endif
1089
1090 /* The socket SK is about to be used to communicate with the remote address
1091  * SA.  Assign it a local address so that getpeername(2) does something
1092  * useful.
1093  *
1094  * If the flag `IBF_V6MAPPED' is set then, then SA must be an `AF_INET'
1095  * address; after deciding on the appropriate local address, convert it to be
1096  * an IPv4-mapped IPv6 address before final conversion to a Unix-domain
1097  * socket address and actually binding.  Note that this could well mean that
1098  * the socket ends up bound to the v6-mapped v4 wildcard address
1099  * ::ffff:0.0.0.0, which looks very strange but is meaningful.
1100  */
1101 #define IBF_V6MAPPED 1u
1102 static int do_implicit_bind(int sk, const struct sockaddr *sa, unsigned f)
1103 {
1104   address addr;
1105   struct sockaddr_in6 sin6;
1106   struct sockaddr_un sun;
1107   const impbind *i;
1108   Dpid;
1109
1110   D( fprintf(stderr, "noip(%d): checking impbind list...\n", pid); )
1111   for (i = impbinds; i; i = i->next) {
1112     D( dump_impbind(i); )
1113     if (sa->sa_family == i->af &&
1114         sockaddr_in_range_p(sa, &i->minaddr, &i->maxaddr)) {
1115       D( fprintf(stderr, "noip(%d): match!\n", pid); )
1116       addr.sa.sa_family = sa->sa_family;
1117       ipaddr_to_sockaddr(&addr.sa, &i->bindaddr);
1118       goto found;
1119     }
1120   }
1121   D( fprintf(stderr, "noip(%d): no match; using wildcard\n", pid); )
1122   wildcard_address(sa->sa_family, &addr.sa);
1123 found:
1124   if (addr.sa.sa_family != AF_INET || !(f&IBF_V6MAPPED)) sa = &addr.sa;
1125   else { map_ipv4_sockaddr(&sin6, &addr.sin); sa = SA(&sin6); }
1126   encode_inet_addr(&sun, sa, ENCF_FRESH);
1127   D( fprintf(stderr, "noip(%d): implicitly binding to %s\n",
1128              pid, sun.sun_path); )
1129   if (real_bind(sk, SA(&sun), SUN_LEN(&sun))) return (-1);
1130   return (0);
1131 }
1132
1133 /* The socket SK is about to communicate with the remote address *SA.  Ensure
1134  * that the socket has a local address, and adjust *SA to refer to the real
1135  * remote endpoint.
1136  *
1137  * If we need to translate the remote address, then the Unix-domain endpoint
1138  * address will end in *SUN, and *SA will be adjusted to point to it.
1139  */
1140 static int fixup_client_socket(int sk, const struct sockaddr **sa_r,
1141                                socklen_t *len_r, struct sockaddr_un *sun)
1142 {
1143   struct sockaddr_in sin;
1144   socklen_t mylen = sizeof(*sun);
1145   const struct sockaddr *sa = *sa_r;
1146   unsigned ibf = 0;
1147
1148   /* If this isn't a Unix-domain socket then there's nothing to do. */
1149   if (real_getsockname(sk, SA(sun), &mylen) < 0) return (-1);
1150   if (sun->sun_family != AF_UNIX) return (0);
1151   if (mylen < sizeof(*sun)) ((char *)sun)[mylen] = 0;
1152
1153   /* If the remote address is v6-mapped IPv4, then unmap it so as to search
1154    * for IPv4 servers.  Also remember to v6-map the local address when we
1155    * autobind.
1156    */
1157   if (sa->sa_family == AF_INET6 && !(unmap_ipv4_sockaddr(&sin, SIN6(sa)))) {
1158     sa = SA(&sin);
1159     ibf |= IBF_V6MAPPED;
1160   }
1161
1162   /* If we're allowed to talk to a real remote endpoint, then fix things up
1163    * as necessary and proceed.
1164    */
1165   if (acl_allows_p(connect_real, sa)) {
1166     if (fixup_real_ip_socket(sk, (*sa_r)->sa_family, 0)) return (-1);
1167     return (0);
1168   }
1169
1170   /* Speaking of which, if we don't have a local address, then we should
1171    * arrange one now.
1172    */
1173   if (!sun->sun_path[0] && do_implicit_bind(sk, sa, ibf)) return (-1);
1174
1175   /* And then come up with a remote address. */
1176   encode_inet_addr(sun, sa, 0);
1177   *sa_r = SA(sun);
1178   *len_r = SUN_LEN(sun);
1179   return (0);
1180 }
1181
1182 /*----- Configuration -----------------------------------------------------*/
1183
1184 /* Return the process owner's home directory. */
1185 static char *home(void)
1186 {
1187   char *p;
1188   struct passwd *pw;
1189
1190   if (getuid() == uid &&
1191       (p = getenv("HOME")) != 0)
1192     return (p);
1193   else if ((pw = getpwuid(uid)) != 0)
1194     return (pw->pw_dir);
1195   else
1196     return "/notexist";
1197 }
1198
1199 /* Return a good temporary directory to use. */
1200 static char *tmpdir(void)
1201 {
1202   char *p;
1203
1204   if ((p = getenv("TMPDIR")) != 0) return (p);
1205   else if ((p = getenv("TMP")) != 0) return (p);
1206   else return ("/tmp");
1207 }
1208
1209 /* Return the user's name, or at least something distinctive. */
1210 static char *user(void)
1211 {
1212   static char buf[16];
1213   char *p;
1214   struct passwd *pw;
1215
1216   if ((p = getenv("USER")) != 0) return (p);
1217   else if ((p = getenv("LOGNAME")) != 0) return (p);
1218   else if ((pw = getpwuid(uid)) != 0) return (pw->pw_name);
1219   else {
1220     snprintf(buf, sizeof(buf), "uid-%lu", (unsigned long)uid);
1221     return (buf);
1222   }
1223 }
1224
1225 /* Skip P over space characters. */
1226 #define SKIPSPC do { while (*p && isspace(UC(*p))) p++; } while (0)
1227
1228 /* Set Q to point to the next word following P, null-terminate it, and step P
1229  * past it. */
1230 #define NEXTWORD(q) do {                                                \
1231   SKIPSPC;                                                              \
1232   q = p;                                                                \
1233   while (*p && !isspace(UC(*p))) p++;                                   \
1234   if (*p) *p++ = 0;                                                     \
1235 } while (0)
1236
1237 /* Set Q to point to the next dotted-quad address, store the ending delimiter
1238  * in DEL, null-terminate it, and step P past it. */
1239 static void parse_nextaddr(char **pp, char **qq, int *del)
1240 {
1241   char *p = *pp;
1242
1243   SKIPSPC;
1244   if (*p == '[') {
1245     p++; SKIPSPC;
1246     *qq = p;
1247     p += strcspn(p, "]");
1248     if (*p) *p++ = 0;
1249     *del = 0;
1250   } else {
1251     *qq = p;
1252     while (*p && (*p == '.' || isdigit(UC(*p)))) p++;
1253     *del = *p;
1254     if (*p) *p++ = 0;
1255   }
1256   *pp = p;
1257 }
1258
1259 /* Set Q to point to the next decimal number, store the ending delimiter in
1260  * DEL, null-terminate it, and step P past it. */
1261 #define NEXTNUMBER(q, del) do {                                         \
1262   SKIPSPC;                                                              \
1263   q = p;                                                                \
1264   while (*p && isdigit(UC(*p))) p++;                                    \
1265   del = *p;                                                             \
1266   if (*p) *p++ = 0;                                                     \
1267 } while (0)
1268
1269 /* Push the character DEL back so we scan it again, unless it's zero
1270  * (end-of-file). */
1271 #define RESCAN(del) do { if (del) *--p = del; } while (0)
1272
1273 /* Evaluate true if P is pointing to the word KW (and not some longer string
1274  * of which KW is a prefix). */
1275
1276 #define KWMATCHP(kw) (strncmp(p, kw, sizeof(kw) - 1) == 0 &&            \
1277                       !isalnum(UC(p[sizeof(kw) - 1])) &&                \
1278                       (p += sizeof(kw) - 1))
1279
1280 /* Parse a port list, starting at *PP.  Port lists have the form
1281  * [:LOW[-HIGH]]: if omitted, all ports are included; if HIGH is omitted,
1282  * it's as if HIGH = LOW.  Store LOW in *MIN, HIGH in *MAX and set *PP to the
1283  * rest of the string.
1284  */
1285 static void parse_ports(char **pp, unsigned short *min, unsigned short *max)
1286 {
1287   char *p = *pp, *q;
1288   int del;
1289
1290   SKIPSPC;
1291   if (*p != ':')
1292     { *min = 0; *max = 0xffff; }
1293   else {
1294     p++;
1295     NEXTNUMBER(q, del); *min = strtoul(q, 0, 0); RESCAN(del);
1296     SKIPSPC;
1297     if (*p == '-')
1298       { p++; NEXTNUMBER(q, del); *max = strtoul(q, 0, 0); RESCAN(del); }
1299     else
1300       *max = *min;
1301   }
1302   *pp = p;
1303 }
1304
1305 /* Parse an address range designator starting at PP and store a
1306  * representation of it in R.  An address range designator has the form:
1307  *
1308  *      any | local | ADDR | ADDR - ADDR | ADDR/ADDR | ADDR/INT
1309  */
1310 static int parse_addrrange(char **pp, addrrange *r)
1311 {
1312   char *p = *pp, *q;
1313   int n;
1314   int del;
1315   int af;
1316
1317   SKIPSPC;
1318   if (KWMATCHP("any")) r->type = ANY;
1319   else if (KWMATCHP("local")) r->type = LOCAL;
1320   else {
1321     parse_nextaddr(&p, &q, &del);
1322     af = guess_address_family(q);
1323     if (inet_pton(af, q, &r->u.range.min) <= 0) goto bad;
1324     RESCAN(del);
1325     SKIPSPC;
1326     if (*p == '-') {
1327       p++;
1328       parse_nextaddr(&p, &q, &del);
1329       if (inet_pton(af, q, &r->u.range.max) <= 0) goto bad;
1330       RESCAN(del);
1331     } else if (*p == '/') {
1332       p++;
1333       NEXTNUMBER(q, del);
1334       n = strtoul(q, 0, 0);
1335       r->u.range.max = r->u.range.min;
1336       mask_address(af, &r->u.range.min, n, 0);
1337       mask_address(af, &r->u.range.max, n, 1);
1338       RESCAN(del);
1339     } else
1340       r->u.range.max = r->u.range.min;
1341     r->type = RANGE;
1342     r->u.range.af = af;
1343   }
1344   *pp = p;
1345   return (0);
1346
1347 bad:
1348   return (-1);
1349 }
1350
1351 /* Call FUNC on each individual address range in R. */
1352 static void foreach_addrrange(const addrrange *r,
1353                               void (*func)(int af,
1354                                            const ipaddr *min,
1355                                            const ipaddr *max,
1356                                            void *p),
1357                               void *p)
1358 {
1359   ipaddr minaddr, maxaddr;
1360   int i, af;
1361
1362   switch (r->type) {
1363     case EMPTY:
1364       break;
1365     case ANY:
1366       for (i = 0; address_families[i] >= 0; i++) {
1367         af = address_families[i];
1368         memset(&minaddr, 0, sizeof(minaddr));
1369         maxaddr = minaddr; mask_address(af, &maxaddr, 0, 1);
1370         func(af, &minaddr, &maxaddr, p);
1371       }
1372       break;
1373     case LOCAL:
1374       for (i = 0; address_families[i] >= 0; i++) {
1375         af = address_families[i];
1376         memset(&minaddr, 0, sizeof(minaddr));
1377         maxaddr = minaddr; mask_address(af, &maxaddr, 0, 1);
1378         func(af, &minaddr, &minaddr, p);
1379         func(af, &maxaddr, &maxaddr, p);
1380       }
1381       for (i = 0; i < n_local_ipaddrs; i++) {
1382         func(local_ipaddrs[i].af,
1383              &local_ipaddrs[i].addr, &local_ipaddrs[i].addr,
1384              p);
1385       }
1386       break;
1387     case RANGE:
1388       func(r->u.range.af, &r->u.range.min, &r->u.range.max, p);
1389       break;
1390     default:
1391       abort();
1392   }
1393 }
1394
1395 struct add_aclnode_ctx {
1396   int act;
1397   unsigned short minport, maxport;
1398   aclnode ***tail;
1399 };
1400
1401 static void add_aclnode(int af, const ipaddr *min, const ipaddr *max,
1402                         void *p)
1403 {
1404   struct add_aclnode_ctx *ctx = p;
1405   aclnode *a;
1406
1407   NEW(a);
1408   a->act = ctx->act;
1409   a->af = af;
1410   a->minaddr = *min; a->maxaddr = *max;
1411   a->minport = ctx->minport; a->maxport = ctx->maxport;
1412   **ctx->tail = a; *ctx->tail = &a->next;
1413 }
1414
1415 /* Parse an ACL line.  *PP points to the end of the line; *TAIL points to
1416  * the list tail (i.e., the final link in the list).  An ACL entry has the
1417  * form +|- ADDR-RANGE PORTS
1418  * where PORTS is parsed by parse_ports above; an ACL line consists of a
1419  * comma-separated sequence of entries..
1420  */
1421 static void parse_acl_line(char **pp, aclnode ***tail)
1422 {
1423   struct add_aclnode_ctx ctx;
1424   addrrange r;
1425   char *p = *pp;
1426
1427   ctx.tail = tail;
1428   for (;;) {
1429     SKIPSPC;
1430     if (*p == '+') ctx.act = ALLOW;
1431     else if (*p == '-') ctx.act = DENY;
1432     else goto bad;
1433
1434     p++;
1435     if (parse_addrrange(&p, &r)) goto bad;
1436     parse_ports(&p, &ctx.minport, &ctx.maxport);
1437     foreach_addrrange(&r, add_aclnode, &ctx);
1438     SKIPSPC;
1439     if (*p != ',') break;
1440     if (*p) p++;
1441   }
1442   if (*p) goto bad;
1443   *pp = p;
1444   return;
1445
1446 bad:
1447   D( fprintf(stderr, "noip(%d): bad acl spec (ignored)\n", getpid()); )
1448   return;
1449 }
1450
1451 /* Parse an ACL from an environment variable VAR, attaching it to the list
1452  * TAIL.
1453  */
1454 static void parse_acl_env(const char *var, aclnode ***tail)
1455 {
1456   char *p, *q;
1457
1458   if ((p = getenv(var)) != 0) {
1459     p = q = xstrdup(p);
1460     parse_acl_line(&q, tail);
1461     free(p);
1462   }
1463 }
1464
1465 struct add_impbind_ctx {
1466   int af, how;
1467   ipaddr addr;
1468 };
1469
1470 static void add_impbind(int af, const ipaddr *min, const ipaddr *max,
1471                         void *p)
1472 {
1473   struct add_impbind_ctx *ctx = p;
1474   impbind *i;
1475
1476   if (ctx->af && af != ctx->af) return;
1477   NEW(i);
1478   i->af = af;
1479   i->how = ctx->how;
1480   i->minaddr = *min; i->maxaddr = *max;
1481   switch (ctx->how) {
1482     case EXPLICIT: i->bindaddr = ctx->addr;
1483     case SAME: break;
1484     default: abort();
1485   }
1486   *impbind_tail = i; impbind_tail = &i->next;
1487 }
1488
1489 /* Parse an implicit-bind line.  An implicit-bind entry has the form
1490  * ADDR-RANGE {ADDR | same}
1491  */
1492 static void parse_impbind_line(char **pp)
1493 {
1494   struct add_impbind_ctx ctx;
1495   char *p = *pp, *q;
1496   addrrange r;
1497   int del;
1498
1499   for (;;) {
1500     if (parse_addrrange(&p, &r)) goto bad;
1501     SKIPSPC;
1502     if (KWMATCHP("same")) {
1503       ctx.how = SAME;
1504       ctx.af = 0;
1505     } else {
1506       ctx.how = EXPLICIT;
1507       parse_nextaddr(&p, &q, &del);
1508       ctx.af = guess_address_family(q);
1509       if (inet_pton(ctx.af, q, &ctx.addr) < 0) goto bad;
1510       RESCAN(del);
1511     }
1512     foreach_addrrange(&r, add_impbind, &ctx);
1513     SKIPSPC;
1514     if (*p != ',') break;
1515     if (*p) p++;
1516   }
1517   if (*p) goto bad;
1518   *pp = p;
1519   return;
1520
1521 bad:
1522   D( fprintf(stderr, "noip(%d): bad implicit-bind spec (ignored)\n",
1523              getpid()); )
1524   return;
1525 }
1526
1527 /* Parse implicit-bind instructions from an environment variable VAR,
1528  * attaching it to the list.
1529  */
1530 static void parse_impbind_env(const char *var)
1531 {
1532   char *p, *q;
1533
1534   if ((p = getenv(var)) != 0) {
1535     p = q = xstrdup(p);
1536     parse_impbind_line(&q);
1537     free(p);
1538   }
1539 }
1540
1541 /* Parse the autoports configuration directive.  Syntax is MIN - MAX. */
1542 static void parse_autoports(char **pp)
1543 {
1544   char *p = *pp, *q;
1545   unsigned x, y;
1546   int del;
1547
1548   SKIPSPC;
1549   NEXTNUMBER(q, del); x = strtoul(q, 0, 0); RESCAN(del);
1550   SKIPSPC;
1551   if (*p != '-') goto bad;
1552   p++;
1553   NEXTNUMBER(q, del); y = strtoul(q, 0, 0); RESCAN(del);
1554   minautoport = x; maxautoport = y;
1555   SKIPSPC; if (*p) goto bad;
1556   *pp = p;
1557   return;
1558
1559 bad:
1560   D( fprintf(stderr, "noip(%d): bad port range (ignored)\n", getpid()); )
1561   return;
1562 }
1563
1564 /* Read the configuration from the config file and environment. */
1565 static void readconfig(void)
1566 {
1567   FILE *fp;
1568   char buf[1024];
1569   size_t n;
1570   char *p, *q, *cmd;
1571   Dpid;
1572
1573   parse_acl_env("NOIP_REALBIND_BEFORE", &bind_tail);
1574   parse_acl_env("NOIP_REALCONNECT_BEFORE", &connect_tail);
1575   parse_impbind_env("NOIP_IMPBIND_BEFORE");
1576   if ((p = getenv("NOIP_AUTOPORTS")) != 0) {
1577     p = q = xstrdup(p);
1578     parse_autoports(&q);
1579     free(p);
1580   }
1581   if ((p = getenv("NOIP_CONFIG")) == 0)
1582     snprintf(p = buf, sizeof(buf), "%s/.noip", home());
1583   D( fprintf(stderr, "noip(%d): config file: %s\n", pid, p); )
1584
1585   if ((fp = fopen(p, "r")) == 0) {
1586     D( fprintf(stderr, "noip(%d): couldn't read config: %s\n",
1587                pid, strerror(errno)); )
1588     goto done;
1589   }
1590   while (fgets(buf, sizeof(buf), fp)) {
1591     n = strlen(buf);
1592     p = buf;
1593
1594     SKIPSPC;
1595     if (!*p || *p == '#') continue;
1596     while (n && isspace(UC(buf[n - 1]))) n--;
1597     buf[n] = 0;
1598     NEXTWORD(cmd);
1599     SKIPSPC;
1600
1601     if (strcmp(cmd, "socketdir") == 0)
1602       sockdir = xstrdup(p);
1603     else if (strcmp(cmd, "realbind") == 0)
1604       parse_acl_line(&p, &bind_tail);
1605     else if (strcmp(cmd, "realconnect") == 0)
1606       parse_acl_line(&p, &connect_tail);
1607     else if (strcmp(cmd, "impbind") == 0)
1608       parse_impbind_line(&p);
1609     else if (strcmp(cmd, "autoports") == 0)
1610       parse_autoports(&p);
1611     else if (strcmp(cmd, "debug") == 0)
1612       debug = *p ? atoi(p) : 1;
1613     else
1614       D( fprintf(stderr, "noip(%d): bad config command %s\n", pid, cmd); )
1615   }
1616   fclose(fp);
1617
1618 done:
1619   parse_acl_env("NOIP_REALBIND", &bind_tail);
1620   parse_acl_env("NOIP_REALCONNECT", &connect_tail);
1621   parse_impbind_env("NOIP_IMPBIND");
1622   parse_acl_env("NOIP_REALBIND_AFTER", &bind_tail);
1623   parse_acl_env("NOIP_REALCONNECT_AFTER", &connect_tail);
1624   parse_impbind_env("NOIP_IMPBIND_AFTER");
1625   *bind_tail = 0;
1626   *connect_tail = 0;
1627   *impbind_tail = 0;
1628   if (!sockdir) sockdir = getenv("NOIP_SOCKETDIR");
1629   if (!sockdir) {
1630     snprintf(buf, sizeof(buf), "%s/noip-%s", tmpdir(), user());
1631     sockdir = xstrdup(buf);
1632   }
1633   D( fprintf(stderr, "noip(%d): socketdir: %s\n", pid, sockdir);
1634      fprintf(stderr, "noip(%d): autoports: %u-%u\n",
1635              pid, minautoport, maxautoport);
1636      fprintf(stderr, "noip(%d): realbind acl:\n", pid);
1637      dump_acl(bind_real);
1638      fprintf(stderr, "noip(%d): realconnect acl:\n", pid);
1639      dump_acl(connect_real);
1640      fprintf(stderr, "noip(%d): impbind list:\n", pid);
1641      dump_impbind_list(); )
1642 }
1643
1644 /*----- Overridden system calls -------------------------------------------*/
1645
1646 static void dump_syserr(long rc)
1647   { fprintf(stderr, " => %ld (E%d)\n", rc, errno); }
1648
1649 static void dump_sysresult(long rc)
1650 {
1651   if (rc < 0) dump_syserr(rc);
1652   else fprintf(stderr, " => %ld\n", rc);
1653 }
1654
1655 static void dump_addrresult(long rc, const struct sockaddr *sa,
1656                             socklen_t len)
1657 {
1658   char addrbuf[ADDRBUFSZ];
1659
1660   if (rc < 0) dump_syserr(rc);
1661   else {
1662     fprintf(stderr, " => %ld [%s]\n", rc,
1663             present_sockaddr(sa, len, addrbuf, sizeof(addrbuf)));
1664   }
1665 }
1666
1667 int socket(int pf, int ty, int proto)
1668 {
1669   int sk;
1670
1671   D( fprintf(stderr, "noip(%d): SOCKET pf=%d, type=%d, proto=%d",
1672              getpid(), pf, ty, proto); )
1673
1674   switch (pf) {
1675     default:
1676       if (!family_known_p(pf)) {
1677         D( fprintf(stderr, " -> unknown; refuse\n"); )
1678         errno = EAFNOSUPPORT;
1679         sk = -1;
1680       }
1681       D( fprintf(stderr, " -> inet; substitute"); )
1682       pf = PF_UNIX;
1683       proto = 0;
1684       break;
1685     case PF_UNIX:
1686 #ifdef PF_NETLINK
1687     case PF_NETLINK:
1688 #endif
1689       D( fprintf(stderr, " -> safe; permit"); )
1690       break;
1691   }
1692   sk = real_socket(pf, ty, proto);
1693   D( dump_sysresult(sk); )
1694   return (sk);
1695 }
1696
1697 int socketpair(int pf, int ty, int proto, int *sk)
1698 {
1699   int rc;
1700
1701   D( fprintf(stderr, "noip(%d): SOCKETPAIR pf=%d, type=%d, proto=%d",
1702              getpid(), pf, ty, proto); )
1703   if (!family_known_p(pf))
1704     D( fprintf(stderr, " -> unknown; permit"); )
1705   else {
1706     D( fprintf(stderr, " -> inet; substitute"); )
1707     pf = PF_UNIX;
1708     proto = 0;
1709   }
1710   rc = real_socketpair(pf, ty, proto, sk);
1711   D( if (rc < 0) dump_syserr(rc);
1712      else fprintf(stderr, " => %d (%d, %d)\n", rc, sk[0], sk[1]); )
1713   return (rc);
1714 }
1715
1716 int bind(int sk, const struct sockaddr *sa, socklen_t len)
1717 {
1718   struct sockaddr_un sun;
1719   int rc;
1720   Dpid;
1721
1722   D({ char buf[ADDRBUFSZ];
1723       fprintf(stderr, "noip(%d): BIND sk=%d, sa[%d]=%s", pid,
1724               sk, len, present_sockaddr(sa, len, buf, sizeof(buf))); })
1725
1726   if (!family_known_p(sa->sa_family))
1727     D( fprintf(stderr, " -> unknown af; pass through"); )
1728   else {
1729     D( fprintf(stderr, " -> checking...\n"); )
1730     PRESERVING_ERRNO({
1731       if (acl_allows_p(bind_real, sa)) {
1732         if (fixup_real_ip_socket(sk, sa->sa_family, 0))
1733           return (-1);
1734       } else {
1735         encode_inet_addr(&sun, sa, ENCF_FRESH);
1736         sa = SA(&sun);
1737         len = SUN_LEN(&sun);
1738       }
1739     });
1740     D( fprintf(stderr, "noip(%d): BIND ...", pid); )
1741   }
1742   rc = real_bind(sk, sa, len);
1743   D( dump_sysresult(rc); )
1744   return (rc);
1745 }
1746
1747 int connect(int sk, const struct sockaddr *sa, socklen_t len)
1748 {
1749   struct sockaddr_un sun;
1750   int rc;
1751   Dpid;
1752
1753   D({ char buf[ADDRBUFSZ];
1754       fprintf(stderr, "noip(%d): CONNECT sk=%d, sa[%d]=%s", pid,
1755               sk, len, present_sockaddr(sa, len, buf, sizeof(buf))); })
1756
1757   if (!family_known_p(sa->sa_family)) {
1758     D( fprintf(stderr, " -> unknown af; pass through"); )
1759     rc = real_connect(sk, sa, len);
1760   } else {
1761     D( fprintf(stderr, " -> checking...\n"); )
1762     PRESERVING_ERRNO({
1763       fixup_client_socket(sk, &sa, &len, &sun);
1764     });
1765     D( fprintf(stderr, "noip(%d): CONNECT ...", pid); )
1766     rc = real_connect(sk, sa, len);
1767     if (rc < 0) {
1768       switch (errno) {
1769         case ENOENT: errno = ECONNREFUSED; break;
1770       }
1771     }
1772   }
1773   D( dump_sysresult(rc); )
1774   return (rc);
1775 }
1776
1777 ssize_t sendto(int sk, const void *buf, size_t len, int flags,
1778                const struct sockaddr *to, socklen_t tolen)
1779 {
1780   struct sockaddr_un sun;
1781   ssize_t n;
1782   Dpid;
1783
1784   D({ char addrbuf[ADDRBUFSZ];
1785       fprintf(stderr, "noip(%d): SENDTO sk=%d, len=%lu, flags=%d, to[%d]=%s",
1786               pid, sk, (unsigned long)len, flags, tolen,
1787               present_sockaddr(to, tolen, addrbuf, sizeof(addrbuf))); })
1788
1789   if (!to)
1790     D( fprintf(stderr, " -> null address; leaving"); )
1791   else if (!family_known_p(to->sa_family))
1792     D( fprintf(stderr, " -> unknown af; pass through"); )
1793   else {
1794     D( fprintf(stderr, " -> checking...\n"); )
1795     PRESERVING_ERRNO({
1796       fixup_client_socket(sk, &to, &tolen, &sun);
1797     });
1798     D( fprintf(stderr, "noip(%d): SENDTO ...", pid); )
1799   }
1800   n = real_sendto(sk, buf, len, flags, to, tolen);
1801   D( dump_sysresult(n); )
1802   return (n);
1803 }
1804
1805 ssize_t recvfrom(int sk, void *buf, size_t len, int flags,
1806                  struct sockaddr *from, socklen_t *fromlen)
1807 {
1808   char sabuf[1024];
1809   socklen_t mylen = sizeof(sabuf);
1810   ssize_t n;
1811   Dpid;
1812
1813   D( fprintf(stderr, "noip(%d): RECVFROM sk=%d, len=%lu, flags=%d",
1814              pid, sk, (unsigned long)len, flags); )
1815
1816   if (!from) {
1817     D( fprintf(stderr, " -> null addr; pass through"); )
1818     n = real_recvfrom(sk, buf, len, flags, 0, 0);
1819   } else {
1820     n = real_recvfrom(sk, buf, len, flags, SA(sabuf), &mylen);
1821     if (n >= 0) {
1822       D( fprintf(stderr, " -> converting...\n"); )
1823       PRESERVING_ERRNO({
1824         return_fake_peer(sk, SA(sabuf), mylen, from, fromlen);
1825       });
1826       D( fprintf(stderr, "noip(%d): ... RECVFROM", pid); )
1827     }
1828   }
1829   D( dump_addrresult(n, from, fromlen ? *fromlen : 0); )
1830   return (n);
1831 }
1832
1833 ssize_t sendmsg(int sk, const struct msghdr *msg, int flags)
1834 {
1835   struct sockaddr_un sun;
1836   const struct sockaddr *sa = SA(msg->msg_name);
1837   struct msghdr mymsg;
1838   ssize_t n;
1839   Dpid;
1840
1841   D({ char addrbuf[ADDRBUFSZ];
1842       fprintf(stderr, "noip(%d): SENDMSG sk=%d, "
1843                       "msg_flags=%d, msg_name[%d]=%s, ...",
1844               pid, sk, msg->msg_flags, msg->msg_namelen,
1845               present_sockaddr(sa, msg->msg_namelen,
1846                                addrbuf, sizeof(addrbuf))); })
1847
1848   if (!sa)
1849     D( fprintf(stderr, " -> null address; leaving"); )
1850   else if (!family_known_p(sa->sa_family))
1851     D( fprintf(stderr, " -> unknown af; pass through"); )
1852   else {
1853     D( fprintf(stderr, " -> checking...\n"); )
1854     PRESERVING_ERRNO({
1855       mymsg = *msg;
1856       fixup_client_socket(sk, &sa, &mymsg.msg_namelen, &sun);
1857       mymsg.msg_name = SA(sa);
1858       msg = &mymsg;
1859     });
1860     D( fprintf(stderr, "noip(%d): SENDMSG ...", pid); )
1861   }
1862   n = real_sendmsg(sk, msg, flags);
1863   D( dump_sysresult(n); )
1864   return (n);
1865 }
1866
1867 ssize_t recvmsg(int sk, struct msghdr *msg, int flags)
1868 {
1869   char sabuf[1024];
1870   struct sockaddr *sa = SA(msg->msg_name);
1871   socklen_t len = msg->msg_namelen;
1872   ssize_t n;
1873   Dpid;
1874
1875   D( fprintf(stderr, "noip(%d): RECVMSG sk=%d msg_flags=%d, ...",
1876              pid, sk, msg->msg_flags); )
1877
1878   if (!msg->msg_name) {
1879     D( fprintf(stderr, " -> null addr; pass through"); )
1880     return (real_recvmsg(sk, msg, flags));
1881   } else {
1882     msg->msg_name = sabuf;
1883     msg->msg_namelen = sizeof(sabuf);
1884     n = real_recvmsg(sk, msg, flags);
1885     if (n >= 0) {
1886       D( fprintf(stderr, " -> converting...\n"); )
1887       PRESERVING_ERRNO({
1888         return_fake_peer(sk, SA(sabuf), msg->msg_namelen, sa, &len);
1889       });
1890     }
1891     D( fprintf(stderr, "noip(%d): ... RECVMSG", pid); )
1892     msg->msg_name = sa;
1893     msg->msg_namelen = len;
1894   }
1895   D( dump_addrresult(n, sa, len); )
1896   return (n);
1897 }
1898
1899 int accept(int sk, struct sockaddr *sa, socklen_t *len)
1900 {
1901   char sabuf[1024];
1902   socklen_t mylen = sizeof(sabuf);
1903   int nsk;
1904   Dpid;
1905
1906   D( fprintf(stderr, "noip(%d): ACCEPT sk=%d", pid, sk); )
1907
1908   nsk = real_accept(sk, SA(sabuf), &mylen);
1909   if (nsk < 0) /* failed */;
1910   else if (!sa) D( fprintf(stderr, " -> address not wanted"); )
1911   else {
1912     D( fprintf(stderr, " -> converting...\n"); )
1913     return_fake_peer(sk, SA(sabuf), mylen, sa, len);
1914     D( fprintf(stderr, "noip(%d): ... ACCEPT", pid); )
1915   }
1916   D( dump_addrresult(nsk, sa, len ? *len : 0); )
1917   return (nsk);
1918 }
1919
1920 int getsockname(int sk, struct sockaddr *sa, socklen_t *len)
1921 {
1922   char sabuf[1024];
1923   socklen_t mylen = sizeof(sabuf);
1924   int rc;
1925   Dpid;
1926
1927   D( fprintf(stderr, "noip(%d): GETSOCKNAME sk=%d", pid, sk); )
1928   rc = real_getsockname(sk, SA(sabuf), &mylen);
1929   if (rc >= 0) {
1930     D( fprintf(stderr, " -> converting...\n"); )
1931     return_fake_name(SA(sabuf), mylen, sa, len, 0);
1932     D( fprintf(stderr, "noip(%d): ... GETSOCKNAME", pid); )
1933   }
1934   D( dump_addrresult(rc, sa, *len); )
1935   return (rc);
1936 }
1937
1938 int getpeername(int sk, struct sockaddr *sa, socklen_t *len)
1939 {
1940   char sabuf[1024];
1941   socklen_t mylen = sizeof(sabuf);
1942   int rc;
1943   Dpid;
1944
1945   D( fprintf(stderr, "noip(%d): GETPEERNAME sk=%d", pid, sk); )
1946   rc = real_getpeername(sk, SA(sabuf), &mylen);
1947   if (rc >= 0) {
1948     D( fprintf(stderr, " -> converting...\n"); )
1949     return_fake_peer(sk, SA(sabuf), mylen, sa, len);
1950     D( fprintf(stderr, "noip(%d): ... GETPEERNAME", pid); )
1951   }
1952   D( dump_addrresult(rc, sa, *len); )
1953   return (0);
1954 }
1955
1956 int getsockopt(int sk, int lev, int opt, void *p, socklen_t *len)
1957 {
1958   switch (lev) {
1959     case IPPROTO_IP:
1960     case IPPROTO_IPV6:
1961     case IPPROTO_TCP:
1962     case IPPROTO_UDP:
1963       if (*len > 0)
1964         memset(p, 0, *len);
1965       return (0);
1966   }
1967   return (real_getsockopt(sk, lev, opt, p, len));
1968 }
1969
1970 int setsockopt(int sk, int lev, int opt, const void *p, socklen_t len)
1971 {
1972   switch (lev) {
1973     case IPPROTO_IP:
1974     case IPPROTO_IPV6:
1975     case IPPROTO_TCP:
1976     case IPPROTO_UDP:
1977       return (0);
1978   }
1979   switch (opt) {
1980     case SO_BINDTODEVICE:
1981     case SO_ATTACH_FILTER:
1982     case SO_DETACH_FILTER:
1983       return (0);
1984   }
1985   return (real_setsockopt(sk, lev, opt, p, len));
1986 }
1987
1988 int ioctl(int fd, unsigned long op, ...)
1989 {
1990   va_list ap;
1991   void *arg;
1992   int sk;
1993   int rc;
1994
1995   va_start(ap, op);
1996   arg = va_arg(ap, void *);
1997
1998   switch (op) {
1999     case SIOCGIFADDR:
2000     case SIOCGIFBRDADDR:
2001     case SIOCGIFDSTADDR:
2002     case SIOCGIFNETMASK:
2003       PRESERVING_ERRNO({
2004         if (fixup_real_ip_socket(fd, AF_INET, &sk)) goto real;
2005       });
2006       rc = real_ioctl(sk, op, arg);
2007       PRESERVING_ERRNO({ close(sk); });
2008       break;
2009     default:
2010     real:
2011       rc = real_ioctl(fd, op, arg);
2012       break;
2013   }
2014   va_end(ap);
2015   return (rc);
2016 }
2017
2018 /*----- Initialization ----------------------------------------------------*/
2019
2020 /* Clean up the socket directory, deleting stale sockets. */
2021 static void cleanup_sockdir(void)
2022 {
2023   DIR *dir;
2024   struct dirent *d;
2025   address addr;
2026   struct sockaddr_un sun;
2027   struct stat st;
2028   Dpid;
2029
2030   if ((dir = opendir(sockdir)) == 0) return;
2031   sun.sun_family = AF_UNIX;
2032   while ((d = readdir(dir)) != 0) {
2033     if (d->d_name[0] == '.') continue;
2034     snprintf(sun.sun_path, sizeof(sun.sun_path),
2035              "%s/%s", sockdir, d->d_name);
2036     if (decode_inet_addr(&addr.sa, 0, &sun, SUN_LEN(&sun)) ||
2037         stat(sun.sun_path, &st) ||
2038         !S_ISSOCK(st.st_mode)) {
2039       D( fprintf(stderr, "noip(%d): ignoring unknown socketdir entry `%s'\n",
2040                  pid, sun.sun_path); )
2041       continue;
2042     }
2043     if (unix_socket_status(&sun, 0) == STALE) {
2044       D( fprintf(stderr, "noip(%d): clearing away stale socket %s\n",
2045                  pid, d->d_name); )
2046       unlink(sun.sun_path);
2047     }
2048   }
2049   closedir(dir);
2050 }
2051
2052 /* Find the addresses attached to local network interfaces, and remember them
2053  * in a table.
2054  */
2055 static void get_local_ipaddrs(void)
2056 {
2057   struct ifaddrs *ifa_head, *ifa;
2058   ipaddr a;
2059   int i;
2060   Dpid;
2061
2062   D( fprintf(stderr, "noip(%d): fetching local addresses...\n", pid); )
2063   if (getifaddrs(&ifa_head)) { perror("getifaddrs"); return; }
2064   for (n_local_ipaddrs = 0, ifa = ifa_head;
2065        n_local_ipaddrs < MAX_LOCAL_IPADDRS && ifa;
2066        ifa = ifa->ifa_next) {
2067     if (!ifa->ifa_addr || !family_known_p(ifa->ifa_addr->sa_family))
2068       continue;
2069     ipaddr_from_sockaddr(&a, ifa->ifa_addr);
2070     D({ char buf[ADDRBUFSZ];
2071         fprintf(stderr, "noip(%d):   local addr %s = %s", pid,
2072                 ifa->ifa_name,
2073                 inet_ntop(ifa->ifa_addr->sa_family, &a,
2074                           buf, sizeof(buf))); })
2075     for (i = 0; i < n_local_ipaddrs; i++) {
2076       if (ifa->ifa_addr->sa_family == local_ipaddrs[i].af &&
2077           ipaddr_equal_p(local_ipaddrs[i].af, &a, &local_ipaddrs[i].addr)) {
2078         D( fprintf(stderr, " (duplicate)\n"); )
2079         goto skip;
2080       }
2081     }
2082     D( fprintf(stderr, "\n"); )
2083     local_ipaddrs[n_local_ipaddrs].af = ifa->ifa_addr->sa_family;
2084     local_ipaddrs[n_local_ipaddrs].addr = a;
2085     n_local_ipaddrs++;
2086   skip:;
2087   }
2088   freeifaddrs(ifa_head);
2089 }
2090
2091 /* Print the given message to standard error.  Avoids stdio. */
2092 static void printerr(const char *p)
2093   { if (write(STDERR_FILENO, p, strlen(p))) ; }
2094
2095 /* Create the socket directory, being careful about permissions. */
2096 static void create_sockdir(void)
2097 {
2098   struct stat st;
2099
2100   if (lstat(sockdir, &st)) {
2101     if (errno == ENOENT) {
2102       if (mkdir(sockdir, 0700)) {
2103         perror("noip: creating socketdir");
2104         exit(127);
2105       }
2106       if (!lstat(sockdir, &st))
2107         goto check;
2108     }
2109     perror("noip: checking socketdir");
2110     exit(127);
2111   }
2112 check:
2113   if (!S_ISDIR(st.st_mode)) {
2114     printerr("noip: bad socketdir: not a directory\n");
2115     exit(127);
2116   }
2117   if (st.st_uid != uid) {
2118     printerr("noip: bad socketdir: not owner\n");
2119     exit(127);
2120   }
2121   if (st.st_mode & 077) {
2122     printerr("noip: bad socketdir: not private\n");
2123     exit(127);
2124   }
2125 }
2126
2127 /* Initialization function. */
2128 static void setup(void) __attribute__((constructor));
2129 static void setup(void)
2130 {
2131   PRESERVING_ERRNO({
2132     char *p;
2133
2134     import();
2135     uid = geteuid();
2136     if ((p = getenv("NOIP_DEBUG")) && atoi(p))
2137       debug = 1;
2138     get_local_ipaddrs();
2139     readconfig();
2140     create_sockdir();
2141     cleanup_sockdir();
2142   });
2143 }
2144
2145 /*----- That's all, folks -------------------------------------------------*/