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 the local
15 * system; <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)
24 * if `=' is specified then it's only allowed for the local
28 * or /<config-file-name> or ./<config-file-name> or ../<config-file-name>
29 * which refers to a file which contains lines which
32 * which means that anything is permitted
34 * Should be run from userv with no-disconnect-hup.
37 * Copyright (C) 1999 Ian Jackson
39 * This is free software; you can redistribute it and/or modify it
40 * under the terms of the GNU General Public License as published by
41 * the Free Software Foundation; either version 2 of the License, or
42 * (at your option) any later version.
44 * This program is distributed in the hope that it will be useful, but
45 * WITHOUT ANY WARRANTY; without even the implied warranty of
46 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
47 * General Public License for more details.
49 * You should have received a copy of the GNU General Public License
50 * along with userv-utils; if not, write to the Free Software
51 * Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
67 #include <sys/types.h>
75 static const unsigned long gidmaxval= (unsigned long)((gid_t)-2);
76 static const char *const protos_ok[]= { "slip", "cslip", "adaptive", 0 };
77 static const int signals[]= { SIGHUP, SIGINT, SIGTERM, 0 };
79 static const char *configstr, *proto;
80 static unsigned long localaddr, peeraddr, mtu;
81 static int localallow, peerallow, allallow;
83 static struct exroute {
84 unsigned long prefix, mask;
86 char prefixtxt[ATXTLEN], masktxt[ATXTLEN];
87 } exroutes[MAXEXROUTES];
89 static char localtxt[ATXTLEN];
90 static char peertxt[ATXTLEN];
92 static struct pplace {
93 struct pplace *parent;
99 static int slpipe[2], ptmaster, undoslattach;
100 static const char *ifname;
101 static const char *ptyname;
106 struct { pid_t sl, cout, cin, task; } byname;
107 pid_t bynumber[NPIDS];
109 sigset_t emptyset, fullset;
112 static int cleantask(void) {
117 if (pid == (pid_t)-1)
118 perror("userv-ipif: fork for undo slattach failed - cannot clean up properly");
122 static void terminate(int estatus) {
126 for (i=0; i<NPIDS; i++)
127 if (pids.bynumber[i]) kill(pids.bynumber[i], SIGTERM);
131 execlp("slattach", "slattach", "-p", "tty", ptyname, (char*)0);
132 perror("userv-ipif: exec slattach for undo slattach failed");
135 if (ifname && cleantask()) {
136 execlp("ifconfig", "ifconfig", ifname, "down", (char*)0);
137 perror("userv-ipif: exec ifconfig for undo ifconfig failed");
143 pid= waitpid(-1,&status,0);
144 if (pid == (pid_t)-1) break;
150 static void fatal(const char *fmt, ...)
151 __attribute__((format(printf,1,2)));
152 static void fatal(const char *fmt, ...) {
156 fputs("userv-ipif service: fatal error: ",stderr);
157 vfprintf(stderr, fmt, al);
162 static void sysfatal(const char *fmt, ...)
163 __attribute__((format(printf,1,2)));
164 static void sysfatal(const char *fmt, ...) {
171 fputs("userv-ipif service: fatal system error: ",stderr);
172 vfprintf(stderr, fmt, al);
173 fprintf(stderr,": %s\n", strerror(e));
178 static void badusage(const char *fmt, ...)
179 __attribute__((format(printf,1,2)));
180 static void badusage(const char *fmt, ...) {
186 "userv-ipif service: %s:%d: ",
187 cpplace->filename, cpplace->lineno);
189 fputs("userv-ipif service: invalid usage: ",stderr);
192 vfprintf(stderr, fmt, al);
196 for (cpp=cpplace->parent; cpp; cpp=cpp->parent) {
198 "userv-ipif service: %s:%d: ... in file included from here\n",
199 cpp->filename, cpp->lineno);
205 static char *ip2txt(unsigned long addr, char *buf) {
206 sprintf(buf, "%lu.%lu.%lu.%lu",
214 static unsigned long eat_number(const char **argp, const char *what,
215 unsigned long min, unsigned long max,
216 const char *endchars, int *endchar_r) {
217 /* If !endchars then the endchar must be a nul, otherwise it may be
218 * a nul (resulting in *argp set to 0) or something else (*argp set
219 * to point to after delim, *endchar_r set to delim).
220 * *endchar_r may be 0.
226 if (!*argp) { badusage("missing number %s",what); }
227 rv= strtoul(*argp,&ep,0);
228 if ((endchar= *ep)) {
229 if (!endchars) badusage("junk after number %s",what);
230 if (!strchr(endchars,endchar))
231 badusage("invalid character or delimiter `%c' in or after number, %s:"
232 " expected %s (or none?)", endchar,what,endchars);
237 if (endchar_r) *endchar_r= endchar;
238 if (rv < min || rv > max) badusage("number %s value %lu out of range %lu..%lu",
243 static void addrnet_mustdiffer(const char *w1, unsigned long p1, unsigned long m1,
244 const char *w2, unsigned long p2, unsigned long m2) {
248 if ((p1 & mask) != (p2 & mask)) return;
249 badusage("%s %08lx/%08lx overlaps/clashes with %s %08lx/%08lx",
253 static unsigned long eat_addr(const char **argp, const char *what,
254 const char *endchars, int *endchar_r) {
263 sprintf(whatbuf,"%s byte #%d",what,i);
264 rv |= eat_number(argp,whatbuf, 0,255, i<3 ? "." : endchars, endchar_r);
270 static void eat_prefixmask(const char **argp, const char *what,
271 const char *endchars, int *endchar_r,
272 unsigned long *prefix_r, unsigned long *mask_r, int *len_r) {
273 /* mask_r and len_r may be 0 */
276 unsigned long prefix, mask;
278 prefix= eat_addr(argp,what, "/",0);
279 sprintf(whatbuf,"%s length",what);
280 len= eat_number(argp,whatbuf, 0,32, endchars,endchar_r);
282 mask= (~0UL << (32-len));
283 if (prefix & ~mask) badusage("%s prefix %08lx not fully contained in mask %08lx",
286 if (mask_r) *mask_r= mask;
287 if (len_r) *len_r= len;
290 static int addrnet_isin(unsigned long prefix, unsigned long mask,
291 unsigned long mprefix, unsigned long mmask) {
292 return !(~mask & mmask) && (prefix & mmask) == mprefix;
296 static void permit(unsigned long pprefix, unsigned long pmask, int localonly) {
299 assert(!(pprefix & ~pmask));
302 if (!proto) fputs(localonly ? "permits-l" : "permits",stdout);
303 if (addrnet_isin(localaddr,~0UL, pprefix,pmask)) {
304 if (!proto) fputs(" local-addr",stdout);
308 if (addrnet_isin(peeraddr,~0UL, pprefix,pmask)) {
309 if (!proto) fputs(" peer-addr",stdout);
312 for (i=0; i<nexroutes; i++) {
313 if (addrnet_isin(exroutes[i].prefix,exroutes[i].mask, pprefix,pmask)) {
314 if (!proto) printf(" route#%d",i);
315 any= exroutes[i].allow= 1;
320 if (!any) fputs(" nothing",stdout);
325 static void pconfig(const char *configstr, int truncated);
327 static void pfile(const char *filename) {
331 struct pplace npp, *cpp;
333 for (cpp=cpplace; cpp; cpp=cpp->parent) {
334 if (!strcmp(cpp->filename,filename))
335 badusage("recursive configuration file `%s'",filename);
338 file= fopen(filename,"r");
340 badusage("cannot open configuration file `%s': %s", filename, strerror(errno));
342 if (!proto) printf("config file `%s':\n",filename);
345 npp.filename= filename;
349 while (fgets(buf, sizeof(buf), file)) {
354 truncated= (buf[l-1] != '\n');
355 while (l>0 && isspace((unsigned char) buf[l-1])) l--;
360 while ((c= getc(file)) != EOF && c != '\n');
364 pconfig(buf,truncated);
367 badusage("failed while reading configuration file: %s", strerror(errno));
372 static void pconfig(const char *configstr, int truncated) {
373 unsigned long fgid, tgid, pprefix, pmask;
378 switch (configstr[0]) {
380 if (strcmp(configstr,"*")) badusage("`*' directive must be only thing on line");
388 if (truncated) badusage("filename too long (`%.100s...')",configstr);
393 if (!isdigit((unsigned char)configstr[0]))
394 badusage("unknown configuration directive");
396 fgid= eat_number(&configstr,"gid", 0,gidmaxval, ",",0);
397 if (configstr[0] == '=') {
403 eat_prefixmask(&configstr,"permitted-prefix", ",",0, &pprefix,&pmask,&plen);
404 if (!configstr && truncated) badusage("gid,prefix/len,... spec too long");
406 if (!proto) printf(" %5lu,%s/%d: ", fgid, ip2txt(pprefix,ptxt), plen);
408 gidlist= getenv("USERV_GID");
409 if (!gidlist) fatal("USERV_GID not set");
412 if (!proto) printf("no matching gid\n");
415 tgid= eat_number(&gidlist,"userv-gid", 0,gidmaxval, " ",0);
416 if (tgid == fgid) break;
418 permit(pprefix,pmask,localonly);
423 static void checkallow(int allow, const char *what,
424 const char *prefixtxt, const char *masktxt) {
426 fprintf(stderr,"userv-ipif service: access denied for %s, %s/%s\n",
427 what, prefixtxt, masktxt);
431 static void parseargs(int argc, const char *const *argv) {
432 unsigned long routeaddr, routemask;
434 const char *const *cprotop;
436 char erwhatbuf[100], erwhatbuf2[100];
438 if (argc < NARGS+1) { badusage("too few arguments"); }
439 if (argc > NARGS+1) { badusage("too many arguments"); }
444 if (strcmp(carg,"--")) badusage("separator argument `--' not found, got `%s'",carg);
447 localaddr= eat_addr(&carg,"local-addr", ",",0);
448 peeraddr= eat_addr(&carg,"peer-addr", ",",0);
449 mtu= eat_number(&carg,"mtu", 576,65536, ",",0);
450 localallow= peerallow= 0;
452 if (!strcmp(carg,"debug")) {
455 for (cprotop= protos_ok;
456 (proto= *cprotop) && strcmp(proto,carg);
458 if (!proto) fatal("invalid protocol");
461 addrnet_mustdiffer("local-addr",localaddr,~0UL, "peer-addr",peeraddr,~0UL);
464 if (strcmp(carg,"-")) {
468 if (nexroutes == MAXEXROUTES)
469 fatal("too many extra routes (only %d allowed)",MAXEXROUTES);
470 sprintf(erwhatbuf,"route#%d",nexroutes);
472 eat_prefixmask(&carg,erwhatbuf, ",",0, &routeaddr,&routemask,0);
473 if (routemask == ~0UL) {
474 addrnet_mustdiffer(erwhatbuf,routeaddr,routemask, "local-addr",localaddr,~0UL);
475 addrnet_mustdiffer(erwhatbuf,routeaddr,routemask, "peer-addr",peeraddr,~0UL);
477 for (i=0; i<nexroutes; i++) {
478 sprintf(erwhatbuf2,"route#%d",i);
479 addrnet_mustdiffer(erwhatbuf,routeaddr,routemask,
480 erwhatbuf2,exroutes[i].prefix,exroutes[i].mask);
482 exroutes[nexroutes].prefix= routeaddr;
483 exroutes[nexroutes].mask= routemask;
484 exroutes[nexroutes].allow= 0;
485 ip2txt(routeaddr,exroutes[nexroutes].prefixtxt);
486 ip2txt(routemask,exroutes[nexroutes].masktxt);
490 ip2txt(localaddr,localtxt);
491 ip2txt(peeraddr,peertxt);
494 static void checkpermit(void) {
499 checkallow(localallow,"local-addr", localtxt,"32");
500 checkallow(peerallow,"peer-addr", peertxt,"32");
501 for (i=0; i<nexroutes; i++) {
502 sprintf(erwhatbuf, "route#%d", i);
503 checkallow(exroutes[i].allow, erwhatbuf, exroutes[i].prefixtxt, exroutes[i].masktxt);
505 if (!allallow) fatal("access denied");
508 static void dumpdebug(void) __attribute__((noreturn));
509 static void dumpdebug(void) {
513 printf("protocol: debug\n"
514 "local: %08lx == %s\n"
515 "peer: %08lx == %s\n"
522 for (i=0; i<nexroutes; i++) {
523 sprintf(erwhatbuf, "route#%d:", i);
524 printf("%-9s %08lx/%08lx == %s/%s\n",
526 exroutes[i].prefix, exroutes[i].mask,
527 exroutes[i].prefixtxt, exroutes[i].masktxt);
529 if (ferror(stdout) || fclose(stdout)) sysfatal("flush stdout");
534 static void setsigmask(const sigset_t *ss) {
537 r= sigprocmask(SIG_SETMASK, ss, 0);
538 if (r) sysfatal("[un]block signals");
541 static void setsignals(void (*handler)(int), struct sigaction *sa, int chldflags) {
545 sa->sa_handler= handler;
547 for (signalp=signals; (sig=*signalp); signalp++) {
548 r= sigaction(sig, sa, 0); if (r) sysfatal("uncatch signal");
550 sa->sa_flags= chldflags;
551 r= sigaction(SIGCHLD, sa, 0); if (r) sysfatal("uncatch children");
554 static void infork(void) {
557 memset(&pids,0,sizeof(pids));
558 sigemptyset(&sa.sa_mask);
559 setsignals(SIG_DFL,&sa,0);
560 setsigmask(&emptyset);
564 static pid_t makesubproc(void (*entry)(void)) {
567 pid= fork(); if (pid == (pid_t)-1) sysfatal("fork for subprocess");
575 static int task(void) {
579 if (pid == (pid_t)-1) sysfatal("fork for task");
580 if (!pid) { infork(); return 1; }
582 pids.byname.task= pid;
583 while (pids.byname.task) sigsuspend(&emptyset);
587 static void mdup2(int fd1, int fd2, const char *what) {
591 r= dup2(fd1,fd2); if (r==fd2) return;
592 if (r!=-1) fatal("dup2 in %s gave wrong answer %d instead of %d",what,r,fd2);
593 if (errno != EINTR) sysfatal("dup2 failed in %s",what);
597 static void sl_entry(void) {
598 mdup2(slpipe[1],1,"slattach child");
599 execlp("slattach", "slattach", "-v", "-L", "-p",proto, ptyname, (char*)0);
600 sysfatal("cannot exec slattach");
603 static void cin_entry(void) {
604 mdup2(ptmaster,1,"cat input child");
605 execlp("cat", "cat", (char*)0);
606 sysfatal("cannot exec cat input");
609 static void cout_entry(void) {
610 mdup2(ptmaster,0,"cat output child");
611 execlp("cat", "cat", (char*)0);
612 sysfatal("cannot exec cat output");
615 static void sighandler(int signum) {
618 const char *taskfail;
622 if (signum == SIGCHLD) {
624 pid= waitpid(-1,&status,WNOHANG);
625 if (!pid || pid == (pid_t)-1) return;
627 if (pid == pids.byname.task) {
631 } else if (pid == pids.byname.cin) {
634 taskfail= "input cat";
639 } else if (pid == pids.byname.cout) {
641 taskfail= "output cat";
642 } else if (pid == pids.byname.sl) {
644 taskfail= "slattach";
651 if (WIFEXITED(status)) {
653 "userv-ipif service: %s unexpectedly exited with exit status %d\n",
654 taskfail, WEXITSTATUS(status));
655 } else if (WIFSIGNALED(status)) {
657 "userv-ipif service: %s unexpectedly killed by signal %s%s\n",
658 taskfail, strsignal(WTERMSIG(status)),
659 WCOREDUMP(status) ? " (core dumped)" : "");
661 fprintf(stderr, "userv-ipif service: %s unexpectedly terminated"
662 " with unknown status code %d\n", taskfail, status);
667 "userv-ipif service: received signal %d, terminating\n",
674 static void startup(void) {
678 sigfillset(&fullset);
679 sigemptyset(&emptyset);
681 ptmaster= getpt(); if (ptmaster==-1) sysfatal("allocate pty master");
682 r= grantpt(ptmaster); if (r) sysfatal("grab/grant pty slave");
683 ptyname= ptsname(ptmaster); if (!ptyname) sysfatal("get pty slave name");
684 r= chmod(ptyname,0600); if (r) sysfatal("chmod pty slave");
685 r= unlockpt(ptmaster); if (r) sysfatal("unlock pty");
687 sigfillset(&sa.sa_mask);
688 setsignals(sighandler,&sa,SA_NOCLDSTOP);
689 setsigmask(&fullset);
692 static void startslattach(void) {
693 static char ifnbuf[200];
698 r= pipe(slpipe); if (r) sysfatal("create pipe");
699 piper= fdopen(slpipe[0],"r"); if (!piper) sysfatal("fdopen pipe");
702 pids.byname.sl= makesubproc(sl_entry);
705 setsigmask(&emptyset);
706 if (!fgets(ifnbuf,sizeof(ifnbuf),piper)) {
707 if (ferror(piper)) sysfatal("cannot read ifname from slattach");
708 else fatal("cannot read ifname from slattach");
710 setsigmask(&fullset);
712 if (l<=0 || ifnbuf[l-1] != '\n') fatal("slattach gave strange output `%s'",ifnbuf);
714 for (k=l; k>0 && ifnbuf[k-1]!=' '; k--);
718 static void netconfigure(void) {
723 sprintf(mtutxt,"%lu",mtu);
725 execlp("ifconfig", "ifconfig", ifname, localtxt,
726 "netmask","255.255.255.255", "-broadcast", "pointopoint",peertxt,
727 "mtu",mtutxt, "up", (char*)0);
728 sysfatal("cannot exec ifconfig");
731 for (i=0; i<nexroutes; i++) {
733 execlp("route","route", "add", "-net",exroutes[i].prefixtxt,
734 "netmask",exroutes[i].masktxt,
735 "gw",peertxt, "dev",ifname, (char*)0);
736 sysfatal("cannot exec route (for route)");
741 static void copydata(void) __attribute__((noreturn));
742 static void copydata(void) {
745 pids.byname.cin= makesubproc(cin_entry);
747 r= write(1, "\300", 1); if (r==1) break;
748 assert(r==-1); if (errno != EINTR) sysfatal("send initial delim to confirm");
750 pids.byname.cout= makesubproc(cout_entry);
752 for (;;) sigsuspend(&emptyset);
755 int main(int argc, const char *const *argv) {
756 parseargs(argc,argv);
757 pconfig(configstr,0);
759 if (!proto) dumpdebug();