chiark / gitweb /
noip.c: Make sure it's an AF_UNIX address before counting the length.
[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 distributed in the hope that it will be useful, but WITHOUT
18  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
20  * more details.
21  *
22  * You should have received a copy of the GNU General Public License along
23  * with mLib; if not, write to the Free Software Foundation, Inc., 59 Temple
24  * 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 <ctype.h>
35 #include <errno.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38
39 #include <unistd.h>
40 #include <dirent.h>
41 #include <dlfcn.h>
42 #include <fcntl.h>
43 #include <pwd.h>
44
45 #include <sys/ioctl.h>
46 #include <sys/socket.h>
47 #include <sys/stat.h>
48 #include <sys/un.h>
49
50 #include <netinet/in.h>
51 #include <arpa/inet.h>
52 #include <netinet/tcp.h>
53 #include <netinet/udp.h>
54 #include <net/if.h>
55
56 /*----- Data structures ---------------------------------------------------*/
57
58 enum { UNUSED, STALE, USED };           /* Unix socket status values */
59 enum { WANT_FRESH, WANT_EXISTING };     /* Socket address dispositions */
60 enum { DENY, ALLOW };                   /* ACL verdicts */
61
62 /* Access control list nodes */
63 typedef struct aclnode {
64   struct aclnode *next;
65   int act;
66   unsigned long minaddr, maxaddr;
67   unsigned short minport, maxport;
68 } aclnode;
69
70 /* Local address records */
71 #define MAX_LOCAL_IPADDRS 16
72 static struct in_addr local_ipaddrs[MAX_LOCAL_IPADDRS];
73 static int n_local_ipaddrs;
74
75 /* General configuration */
76 static uid_t uid;
77 static char *sockdir = 0;
78 static int debug = 0;
79 static unsigned minautoport = 16384, maxautoport = 65536;
80
81 /* Access control lists */
82 static aclnode *bind_real, **bind_tail = &bind_real;
83 static aclnode *connect_real,  **connect_tail = &connect_real;
84
85 /*----- Import the real versions of functions -----------------------------*/
86
87 /* The list of functions to immport. */
88 #define IMPORTS(_)                                                      \
89   _(socket, int, (int, int, int))                                       \
90   _(socketpair, int, (int, int, int, int *))                            \
91   _(connect, int, (int, const struct sockaddr *, socklen_t))            \
92   _(bind, int, (int, const struct sockaddr *, socklen_t))               \
93   _(accept, int, (int, struct sockaddr *, socklen_t *))                 \
94   _(getsockname, int, (int, struct sockaddr *, socklen_t *))            \
95   _(getpeername, int, (int, struct sockaddr *, socklen_t *))            \
96   _(getsockopt, int, (int, int, int, void *, socklen_t *))              \
97   _(setsockopt, int, (int, int, int, const void *, socklen_t))          \
98   _(sendto, ssize_t, (int, const void *buf, size_t, int,                \
99                       const struct sockaddr *to, socklen_t tolen))      \
100   _(recvfrom, ssize_t, (int, void *buf, size_t, int,                    \
101                         struct sockaddr *from, socklen_t *fromlen))     \
102   _(sendmsg, ssize_t, (int, const struct msghdr *, int))                \
103   _(recvmsg, ssize_t, (int, struct msghdr *, int))                      \
104   _(close, int, (int))
105
106 /* Function pointers to set up. */
107 #define DECL(imp, ret, args) static ret (*real_##imp) args;
108 IMPORTS(DECL)
109 #undef DECL
110
111 /* Import the system calls. */
112 static void import(void)
113 {
114 #define IMPORT(imp, ret, args)                                          \
115     real_##imp = (ret (*)args)dlsym(RTLD_NEXT, #imp);
116   IMPORTS(IMPORT)
117 #undef IMPORT
118 }
119
120 /*----- Utilities ---------------------------------------------------------*/
121
122 /* Socket address casts */
123 #define SA(sa) ((struct sockaddr *)(sa))
124 #define SIN(sa) ((struct sockaddr_in *)(sa))
125 #define SUN(sa) ((struct sockaddr_un *)(sa))
126
127 /* Raw bytes */
128 #define UC(ch) ((unsigned char)(ch))
129
130 /* Memory allocation */
131 #define NEW(x) ((x) = xmalloc(sizeof(*x)))
132 #define NEWV(x, n) ((x) = xmalloc(sizeof(*x) * (n)))
133
134 /* Debugging */
135 #ifdef DEBUG
136 #  define D(body) { if (debug) { body } }
137 #else
138 #  define D(body) ;
139 #endif
140
141 /* Preservation of error status */
142 #define PRESERVING_ERRNO(body) do {                                     \
143   int _err = errno; { body } errno = _err;                              \
144 } while (0)
145
146 /* Allocate N bytes of memory; abort on failure. */
147 static void *xmalloc(size_t n)
148 {
149   void *p;
150   if (!n) return (0);
151   if ((p = malloc(n)) == 0) { perror("malloc"); exit(127); }
152   return (p);
153 }
154
155 /* Allocate a copy of the null-terminated string P; abort on failure. */
156 static char *xstrdup(const char *p)
157 {
158   size_t n = strlen(p) + 1;
159   char *q = xmalloc(n);
160   memcpy(q, p, n);
161   return (q);
162 }
163 /*----- Access control lists ----------------------------------------------*/
164
165 #ifdef DEBUG
166
167 /* Write to standard error a description of the ACL node A. */
168 static void dump_aclnode(aclnode *a)
169 {
170   char minbuf[16], maxbuf[16];
171   struct in_addr amin, amax;
172
173   amin.s_addr = htonl(a->minaddr);
174   amax.s_addr = htonl(a->maxaddr);
175   fprintf(stderr, "noip:   %c ", a->act ? '+' : '-');
176   if (a->minaddr == 0 && a->maxaddr == 0xffffffff)
177     fprintf(stderr, "any");
178   else {
179     fprintf(stderr, "%s",
180             inet_ntop(AF_INET, &amin, minbuf, sizeof(minbuf)));
181     if (a->maxaddr != a->minaddr) {
182       fprintf(stderr, "-%s",
183               inet_ntop(AF_INET, &amax, maxbuf, sizeof(maxbuf)));
184     }
185   }
186   if (a->minport != 0 || a->maxport != 0xffff) {
187     fprintf(stderr, ":%u", (unsigned)a->minport);
188     if (a->minport != a->maxport)
189       fprintf(stderr, "-%u", (unsigned)a->maxport);
190   }
191   fputc('\n', stderr);
192 }
193
194 static void dump_acl(aclnode *a)
195 {
196   int act = ALLOW;
197
198   for (; a; a = a->next) {
199     dump_aclnode(a);
200     act = a->act;
201   }
202   fprintf(stderr, "noip:   [default policy: %s]\n",
203           act == ALLOW ? "DENY" : "ALLOW");
204 }
205
206 #endif
207
208 /* Returns nonzero if the ACL A allows the IP socket SIN. */
209 static int acl_allows_p(aclnode *a, const struct sockaddr_in *sin)
210 {
211   unsigned long addr = ntohl(sin->sin_addr.s_addr);
212   unsigned short port = ntohs(sin->sin_port);
213   int act = ALLOW;
214
215   D( char buf[16];
216      fprintf(stderr, "noip: check %s:%u\n",
217              inet_ntop(AF_INET, &sin->sin_addr, buf, sizeof(buf)),
218              ntohs((unsigned)sin->sin_port)); )
219   for (; a; a = a->next) {
220     D( dump_aclnode(a); )
221     if (a->minaddr <= addr && addr <= a->maxaddr &&
222         a->minport <= port && port <= a->maxport) {
223       D( fprintf(stderr, "noip: aha!  %s\n", a->act ? "ALLOW" : "DENY"); )
224       return (a->act);
225     }
226     act = a->act;
227   }
228   D( fprintf(stderr, "noip: nothing found: %s\n", act ? "DENY" : "ALLOW"); )
229   return (!act);
230 }
231
232 /*----- Socket address conversion -----------------------------------------*/
233
234 /* Return a uniformly distributed integer between MIN and MAX inclusive. */
235 static unsigned randrange(unsigned min, unsigned max)
236 {
237   unsigned mask, i;
238
239   /* It's so nice not to have to care about the quality of the generator
240      much! */
241   max -= min;
242   for (mask = 1; mask < max; mask = (mask << 1) | 1)
243     ;
244   do i = rand() & mask; while (i > max);
245   return (i + min);
246 }
247
248 /* Return the status of Unix-domain socket address SUN.  Returns: UNUSED if
249  * the socket doesn't exist; USED if the path refers to an active socket, or
250  * isn't really a socket at all, or we can't tell without a careful search
251  * and QUICKP is set; or STALE if the file refers to a socket which isn't
252  * being used any more.
253  */
254 static int unix_socket_status(struct sockaddr_un *sun, int quickp)
255 {
256   struct stat st;
257   FILE *fp = 0;
258   size_t len, n;
259   int rc;
260   char buf[256];
261
262   if (stat(sun->sun_path, &st))
263     return (errno == ENOENT ? UNUSED : USED);
264   if (!S_ISSOCK(st.st_mode) || quickp)
265     return (USED);
266   rc = USED;
267   if ((fp = fopen("/proc/net/unix", "r")) == 0)
268     goto done;
269   if (!fgets(buf, sizeof(buf), fp)) goto done; /* skip header */
270   len = strlen(sun->sun_path);
271   while (fgets(buf, sizeof(buf), fp)) {
272     n = strlen(buf);
273     if (n >= len + 2 && buf[n - len - 2] == ' ' && buf[n - 1] == '\n' &&
274         memcmp(buf + n - len - 1, sun->sun_path, len) == 0)
275       goto done;
276   }
277   if (ferror(fp))
278     goto done;
279   rc = STALE;
280 done:
281   if (fp) fclose(fp);
282   return (rc);
283 }
284
285 /* Encode the Internet address SIN as a Unix-domain address SUN.  If WANT is
286  * WANT_FRESH, and SIN->sin_port is zero, then we pick an arbitrary local
287  * port.  Otherwise we pick the port given.  There's an unpleasant hack to
288  * find servers bound to INADDR_ANY.  Returns zero on success; -1 on failure.
289  */
290 static int encode_inet_addr(struct sockaddr_un *sun,
291                             const struct sockaddr_in *sin,
292                             int want)
293 {
294   int i;
295   int desperatep = 0;
296   char buf[INET_ADDRSTRLEN];
297   int rc;
298
299   D( fprintf(stderr, "noip: encode %s:%u (%s)",
300              inet_ntop(AF_INET, &sin->sin_addr, buf, sizeof(buf)),
301              (unsigned)ntohs(sin->sin_port),
302              want == WANT_EXISTING ? "EXISTING" : "FRESH"); )
303   sun->sun_family = AF_UNIX;
304   if (sin->sin_port || want == WANT_EXISTING) {
305     snprintf(sun->sun_path, sizeof(sun->sun_path), "%s/%s:%u", sockdir,
306              inet_ntop(AF_INET, &sin->sin_addr, buf, sizeof(buf)),
307              (unsigned)ntohs(sin->sin_port));
308     rc = unix_socket_status(sun, 0);
309     if (rc == STALE) unlink(sun->sun_path);
310     if (rc != USED && want == WANT_EXISTING) {
311       snprintf(sun->sun_path, sizeof(sun->sun_path), "%s/0.0.0.0:%u",
312                sockdir, (unsigned)ntohs(sin->sin_port));
313       if (unix_socket_status(sun, 0) == STALE) unlink(sun->sun_path);
314     }
315   } else {
316     for (i = 0; i < 10; i++) {
317       snprintf(sun->sun_path, sizeof(sun->sun_path), "%s/%s:%u", sockdir,
318                inet_ntop(AF_INET, &sin->sin_addr, buf, sizeof(buf)),
319                randrange(minautoport, maxautoport));
320       if (unix_socket_status(sun, 1) == UNUSED) goto found;
321     }
322     for (desperatep = 0; desperatep < 2; desperatep++) {
323       for (i = minautoport; i <= maxautoport; i++) {
324         snprintf(sun->sun_path, sizeof(sun->sun_path), "%s/%s:%u", sockdir,
325                  inet_ntop(AF_INET, &sin->sin_addr, buf, sizeof(buf)),
326                  (unsigned)i);
327         rc = unix_socket_status(sun, !desperatep);
328         switch (rc) {
329           case STALE: unlink(sun->sun_path);
330           case UNUSED: goto found;
331         }
332       }
333     }
334     errno = EADDRINUSE;
335     D( fprintf(stderr, " -- can't resolve\n"); )
336     return (-1);
337   found:;
338   }
339   D( fprintf(stderr, " -> `%s'\n", sun->sun_path); )
340   return (0);
341 }
342
343 /* Decode the Unix address SUN to an Internet address SIN.  If
344  * DECODE_UNBOUND_P is nonzero, an empty address (indicative of an unbound
345  * Unix-domain socket) is translated to a wildcard Internet address.  Returns
346  * zero on success; -1 on failure (e.g., it wasn't one of our addresses).
347  */
348 static int decode_inet_addr(struct sockaddr_in *sin,
349                             const struct sockaddr_un *sun,
350                             socklen_t len,
351                             int decode_unbound_p)
352 {
353   char buf[INET_ADDRSTRLEN + 16];
354   char *p;
355   size_t n = strlen(sockdir), nn;
356   struct sockaddr_in sin_mine;
357   unsigned long port;
358
359   if (!sin)
360     sin = &sin_mine;
361   if (sun->sun_family != AF_UNIX)
362     return (-1);
363   nn = strlen(sun->sun_path);
364   if (len < sizeof(sun)) ((char *)sun)[len] = 0;
365   D( fprintf(stderr, "noip: decode (%d) `%s'",
366              *sun->sun_path, sun->sun_path); )
367   if (decode_unbound_p && !sun->sun_path[0]) {
368     sin->sin_family = AF_INET;
369     sin->sin_addr.s_addr = INADDR_ANY;
370     sin->sin_port = 0;
371     D( fprintf(stderr, " -- unbound socket\n"); )
372     return (0);
373   }
374   if (nn < n + 1 || nn - n >= sizeof(buf) || sun->sun_path[n] != '/' ||
375       memcmp(sun->sun_path, sockdir, n) != 0) {
376     D( fprintf(stderr, " -- not one of ours\n"); )
377     return (-1);
378   }
379   memcpy(buf, sun->sun_path + n + 1, nn - n);
380   if ((p = strchr(buf, ':')) == 0) {
381     D( fprintf(stderr, " -- malformed (no port)\n"); )
382     return (-1);
383   }
384   *p++ = 0;
385   sin->sin_family = AF_INET;
386   if (inet_pton(AF_INET, buf, &sin->sin_addr) <= 0) {
387     D( fprintf(stderr, " -- malformed (bad address `%s')\n", buf); )
388     return (-1);
389   }
390   port = strtoul(p, &p, 10);
391   if (*p || port >= 65536) {
392     D( fprintf(stderr, " -- malformed (port out of range)"); )
393     return (-1);
394   }
395   sin->sin_port = htons(port);
396   D( fprintf(stderr, " -> %s:%u\n",
397              inet_ntop(AF_INET, &sin->sin_addr, buf, sizeof(buf)),
398              (unsigned)port); )
399   return (0);
400 }
401
402 /* SK is (or at least might be) a Unix-domain socket we created when an
403  * Internet socket was asked for.  We've decided it should be an Internet
404  * socket after all, so convert it.
405  */
406 static int fixup_real_ip_socket(int sk)
407 {
408   int nsk;
409   int type;
410   int f, fd;
411   struct sockaddr_un sun;
412   struct sockaddr_in sin;
413   socklen_t len;
414
415 #define OPTS(_)                                                         \
416   _(DEBUG, int)                                                         \
417   _(REUSEADDR, int)                                                     \
418   _(DONTROUTE, int)                                                     \
419   _(BROADCAST, int)                                                     \
420   _(SNDBUF, int)                                                        \
421   _(RCVBUF, int)                                                        \
422   _(OOBINLINE, int)                                                     \
423   _(NO_CHECK, int)                                                      \
424   _(LINGER, struct linger)                                              \
425   _(BSDCOMPAT, int)                                                     \
426   _(RCVLOWAT, int)                                                      \
427   _(RCVTIMEO, struct timeval)                                           \
428   _(SNDTIMEO, struct timeval)
429
430   len = sizeof(sun);
431   if (real_getsockname(sk, SA(&sun), &len))
432     return (-1);
433   if (decode_inet_addr(&sin, &sun, len, 1))
434     return (0); /* Not one of ours */
435   len = sizeof(type);
436   if (real_getsockopt(sk, SOL_SOCKET, SO_TYPE, &type, &len) < 0 ||
437       (nsk = real_socket(PF_INET, type, 0)) < 0)
438     return (-1);
439 #define FIX(opt, ty) do {                                               \
440   ty ov_;                                                               \
441   len = sizeof(ov_);                                                    \
442   if (real_getsockopt(sk, SOL_SOCKET, SO_##opt, &ov_, &len) < 0 ||      \
443       real_setsockopt(nsk, SOL_SOCKET, SO_##opt, &ov_, len)) {          \
444     real_close(nsk);                                                    \
445     return (-1);                                                        \
446   }                                                                     \
447 } while (0);
448   OPTS(FIX)
449 #undef FIX
450   if ((f = fcntl(sk, F_GETFL)) < 0 ||
451       (fd = fcntl(sk, F_GETFD)) < 0 ||
452       fcntl(nsk, F_SETFL, f) < 0 ||
453       dup2(nsk, sk) < 0) {
454     real_close(nsk);
455     return (-1);
456   }
457   unlink(sun.sun_path);
458   real_close(nsk);
459   if (fcntl(sk, F_SETFD, fd) < 0) {
460     perror("noip: fixup_real_ip_socket F_SETFD");
461     abort();
462   }
463   return (0);
464 }
465
466 /* The socket SK is about to be used to communicate with the remote address
467  * SA.  Assign it a local address so that getpeername does something useful.
468  */
469 static int do_implicit_bind(int sk, const struct sockaddr **sa,
470                             socklen_t *len, struct sockaddr_un *sun)
471 {
472   struct sockaddr_in sin;
473   socklen_t mylen = sizeof(*sun);
474
475   if (acl_allows_p(connect_real, SIN(*sa))) {
476     if (fixup_real_ip_socket(sk))
477       return (-1);
478   } else {
479     if (real_getsockname(sk, SA(sun), &mylen) < 0)
480       return (-1);
481     if (sun->sun_family == AF_UNIX) {
482       if (mylen < sizeof(*sun)) ((char *)sun)[mylen] = 0;
483       if (!sun->sun_path[0]) {
484         sin.sin_family = AF_INET;
485         sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
486         sin.sin_port = 0;
487         encode_inet_addr(sun, &sin, WANT_FRESH);
488         if (real_bind(sk, SA(sun), SUN_LEN(sun)))
489           return (-1);
490       }
491       encode_inet_addr(sun, SIN(*sa), WANT_EXISTING);
492       *sa = SA(sun);
493       *len = SUN_LEN(sun);
494     }
495   }
496   return (0);
497 }
498
499 /* We found the real address SA, with length LEN; if it's a Unix-domain
500  * address corresponding to a fake socket, convert it to cover up the
501  * deception.  Whatever happens, put the result at FAKE and store its length
502  * at FAKELEN.
503  */
504 static void return_fake_name(struct sockaddr *sa, socklen_t len,
505                              struct sockaddr *fake, socklen_t *fakelen)
506 {
507   struct sockaddr_in sin;
508   socklen_t alen;
509
510   if (sa->sa_family == AF_UNIX &&
511       !decode_inet_addr(&sin, SUN(sa), len, 0)) {
512     sa = SA(&sin);
513     len = sizeof(sin);
514   }
515   alen = len;
516   if (len > *fakelen)
517     len = *fakelen;
518   if (len > 0)
519     memcpy(fake, sa, len);
520   *fakelen = alen;
521 }
522
523 /*----- Configuration -----------------------------------------------------*/
524
525 /* Return the process owner's home directory. */
526 static char *home(void)
527 {
528   char *p;
529   struct passwd *pw;
530
531   if (getuid() == uid &&
532       (p = getenv("HOME")) != 0)
533     return (p);
534   else if ((pw = getpwuid(uid)) != 0)
535     return (pw->pw_dir);
536   else
537     return "/notexist";
538 }
539
540 /* Return a good temporary directory to use. */
541 static char *tmpdir(void)
542 {
543   char *p;
544
545   if ((p = getenv("TMPDIR")) != 0) return (p);
546   else if ((p = getenv("TMP")) != 0) return (p);
547   else return ("/tmp");
548 }
549
550 /* Return the user's name, or at least something distinctive. */
551 static char *user(void)
552 {
553   static char buf[16];
554   char *p;
555   struct passwd *pw;
556
557   if ((p = getenv("USER")) != 0) return (p);
558   else if ((p = getenv("LOGNAME")) != 0) return (p);
559   else if ((pw = getpwuid(uid)) != 0) return (pw->pw_name);
560   else {
561     snprintf(buf, sizeof(buf), "uid-%lu", (unsigned long)uid);
562     return (buf);
563   }
564 }
565
566 /* Skip P over space characters. */
567 #define SKIPSPC do { while (*p && isspace(UC(*p))) p++; } while (0)
568
569 /* Set Q to point to the next word following P, null-terminate it, and step P
570  * past it. */
571 #define NEXTWORD(q) do {                                                \
572   SKIPSPC;                                                              \
573   q = p;                                                                \
574   while (*p && !isspace(UC(*p))) p++;                                   \
575   if (*p) *p++ = 0;                                                     \
576 } while (0)
577
578 /* Set Q to point to the next dotted-quad address, store the ending delimiter
579  * in DEL, null-terminate it, and step P past it. */
580 #define NEXTADDR(q, del) do {                                           \
581   SKIPSPC;                                                              \
582   q = p;                                                                \
583   while (*p && (*p == '.' || isdigit(UC(*p)))) p++;                     \
584   del = *p;                                                             \
585   if (*p) *p++ = 0;                                                     \
586 } while (0)
587
588 /* Set Q to point to the next decimal number, store the ending delimiter in
589  * DEL, null-terminate it, and step P past it. */
590 #define NEXTNUMBER(q, del) do {                                         \
591   SKIPSPC;                                                              \
592   q = p;                                                                \
593   while (*p && isdigit(UC(*p))) p++;                                    \
594   del = *p;                                                             \
595   if (*p) *p++ = 0;                                                     \
596 } while (0)
597
598 /* Push the character DEL back so we scan it again, unless it's zero
599  * (end-of-file). */
600 #define RESCAN(del) do { if (del) *--p = del; } while (0)
601
602 /* Evaluate true if P is pointing to the word KW (and not some longer string
603  * of which KW is a prefix). */
604
605 #define KWMATCHP(kw) (strncmp(p, kw, sizeof(kw) - 1) == 0 &&            \
606                       !isalnum(UC(p[sizeof(kw) - 1])) &&                \
607                       (p += sizeof(kw) - 1))
608
609 /* Parse a port list, starting at *PP.  Port lists have the form
610  * [:LOW[-HIGH]]: if omitted, all ports are included; if HIGH is omitted,
611  * it's as if HIGH = LOW.  Store LOW in *MIN, HIGH in *MAX and set *PP to the
612  * rest of the string.
613  */
614 static void parse_ports(char **pp, unsigned short *min, unsigned short *max)
615 {
616   char *p = *pp, *q;
617   int del;
618
619   SKIPSPC;
620   if (*p != ':')
621     { *min = 0; *max = 0xffff; }
622   else {
623     p++;
624     NEXTNUMBER(q, del); *min = strtoul(q, 0, 0); RESCAN(del);
625     SKIPSPC;
626     if (*p == '-')
627       { p++; NEXTNUMBER(q, del); *max = strtoul(q, 0, 0); RESCAN(del); }
628     else
629       *max = *min;
630   }
631   *pp = p;
632 }
633
634 /* Make a new ACL node.  ACT is the verdict; MINADDR and MAXADDR are the
635  * ranges on IP addresses; MINPORT and MAXPORT are the ranges on port
636  * numbers; TAIL is the list tail to attach the new node to.
637  */
638 #define ACLNODE(tail_, act_,                                            \
639                 minaddr_, maxaddr_, minport_, maxport_) do {            \
640   aclnode *a_;                                                          \
641   NEW(a_);                                                              \
642   a_->act = act_;                                                       \
643   a_->minaddr = minaddr_; a_->maxaddr = maxaddr_;                       \
644   a_->minport = minport_; a_->maxport = maxport_;                       \
645   *tail_ = a_; tail_ = &a_->next;                                       \
646 } while (0)
647
648 /* Parse an ACL line.  *PP points to the end of the line; *TAIL points to
649  * the list tail (i.e., the final link in the list).  An ACL entry has the
650  * form +|- [any | local | ADDR | ADDR - ADDR | ADDR/ADDR | ADDR/INT] PORTS
651  * where PORTS is parsed by parse_ports above; an ACL line consists of a
652  * comma-separated sequence of entries..
653  */
654 static void parse_acl_line(char **pp, aclnode ***tail)
655 {
656   struct in_addr addr;
657   unsigned long minaddr, maxaddr, mask;
658   unsigned short minport, maxport;
659   int i, n;
660   int act;
661   int del;
662   char *p = *pp;
663   char *q;
664
665   for (;;) {
666     SKIPSPC;
667     if (*p == '+') act = ALLOW;
668     else if (*p == '-') act = DENY;
669     else goto bad;
670
671     p++;
672     SKIPSPC;
673     if (KWMATCHP("any")) {
674       minaddr = 0;
675       maxaddr = 0xffffffff;
676       goto justone;
677     } else if (KWMATCHP("local")) {
678       parse_ports(&p, &minport, &maxport);
679       ACLNODE(*tail, act, 0, 0, minport, maxport);
680       ACLNODE(*tail, act, 0xffffffff, 0xffffffff, minport, maxport);
681       for (i = 0; i < n_local_ipaddrs; i++) {
682         minaddr = ntohl(local_ipaddrs[i].s_addr);
683         ACLNODE(*tail, act, minaddr, minaddr, minport, maxport);
684       }
685     } else {
686       if (*p == ':') {
687         minaddr = 0;
688         maxaddr = 0xffffffff;
689       } else {
690         NEXTADDR(q, del);
691         if (inet_pton(AF_INET, q, &addr) <= 0) goto bad;
692         minaddr = ntohl(addr.s_addr);
693         RESCAN(del);
694         SKIPSPC;
695         if (*p == '-') {
696           p++;
697           NEXTADDR(q, del);
698           if (inet_pton(AF_INET, q, &addr) <= 0) goto bad;
699           RESCAN(del);
700           maxaddr = ntohl(addr.s_addr);
701         } else if (*p == '/') {
702           p++;
703           NEXTADDR(q, del);
704           if (strchr(q, '.')) {
705             if (inet_pton(AF_INET, q, &addr) <= 0) goto bad;
706             mask = ntohl(addr.s_addr);
707           } else {
708             n = strtoul(q, 0, 0);
709             mask = (~0ul << (32 - n)) & 0xffffffff;
710           }
711           RESCAN(del);
712           minaddr &= mask;
713           maxaddr = minaddr | (mask ^ 0xffffffff);
714         } else
715           maxaddr = minaddr;
716       }
717     justone:
718       parse_ports(&p, &minport, &maxport);
719       ACLNODE(*tail, act, minaddr, maxaddr, minport, maxport);
720     }
721     SKIPSPC;
722     if (*p != ',') break;
723     p++;
724   }
725   return;
726
727 bad:
728   D( fprintf(stderr, "noip: bad acl spec (ignored)\n"); )
729   return;
730 }
731
732 /* Parse the autoports configuration directive.  Syntax is MIN - MAX. */
733 static void parse_autoports(char **pp)
734 {
735   char *p = *pp, *q;
736   unsigned x, y;
737   int del;
738
739   SKIPSPC;
740   NEXTNUMBER(q, del); x = strtoul(q, 0, 0); RESCAN(del);
741   SKIPSPC;
742   if (*p != '-') goto bad; p++;
743   NEXTNUMBER(q, del); y = strtoul(q, 0, 0); RESCAN(del);
744   minautoport = x; maxautoport = y;
745   return;
746
747 bad:
748   D( fprintf(stderr, "bad port range (ignored)\n"); )
749   return;
750 }
751
752 /* Parse an ACL from an environment variable VAR, attaching it to the list
753  * TAIL. */
754 static void parse_acl_env(const char *var, aclnode ***tail)
755 {
756   char *p, *q;
757
758   if ((p = getenv(var)) != 0) {
759     p = q = xstrdup(p);
760     parse_acl_line(&q, tail);
761     free(p);
762   }
763 }
764
765 /* Read the configuration from the config file and environment. */
766 static void readconfig(void)
767 {
768   FILE *fp;
769   char buf[1024];
770   size_t n;
771   char *p, *q, *cmd;
772
773   parse_acl_env("NOIP_REALBIND_BEFORE", &bind_tail);
774   parse_acl_env("NOIP_REALCONNECT_BEFORE", &connect_tail);
775   if ((p = getenv("NOIP_AUTOPORTS")) != 0) {
776     p = q = xstrdup(p);
777     parse_autoports(&q);
778     free(p);
779   }
780   if ((p = getenv("NOIP_CONFIG")) == 0)
781     snprintf(p = buf, sizeof(buf), "%s/.noip", home());
782   D( fprintf(stderr, "noip: config file: %s\n", p); )
783
784   if ((fp = fopen(p, "r")) == 0) {
785     D( fprintf(stderr, "noip: couldn't read config: %s\n",
786                strerror(errno)); )
787     goto done;
788   }
789   while (fgets(buf, sizeof(buf), fp)) {
790     n = strlen(buf);
791     p = buf;
792
793     SKIPSPC;
794     if (!*p || *p == '#') continue;
795     while (n && isspace(UC(buf[n - 1]))) n--;
796     buf[n] = 0;
797     NEXTWORD(cmd);
798     SKIPSPC;
799
800     if (strcmp(cmd, "socketdir") == 0)
801       sockdir = xstrdup(p);
802     else if (strcmp(cmd, "realbind") == 0)
803       parse_acl_line(&p, &bind_tail);
804     else if (strcmp(cmd, "realconnect") == 0)
805       parse_acl_line(&p, &connect_tail);
806     else if (strcmp(cmd, "autoports") == 0)
807       parse_autoports(&p);
808     else if (strcmp(cmd, "debug") == 0)
809       debug = *p ? atoi(p) : 1;
810     else
811       D( fprintf(stderr, "noip: bad config command %s\n", cmd); )
812   }
813   fclose(fp);
814
815 done:
816   parse_acl_env("NOIP_REALBIND", &bind_tail);
817   parse_acl_env("NOIP_REALCONNECT", &connect_tail);
818   parse_acl_env("NOIP_REALBIND_AFTER", &bind_tail);
819   parse_acl_env("NOIP_REALCONNECT_AFTER", &connect_tail);
820   *bind_tail = 0;
821   *connect_tail = 0;
822   if (!sockdir) sockdir = getenv("NOIP_SOCKETDIR");
823   if (!sockdir) {
824     snprintf(buf, sizeof(buf), "%s/noip-%s", tmpdir(), user());
825     sockdir = xstrdup(buf);
826   }
827   D( fprintf(stderr, "noip: socketdir: %s\n", sockdir);
828      fprintf(stderr, "noip: autoports: %u-%u\n",
829              minautoport, maxautoport);
830      fprintf(stderr, "noip: realbind acl:\n");
831      dump_acl(bind_real);
832      fprintf(stderr, "noip: realconnect acl:\n");
833      dump_acl(connect_real); )
834 }
835
836 /*----- Overridden system calls -------------------------------------------*/
837
838 int socket(int pf, int ty, int proto)
839 {
840   switch (pf) {
841     case PF_INET:
842       pf = PF_UNIX;
843       proto = 0;
844     case PF_UNIX:
845       return real_socket(pf, ty, proto);
846     default:
847       errno = EAFNOSUPPORT;
848       return -1;
849   }
850 }
851
852 int socketpair(int pf, int ty, int proto, int *sk)
853 {
854   if (pf == PF_INET) {
855     pf = PF_UNIX;
856     proto = 0;
857   }
858   return (real_socketpair(pf, ty, proto, sk));
859 }
860
861 int bind(int sk, const struct sockaddr *sa, socklen_t len)
862 {
863   struct sockaddr_un sun;
864
865   if (sa->sa_family == AF_INET) {
866     PRESERVING_ERRNO({
867       if (acl_allows_p(bind_real, SIN(sa))) {
868         if (fixup_real_ip_socket(sk))
869           return (-1);
870       } else {
871         encode_inet_addr(&sun, SIN(sa), WANT_FRESH);
872         sa = SA(&sun);
873         len = SUN_LEN(&sun);
874       }
875     });
876   }
877   return real_bind(sk, sa, len);
878 }
879
880 int connect(int sk, const struct sockaddr *sa, socklen_t len)
881 {
882   struct sockaddr_un sun;
883   int fixup_p = 0;
884   int rc;
885
886   switch (sa->sa_family) {
887     case AF_INET:
888       PRESERVING_ERRNO({
889         do_implicit_bind(sk, &sa, &len, &sun);
890         fixup_p = 1;
891       });
892       rc = real_connect(sk, sa, len);
893       if (rc < 0) {
894         switch (errno) {
895           case ENOENT:  errno = ECONNREFUSED;   break;
896         }
897       }
898       break;
899     default:
900       rc = real_connect(sk, sa, len);
901       break;
902   }
903   return rc;
904 }
905
906 ssize_t sendto(int sk, const void *buf, size_t len, int flags,
907                const struct sockaddr *to, socklen_t tolen)
908 {
909   struct sockaddr_un sun;
910
911   if (to && to->sa_family == AF_INET) {
912     PRESERVING_ERRNO({
913       do_implicit_bind(sk, &to, &tolen, &sun);
914     });
915   }
916   return real_sendto(sk, buf, len, flags, to, tolen);
917 }
918
919 ssize_t recvfrom(int sk, void *buf, size_t len, int flags,
920                  struct sockaddr *from, socklen_t *fromlen)
921 {
922   char sabuf[1024];
923   socklen_t mylen = sizeof(sabuf);
924   ssize_t n;
925
926   if (!from)
927     return real_recvfrom(sk, buf, len, flags, 0, 0);
928   PRESERVING_ERRNO({
929     n = real_recvfrom(sk, buf, len, flags, SA(sabuf), &mylen);
930     if (n < 0)
931       return (-1);
932     return_fake_name(SA(sabuf), mylen, from, fromlen);
933   });
934   return (n);
935 }
936
937 ssize_t sendmsg(int sk, const struct msghdr *msg, int flags)
938 {
939   struct sockaddr_un sun;
940   const struct sockaddr *sa;
941   struct msghdr mymsg;
942
943   if (msg->msg_name && SA(msg->msg_name)->sa_family == AF_INET) {
944     PRESERVING_ERRNO({
945       sa = SA(msg->msg_name);
946       mymsg = *msg;
947       do_implicit_bind(sk, &sa, &mymsg.msg_namelen, &sun);
948       mymsg.msg_name = SA(sa);
949       msg = &mymsg;
950     });
951   }
952   return real_sendmsg(sk, msg, flags);
953 }
954
955 ssize_t recvmsg(int sk, struct msghdr *msg, int flags)
956 {
957   char sabuf[1024];
958   struct sockaddr *sa;
959   socklen_t len;
960   ssize_t n;
961
962   if (!msg->msg_name)
963     return real_recvmsg(sk, msg, flags);
964   PRESERVING_ERRNO({
965     sa = SA(msg->msg_name);
966     len = msg->msg_namelen;
967     msg->msg_name = sabuf;
968     msg->msg_namelen = sizeof(sabuf);
969     n = real_recvmsg(sk, msg, flags);
970     if (n < 0)
971       return (-1);
972     return_fake_name(SA(sabuf), msg->msg_namelen, sa, &len);
973     msg->msg_name = sa;
974     msg->msg_namelen = len;
975   });
976   return (n);
977 }
978
979 int accept(int sk, struct sockaddr *sa, socklen_t *len)
980 {
981   char sabuf[1024];
982   socklen_t mylen = sizeof(sabuf);
983   int nsk = real_accept(sk, SA(sabuf), &mylen);
984
985   if (nsk < 0)
986     return (-1);
987   return_fake_name(SA(sabuf), mylen, sa, len);
988   return (nsk);
989 }
990
991 int getsockname(int sk, struct sockaddr *sa, socklen_t *len)
992 {
993   PRESERVING_ERRNO({
994     char sabuf[1024];
995     socklen_t mylen = sizeof(sabuf);
996     if (real_getsockname(sk, SA(sabuf), &mylen))
997       return (-1);
998     return_fake_name(SA(sabuf), mylen, sa, len);
999   });
1000   return (0);
1001 }
1002
1003 int getpeername(int sk, struct sockaddr *sa, socklen_t *len)
1004 {
1005   PRESERVING_ERRNO({
1006     char sabuf[1024];
1007     socklen_t mylen = sizeof(sabuf);
1008     if (real_getpeername(sk, SA(sabuf), &mylen))
1009       return (-1);
1010     return_fake_name(SA(sabuf), mylen, sa, len);
1011   });
1012   return (0);
1013 }
1014
1015 int getsockopt(int sk, int lev, int opt, void *p, socklen_t *len)
1016 {
1017   switch (lev) {
1018     case SOL_IP:
1019     case SOL_TCP:
1020     case SOL_UDP:
1021       if (*len > 0)
1022         memset(p, 0, *len);
1023       return (0);
1024   }
1025   return real_getsockopt(sk, lev, opt, p, len);
1026 }
1027
1028 int setsockopt(int sk, int lev, int opt, const void *p, socklen_t len)
1029 {
1030   switch (lev) {
1031     case SOL_IP:
1032     case SOL_TCP:
1033     case SOL_UDP:
1034       return (0);
1035   }
1036   switch (opt) {
1037     case SO_BINDTODEVICE:
1038     case SO_ATTACH_FILTER:
1039     case SO_DETACH_FILTER:
1040       return (0);
1041   }
1042   return real_setsockopt(sk, lev, opt, p, len);
1043 }
1044
1045 /*----- Initialization ----------------------------------------------------*/
1046
1047 /* Clean up the socket directory, deleting stale sockets. */
1048 static void cleanup_sockdir(void)
1049 {
1050   DIR *dir;
1051   struct dirent *d;
1052   struct sockaddr_in sin;
1053   struct sockaddr_un sun;
1054   struct stat st;
1055
1056   if ((dir = opendir(sockdir)) == 0)
1057     return;
1058   sun.sun_family = AF_UNIX;
1059   while ((d = readdir(dir)) != 0) {
1060     if (d->d_name[0] == '.') continue;
1061     snprintf(sun.sun_path, sizeof(sun.sun_path),
1062              "%s/%s", sockdir, d->d_name);
1063     if (decode_inet_addr(&sin, &sun, SUN_LEN(&sun), 0) ||
1064         stat(sun.sun_path, &st) ||
1065         !S_ISSOCK(st.st_mode)) {
1066       D( fprintf(stderr, "noip: ignoring unknown socketdir entry `%s'\n",
1067                  sun.sun_path); )
1068       continue;
1069     }
1070     if (unix_socket_status(&sun, 0) == STALE) {
1071       D( fprintf(stderr, "noip: clearing away stale socket %s\n",
1072                  d->d_name); )
1073       unlink(sun.sun_path);
1074     }
1075   }
1076   closedir(dir);
1077 }
1078
1079 /* Find the addresses attached to local network interfaces, and remember them
1080  * in a table.
1081  */
1082 static void get_local_ipaddrs(void)
1083 {
1084   struct if_nameindex *ifn;
1085   struct ifreq ifr;
1086   int sk;
1087   int i;
1088
1089   ifn = if_nameindex();
1090   if ((sk = real_socket(PF_INET, SOCK_STREAM, 00)) < 0)
1091     return;
1092   for (i = n_local_ipaddrs = 0;
1093        n_local_ipaddrs < MAX_LOCAL_IPADDRS &&
1094          ifn[i].if_name && *ifn[i].if_name;
1095        i++) {
1096     strcpy(ifr.ifr_name, ifn[i].if_name);
1097     if (ioctl(sk, SIOCGIFADDR, &ifr) || ifr.ifr_addr.sa_family != AF_INET)
1098       continue;
1099     local_ipaddrs[n_local_ipaddrs++] =
1100       SIN(&ifr.ifr_addr)->sin_addr;
1101     D( fprintf(stderr, "noip: local addr %s = %s\n", ifn[i].if_name,
1102                inet_ntoa(local_ipaddrs[n_local_ipaddrs - 1])); )
1103   }
1104   close(sk);
1105 }
1106
1107 /* Print the given message to standard error.  Avoids stdio. */
1108 static void printerr(const char *p)
1109   { int hunoz; hunoz = write(STDERR_FILENO, p, strlen(p)); }
1110
1111 /* Create the socket directory, being careful about permissions. */
1112 static void create_sockdir(void)
1113 {
1114   struct stat st;
1115
1116   if (stat(sockdir, &st)) {
1117     if (errno == ENOENT) {
1118       if (mkdir(sockdir, 0700)) {
1119         perror("noip: creating socketdir");
1120         exit(127);
1121       }
1122       if (!stat(sockdir, &st))
1123         goto check;
1124     }
1125     perror("noip: checking socketdir");
1126     exit(127);
1127   }
1128 check:
1129   if (!S_ISDIR(st.st_mode)) {
1130     printerr("noip: bad socketdir: not a directory\n");
1131     exit(127);
1132   }
1133   if (st.st_uid != uid) {
1134     printerr("noip: bad socketdir: not owner\n");
1135     exit(127);
1136   }
1137   if (st.st_mode & 077) {
1138     printerr("noip: bad socketdir: not private\n");
1139     exit(127);
1140   }
1141 }
1142
1143 /* Initialization function. */
1144 static void setup(void) __attribute__((constructor));
1145 static void setup(void)
1146 {
1147   PRESERVING_ERRNO({
1148     char *p;
1149
1150     import();
1151     uid = geteuid();
1152     if ((p = getenv("NOIP_DEBUG")) && atoi(p))
1153       debug = 1;
1154     get_local_ipaddrs();
1155     readconfig();
1156     create_sockdir();
1157     cleanup_sockdir();
1158   });
1159 }
1160
1161 /*----- That's all, folks -------------------------------------------------*/