2 * userv service (or standalone program)
3 * for per-user IP subranges.
5 * This is invoked as root, directly from userv.
6 * Its arguments are supposed to be, in order:
8 * Specifies address ranges and gids which own them.
9 * -- Indicates that the remaining arguments are user-supplied
10 * and therefore untrusted.
11 * <local-addr>,<peer-addr>,<mtu>,<proto>
12 * As for slattach. Supported protocols are slip, cslip, and
13 * adaptive. Alternatively, set to `debug' to print debugging
14 * info. <local-addr> is address of the interface on chiark;
15 * <peer-addr> is the address of the point-to-point peer.
16 * <prefix>/<mask>,<prefix>/<mask>,...
17 * List of additional routes to add for this interface.
18 * May be the empty argument, or `-' if this is problematic.
21 * <gid>,<prefix>/<len>[,<junk>]
22 * indicating that that gid may allocate addresses in
23 * the relevant subspace (<junk> is ignored)
26 * or /<config-file-name> or ./<config-file-name> or ../<config-file-name>
27 * which refers to a file which contains lines which
30 * which means that anything is permitted
32 * Should be run from userv with no-disconnect-hup.
46 #include <sys/types.h>
54 static const unsigned long gidmaxval= (unsigned long)((gid_t)-2);
55 static const char *const protos_ok[]= { "slip", "cslip", "adaptive", 0 };
56 static const int signals[]= { SIGHUP, SIGINT, SIGTERM, 0 };
58 static const char *configstr, *proto;
59 static unsigned long localaddr, peeraddr, mtu;
60 static int localallow, peerallow, allallow;
62 static struct exroute {
63 unsigned long prefix, mask;
65 char prefixtxt[ATXTLEN], masktxt[ATXTLEN];
66 } exroutes[MAXEXROUTES];
68 static char localtxt[ATXTLEN];
69 static char peertxt[ATXTLEN];
71 static struct pplace {
72 struct pplace *parent;
78 static int slpipe[2], ptmaster, undoslattach;
79 static const char *ifname;
80 static const char *ptyname;
85 struct { pid_t sl, cout, cin, task; } byname;
86 pid_t bynumber[NPIDS];
88 sigset_t emptyset, fullset;
91 static int cleantask(void) {
97 perror("userv-ipif: fork for undo slattach failed - cannot clean up properly");
101 static void terminate(int estatus) {
105 for (i=0; i<NPIDS; i++)
106 if (pids.bynumber[i]) kill(pids.bynumber[i], SIGTERM);
110 execlp("slattach", "slattach", "-p", "tty", ptyname, (char*)0);
111 perror("userv-ipif: exec slattach for undo slattach failed");
114 if (ifname && cleantask()) {
115 execlp("ifconfig", "ifconfig", ifname, "down", (char*)0);
116 perror("userv-ipif: exec ifconfig for undo ifconfig failed");
122 pid= waitpid(-1,&status,0);
123 if (pid == (pid_t)-1) break;
129 static void fatal(const char *fmt, ...)
130 __attribute__((format(printf,1,2)));
131 static void fatal(const char *fmt, ...) {
135 fputs("userv-ipif service: fatal error: ",stderr);
136 vfprintf(stderr, fmt, al);
141 static void sysfatal(const char *fmt, ...)
142 __attribute__((format(printf,1,2)));
143 static void sysfatal(const char *fmt, ...) {
150 fputs("userv-ipif service: fatal system error: ",stderr);
151 vfprintf(stderr, fmt, al);
152 fprintf(stderr,": %s\n", strerror(e));
157 static void badusage(const char *fmt, ...)
158 __attribute__((format(printf,1,2)));
159 static void badusage(const char *fmt, ...) {
165 "userv-ipif service: %s:%d: ",
166 cpplace->filename, cpplace->lineno);
168 fputs("userv-ipif service: invalid usage: ",stderr);
171 vfprintf(stderr, fmt, al);
175 for (cpp=cpplace->parent; cpp; cpp=cpp->parent) {
177 "userv-ipif service: %s:%d: ... in file included from here\n",
178 cpp->filename, cpp->lineno);
184 static char *ip2txt(unsigned long addr, char *buf) {
185 sprintf(buf, "%lu.%lu.%lu.%lu",
193 static unsigned long eat_number(const char **argp, const char *what,
194 unsigned long min, unsigned long max,
195 const char *endchars, int *endchar_r) {
196 /* If !endchars then the endchar must be a nul, otherwise it may be
197 * a nul (resulting in *argp set to 0) or something else (*argp set
198 * to point to after delim, *endchar_r set to delim).
199 * *endchar_r may be 0.
205 if (!*argp) { badusage("missing number %s",what); }
206 rv= strtoul(*argp,&ep,0);
207 if ((endchar= *ep)) {
208 if (!endchars) badusage("junk after number %s",what);
209 if (!strchr(endchars,endchar))
210 badusage("invalid character or delimiter `%c' in or after number, %s:"
211 " expected %s (or none?)", endchar,what,endchars);
216 if (endchar_r) *endchar_r= endchar;
217 if (rv < min || rv > max) badusage("number %s value %lu out of range %lu..%lu",
222 static void addrnet_mustdiffer(const char *w1, unsigned long p1, unsigned long m1,
223 const char *w2, unsigned long p2, unsigned long m2) {
227 if ((p1 & mask) != (p2 & mask)) return;
228 badusage("%s %08lx/%08lx overlaps/clashes with %s %08lx/%08lx",
232 static unsigned long eat_addr(const char **argp, const char *what,
233 const char *endchars, int *endchar_r) {
242 sprintf(whatbuf,"%s byte #%d",what,i);
243 rv |= eat_number(argp,whatbuf, 0,255, i<3 ? "." : endchars, endchar_r);
249 static void eat_prefixmask(const char **argp, const char *what,
250 const char *endchars, int *endchar_r,
251 unsigned long *prefix_r, unsigned long *mask_r, int *len_r) {
252 /* mask_r and len_r may be 0 */
255 unsigned long prefix, mask;
257 prefix= eat_addr(argp,what, "/",0);
258 sprintf(whatbuf,"%s length",what);
259 len= eat_number(argp,whatbuf, 0,32, endchars,endchar_r);
261 mask= (~0UL << (32-len));
262 if (prefix & ~mask) badusage("%s prefix %08lx not fully contained in mask %08lx",
265 if (mask_r) *mask_r= mask;
266 if (len_r) *len_r= len;
269 static int addrnet_isin(unsigned long prefix, unsigned long mask,
270 unsigned long mprefix, unsigned long mmask) {
271 return !(~mask & mmask) && (prefix & mmask) == mprefix;
275 static void permit(unsigned long pprefix, unsigned long pmask) {
278 assert(!(pprefix & ~pmask));
281 if (!proto) fputs("permits",stdout);
282 if (addrnet_isin(localaddr,~0UL, pprefix,pmask)) {
283 if (!proto) fputs(" local-addr",stdout);
286 if (addrnet_isin(peeraddr,~0UL, pprefix,pmask)) {
287 if (!proto) fputs(" peer-addr",stdout);
290 for (i=0; i<nexroutes; i++) {
291 if (addrnet_isin(exroutes[i].prefix,exroutes[i].mask, pprefix,pmask)) {
292 if (!proto) printf(" route#%d",i);
293 any= exroutes[i].allow= 1;
297 if (!any) fputs(" nothing!",stderr);
302 static void pconfig(const char *configstr, int truncated);
304 static void pfile(const char *filename) {
308 struct pplace npp, *cpp;
310 for (cpp=cpplace; cpp; cpp=cpp->parent) {
311 if (!strcmp(cpp->filename,filename))
312 badusage("recursive configuration file `%s'",filename);
315 file= fopen(filename,"r");
317 badusage("cannot open configuration file `%s': %s", filename, strerror(errno));
319 if (!proto) printf("config file `%s':\n",filename);
322 npp.filename= filename;
326 while (fgets(buf, sizeof(buf), file)) {
331 truncated= (buf[l-1] != '\n');
332 while (l>0 && isspace((unsigned char) buf[l-1])) l--;
337 while ((c= getc(file)) != EOF && c != '\n');
341 pconfig(buf,truncated);
344 badusage("failed while reading configuration file: %s", strerror(errno));
349 static void pconfig(const char *configstr, int truncated) {
350 unsigned long fgid, tgid, pprefix, pmask;
355 switch (configstr[0]) {
357 if (strcmp(configstr,"*")) badusage("`*' directive must be only thing on line");
365 if (truncated) badusage("filename too long (`%.100s...')",configstr);
370 if (!isdigit((unsigned char)configstr[0]))
371 badusage("unknown configuration directive");
373 fgid= eat_number(&configstr,"gid", 0,gidmaxval, ",",0);
374 eat_prefixmask(&configstr,"permitted-prefix", ",",0, &pprefix,&pmask,&plen);
375 if (!configstr && truncated) badusage("gid,prefix/len,... spec too long");
377 if (!proto) printf(" %5lu,%s/%d: ", fgid, ip2txt(pprefix,ptxt), plen);
379 gidlist= getenv("USERV_GID");
380 if (!gidlist) fatal("USERV_GID not set");
383 if (!proto) printf("no matching gid\n");
386 tgid= eat_number(&gidlist,"userv-gid", 0,gidmaxval, " ",0);
387 if (tgid == fgid) break;
389 permit(pprefix,pmask);
394 static void checkallow(int allow, const char *what,
395 const char *prefixtxt, const char *masktxt) {
397 fprintf(stderr,"userv-ipif service: access denied for %s, %s/%s\n",
398 what, prefixtxt, masktxt);
402 static void parseargs(int argc, const char *const *argv) {
403 unsigned long routeaddr, routemask;
405 const char *const *cprotop;
407 char erwhatbuf[100], erwhatbuf2[100];
409 if (argc < NARGS+1) { badusage("too few arguments"); }
410 if (argc > NARGS+1) { badusage("too many arguments"); }
415 if (strcmp(carg,"--")) badusage("separator argument `--' not found, got `%s'",carg);
418 localaddr= eat_addr(&carg,"local-addr", ",",0);
419 peeraddr= eat_addr(&carg,"peer-addr", ",",0);
420 mtu= eat_number(&carg,"mtu", 576,65536, ",",0);
421 localallow= peerallow= 0;
423 if (!strcmp(carg,"debug")) {
426 for (cprotop= protos_ok;
427 (proto= *cprotop) && strcmp(proto,carg);
429 if (!proto) fatal("invalid protocol");
432 addrnet_mustdiffer("local-addr",localaddr,~0UL, "peer-addr",peeraddr,~0UL);
435 if (strcmp(carg,"-")) {
439 if (nexroutes == MAXEXROUTES)
440 fatal("too many extra routes (only %d allowed)",MAXEXROUTES);
441 sprintf(erwhatbuf,"route#%d",nexroutes);
443 eat_prefixmask(&carg,erwhatbuf, ",",0, &routeaddr,&routemask,0);
444 if (routemask == ~0UL) {
445 addrnet_mustdiffer(erwhatbuf,routeaddr,routemask, "local-addr",localaddr,~0UL);
446 addrnet_mustdiffer(erwhatbuf,routeaddr,routemask, "peer-addr",peeraddr,~0UL);
448 for (i=0; i<nexroutes; i++) {
449 sprintf(erwhatbuf2,"route#%d",i);
450 addrnet_mustdiffer(erwhatbuf,routeaddr,routemask,
451 erwhatbuf2,exroutes[i].prefix,exroutes[i].mask);
453 exroutes[nexroutes].prefix= routeaddr;
454 exroutes[nexroutes].mask= routemask;
455 exroutes[nexroutes].allow= 0;
456 ip2txt(routeaddr,exroutes[nexroutes].prefixtxt);
457 ip2txt(routemask,exroutes[nexroutes].masktxt);
461 ip2txt(localaddr,localtxt);
462 ip2txt(peeraddr,peertxt);
465 static void checkpermit(void) {
470 checkallow(localallow,"local-addr", localtxt,"32");
471 checkallow(peerallow,"peer-addr", peertxt,"32");
472 for (i=0; i<nexroutes; i++) {
473 sprintf(erwhatbuf, "route#%d", i);
474 checkallow(exroutes[i].allow, erwhatbuf, exroutes[i].prefixtxt, exroutes[i].masktxt);
476 if (!allallow) fatal("access denied");
479 static void dumpdebug(void) __attribute__((noreturn));
480 static void dumpdebug(void) {
484 printf("protocol: debug\n"
485 "local: %08lx == %s\n"
486 "peer: %08lx == %s\n"
493 for (i=0; i<nexroutes; i++) {
494 sprintf(erwhatbuf, "route#%d:", i);
495 printf("%-9s %08lx/%08lx == %s/%s\n",
497 exroutes[i].prefix, exroutes[i].mask,
498 exroutes[i].prefixtxt, exroutes[i].masktxt);
500 if (ferror(stdout) || fclose(stdout)) sysfatal("flush stdout");
505 static void setsigmask(const sigset_t *ss) {
508 r= sigprocmask(SIG_SETMASK, ss, 0);
509 if (r) sysfatal("[un]block signals");
512 static void setsignals(void (*handler)(int), struct sigaction *sa, int chldflags) {
516 sa->sa_handler= handler;
518 for (signalp=signals; (sig=*signalp); signalp++) {
519 r= sigaction(sig, sa, 0); if (r) sysfatal("uncatch signal");
521 sa->sa_flags= chldflags;
522 r= sigaction(SIGCHLD, sa, 0); if (r) sysfatal("uncatch children");
525 static void infork(void) {
528 memset(&pids,0,sizeof(pids));
529 sigemptyset(&sa.sa_mask);
530 setsignals(SIG_DFL,&sa,0);
531 setsigmask(&emptyset);
535 static pid_t makesubproc(void (*entry)(void)) {
538 pid= fork(); if (pid == (pid_t)-1) sysfatal("fork for subprocess");
546 static int task(void) {
550 if (pid == (pid_t)-1) sysfatal("fork for task");
551 if (!pid) { infork(); return 1; }
553 pids.byname.task= pid;
554 while (pids.byname.task) sigsuspend(&emptyset);
558 static void mdup2(int fd1, int fd2, const char *what) {
562 r= dup2(fd1,fd2); if (r==fd2) return;
563 if (r!=-1) fatal("dup2 in %s gave wrong answer %d instead of %d",what,r,fd2);
564 if (errno != EINTR) sysfatal("dup2 failed in %s",what);
568 static void sl_entry(void) {
569 mdup2(slpipe[1],1,"slattach child");
570 execlp("slattach", "slattach", "-v", "-L", "-p",proto, ptyname, (char*)0);
571 sysfatal("cannot exec slattach");
574 static void cin_entry(void) {
575 mdup2(ptmaster,1,"cat input child");
576 execlp("cat", "cat", (char*)0);
577 sysfatal("cannot exec cat input");
580 static void cout_entry(void) {
581 mdup2(ptmaster,0,"cat output child");
582 execlp("cat", "cat", (char*)0);
583 sysfatal("cannot exec cat output");
586 static void sighandler(int signum) {
589 const char *taskfail;
593 if (signum == SIGCHLD) {
595 pid= waitpid(-1,&status,WNOHANG);
596 if (!pid || pid == (pid_t)-1) return;
598 if (pid == pids.byname.task) {
602 } else if (pid == pids.byname.cin) {
605 taskfail= "input cat";
610 } else if (pid == pids.byname.cout) {
612 taskfail= "output cat";
613 } else if (pid == pids.byname.sl) {
615 taskfail= "slattach";
622 if (WIFEXITED(status)) {
624 "userv-ipif service: %s unexpectedly exited with exit status %d\n",
625 taskfail, WEXITSTATUS(status));
626 } else if (WIFSIGNALED(status)) {
628 "userv-ipif service: %s unexpectedly killed by signal %s%s\n",
629 taskfail, strsignal(WTERMSIG(status)),
630 WCOREDUMP(status) ? " (core dumped)" : "");
632 fprintf(stderr, "userv-ipif service: %s unexpectedly terminated"
633 " with unknown status code %d\n", taskfail, status);
638 "userv-ipif service: received signal %d, terminating\n",
645 static void startup(void) {
649 sigfillset(&fullset);
650 sigemptyset(&emptyset);
652 ptmaster= getpt(); if (ptmaster==-1) sysfatal("allocate pty master");
653 r= grantpt(ptmaster); if (r) sysfatal("grab/grant pty slave");
654 ptyname= ptsname(ptmaster); if (!ptyname) sysfatal("get pty slave name");
655 r= chmod(ptyname,0600); if (r) sysfatal("chmod pty slave");
656 r= unlockpt(ptmaster); if (r) sysfatal("unlock pty");
658 sigfillset(&sa.sa_mask);
659 setsignals(sighandler,&sa,SA_NOCLDSTOP);
660 setsigmask(&fullset);
663 static void startslattach(void) {
664 static char ifnbuf[200];
669 r= pipe(slpipe); if (r) sysfatal("create pipe");
670 piper= fdopen(slpipe[0],"r"); if (!piper) sysfatal("fdopen pipe");
673 pids.byname.sl= makesubproc(sl_entry);
676 setsigmask(&emptyset);
677 if (!fgets(ifnbuf,sizeof(ifnbuf),piper)) {
678 if (ferror(piper)) sysfatal("cannot read ifname from slattach");
679 else fatal("cannot read ifname from slattach");
681 setsigmask(&fullset);
683 if (l<=0 || ifnbuf[l-1] != '\n') fatal("slattach gave strange output `%s'",ifnbuf);
685 for (k=l; k>0 && ifnbuf[k-1]!=' '; k--);
689 static void netconfigure(void) {
694 sprintf(mtutxt,"%lu",mtu);
696 execlp("ifconfig", "ifconfig", ifname, localtxt,
697 "netmask","255.255.255.255", "-broadcast", "pointopoint",peertxt,
698 "mtu",mtutxt, "up", (char*)0);
699 sysfatal("cannot exec ifconfig");
702 for (i=0; i<nexroutes; i++) {
704 execlp("route","route", "add", "-net",exroutes[i].prefixtxt,
705 "netmask",exroutes[i].masktxt,
706 "gw",peertxt, "dev",ifname, (char*)0);
707 sysfatal("cannot exec route (for route)");
712 static void copydata(void) __attribute__((noreturn));
713 static void copydata(void) {
716 pids.byname.cin= makesubproc(cin_entry);
718 r= write(1, "\300", 1); if (r==1) break;
719 assert(r==-1); if (errno != EINTR) sysfatal("send initial delim to confirm");
721 pids.byname.cout= makesubproc(cout_entry);
723 for (;;) sigsuspend(&emptyset);
726 int main(int argc, const char *const *argv) {
727 parseargs(argc,argv);
728 pconfig(configstr,0);
730 if (!proto) dumpdebug();