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