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.
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
));
280 if (!proto
) fputs("permits",stdout
);
281 if (addrnet_isin(localaddr
,~0UL, pprefix
,pmask
)) {
282 if (!proto
) fputs(" local-addr",stdout
);
285 if (addrnet_isin(peeraddr
,~0UL, pprefix
,pmask
)) {
286 if (!proto
) fputs(" peer-addr",stdout
);
289 for (i
=0; i
<nexroutes
; i
++) {
290 if (addrnet_isin(exroutes
[i
].prefix
,exroutes
[i
].mask
, pprefix
,pmask
)) {
291 if (!proto
) printf(" route#%d",i
);
292 any
= exroutes
[i
].allow
= 1;
296 if (!any
) fputs(" nothing!",stderr
);
301 static void pconfig(const char *configstr
, int truncated
);
303 static void pfile(const char *filename
) {
307 struct pplace npp
, *cpp
;
309 for (cpp
=cpplace
; cpp
; cpp
=cpp
->parent
) {
310 if (!strcmp(cpp
->filename
,filename
))
311 badusage("recursive configuration file `%s'",filename
);
314 file
= fopen(filename
,"r");
316 badusage("cannot open configuration file `%s': %s", filename
, strerror(errno
));
318 if (!proto
) printf("config file `%s':\n",filename
);
321 npp
.filename
= filename
;
325 while (fgets(buf
, sizeof(buf
), file
)) {
330 truncated
= (buf
[l
-1] != '\n');
331 while (l
>0 && isspace((unsigned char) buf
[l
-1])) l
--;
336 while ((c
= getc(file
)) != EOF
&& c
!= '\n');
340 pconfig(buf
,truncated
);
343 badusage("failed while reading configuration file: %s", strerror(errno
));
348 static void pconfig(const char *configstr
, int truncated
) {
349 unsigned long fgid
, tgid
, pprefix
, pmask
;
354 switch (configstr
[0]) {
356 if (strcmp(configstr
,"*")) badusage("`*' directive must be only thing on line");
364 if (truncated
) badusage("filename too long (`%.100s...')",configstr
);
369 if (!isdigit((unsigned char)configstr
[0]))
370 badusage("unknown configuration directive");
372 fgid
= eat_number(&configstr
,"gid", 0,gidmaxval
, ",",0);
373 eat_prefixmask(&configstr
,"permitted-prefix", ",",0, &pprefix
,&pmask
,&plen
);
374 if (!configstr
&& truncated
) badusage("gid,prefix/len,... spec too long");
376 if (!proto
) printf(" %5lu,%s/%d: ", fgid
, ip2txt(pprefix
,ptxt
), plen
);
378 gidlist
= getenv("USERV_GID");
379 if (!gidlist
) fatal("USERV_GID not set");
382 if (!proto
) printf("no matching gid\n");
385 tgid
= eat_number(&gidlist
,"userv-gid", 0,gidmaxval
, " ",0);
386 if (tgid
== fgid
) break;
388 permit(pprefix
,pmask
);
393 static void checkallow(int allow
, const char *what
,
394 const char *prefixtxt
, const char *masktxt
) {
396 fprintf(stderr
,"userv-ipif service: access denied for %s, %s/%s\n",
397 what
, prefixtxt
, masktxt
);
401 static void parseargs(int argc
, const char *const *argv
) {
402 unsigned long routeaddr
, routemask
;
404 const char *const *cprotop
;
406 char erwhatbuf
[100], erwhatbuf2
[100];
408 if (argc
< NARGS
+1) { badusage("too few arguments"); }
409 if (argc
> NARGS
+1) { badusage("too many arguments"); }
414 if (strcmp(carg
,"--")) badusage("separator argument `--' not found, got `%s'",carg
);
417 localaddr
= eat_addr(&carg
,"local-addr", ",",0);
418 peeraddr
= eat_addr(&carg
,"peer-addr", ",",0);
419 mtu
= eat_number(&carg
,"mtu", 576,65536, ",",0);
420 localallow
= peerallow
= 0;
422 if (!strcmp(carg
,"debug")) {
425 for (cprotop
= protos_ok
;
426 (proto
= *cprotop
) && strcmp(proto
,carg
);
428 if (!proto
) fatal("invalid protocol");
431 addrnet_mustdiffer("local-addr",localaddr
,~0UL, "peer-addr",peeraddr
,~0UL);
437 if (nexroutes
== MAXEXROUTES
)
438 fatal("too many extra routes (only %d allowed)",MAXEXROUTES
);
439 sprintf(erwhatbuf
,"route#%d",nexroutes
);
441 eat_prefixmask(&carg
,erwhatbuf
, ",",0, &routeaddr
,&routemask
,0);
442 if (routemask
== ~0UL) {
443 addrnet_mustdiffer(erwhatbuf
,routeaddr
,routemask
, "local-addr",localaddr
,~0UL);
444 addrnet_mustdiffer(erwhatbuf
,routeaddr
,routemask
, "peer-addr",peeraddr
,~0UL);
446 for (i
=0; i
<nexroutes
; i
++) {
447 sprintf(erwhatbuf2
,"route#%d",i
);
448 addrnet_mustdiffer(erwhatbuf
,routeaddr
,routemask
,
449 erwhatbuf2
,exroutes
[i
].prefix
,exroutes
[i
].mask
);
451 exroutes
[nexroutes
].prefix
= routeaddr
;
452 exroutes
[nexroutes
].mask
= routemask
;
453 exroutes
[nexroutes
].allow
= 0;
454 ip2txt(routeaddr
,exroutes
[nexroutes
].prefixtxt
);
455 ip2txt(routemask
,exroutes
[nexroutes
].masktxt
);
457 ip2txt(localaddr
,localtxt
);
458 ip2txt(peeraddr
,peertxt
);
461 static void checkpermit(void) {
466 checkallow(localallow
,"local-addr", localtxt
,"32");
467 checkallow(peerallow
,"peer-addr", peertxt
,"32");
468 for (i
=0; i
<nexroutes
; i
++) {
469 sprintf(erwhatbuf
, "route#%d", i
);
470 checkallow(exroutes
[i
].allow
, erwhatbuf
, exroutes
[i
].prefixtxt
, exroutes
[i
].masktxt
);
472 if (!allallow
) fatal("access denied");
475 static void dumpdebug(void) __attribute__((noreturn
));
476 static void dumpdebug(void) {
480 printf("protocol: debug\n"
481 "local: %08lx == %s\n"
482 "peer: %08lx == %s\n"
489 for (i
=0; i
<nexroutes
; i
++) {
490 sprintf(erwhatbuf
, "route#%d:", i
);
491 printf("%-9s %08lx/%08lx == %s/%s\n",
493 exroutes
[i
].prefix
, exroutes
[i
].mask
,
494 exroutes
[i
].prefixtxt
, exroutes
[i
].masktxt
);
496 if (ferror(stdout
) || fclose(stdout
)) sysfatal("flush stdout");
501 static void setsigmask(const sigset_t
*ss
) {
504 r
= sigprocmask(SIG_SETMASK
, ss
, 0);
505 if (r
) sysfatal("[un]block signals");
508 static void setsignals(void (*handler
)(int), struct sigaction
*sa
, int chldflags
) {
512 sa
->sa_handler
= handler
;
514 for (signalp
=signals
; (sig
=*signalp
); signalp
++) {
515 r
= sigaction(sig
, sa
, 0); if (r
) sysfatal("uncatch signal");
517 sa
->sa_flags
= chldflags
;
518 r
= sigaction(SIGCHLD
, sa
, 0); if (r
) sysfatal("uncatch children");
521 static void infork(void) {
524 memset(&pids
,0,sizeof(pids
));
525 sigemptyset(&sa
.sa_mask
);
526 setsignals(SIG_DFL
,&sa
,0);
527 setsigmask(&emptyset
);
531 static pid_t
makesubproc(void (*entry
)(void)) {
534 pid
= fork(); if (pid
== (pid_t
)-1) sysfatal("fork for subprocess");
542 static int task(void) {
546 if (pid
== (pid_t
)-1) sysfatal("fork for task");
547 if (!pid
) { infork(); return 1; }
549 pids
.byname
.task
= pid
;
550 while (pids
.byname
.task
) sigsuspend(&emptyset
);
554 static void mdup2(int fd1
, int fd2
, const char *what
) {
558 r
= dup2(fd1
,fd2
); if (r
==fd2
) return;
559 if (r
!=-1) fatal("dup2 in %s gave wrong answer %d instead of %d",what
,r
,fd2
);
560 if (errno
!= EINTR
) sysfatal("dup2 failed in %s",what
);
564 static void sl_entry(void) {
565 mdup2(slpipe
[1],1,"slattach child");
566 execlp("slattach", "slattach", "-v", "-L", "-p",proto
, ptyname
, (char*)0);
567 sysfatal("cannot exec slattach");
570 static void cin_entry(void) {
571 mdup2(ptmaster
,1,"cat input child");
572 execlp("cat", "cat", (char*)0);
573 sysfatal("cannot exec cat input");
576 static void cout_entry(void) {
577 mdup2(ptmaster
,0,"cat output child");
578 execlp("cat", "cat", (char*)0);
579 sysfatal("cannot exec cat output");
582 static void sighandler(int signum
) {
585 const char *taskfail
;
589 if (signum
== SIGCHLD
) {
591 pid
= waitpid(-1,&status
,WNOHANG
);
592 if (!pid
|| pid
== (pid_t
)-1) return;
594 if (pid
== pids
.byname
.task
) {
598 } else if (pid
== pids
.byname
.cin
) {
601 taskfail
= "input cat";
606 } else if (pid
== pids
.byname
.cout
) {
608 taskfail
= "output cat";
609 } else if (pid
== pids
.byname
.sl
) {
611 taskfail
= "slattach";
618 if (WIFEXITED(status
)) {
620 "userv-ipif service: %s unexpectedly exited with exit status %d\n",
621 taskfail
, WEXITSTATUS(status
));
622 } else if (WIFSIGNALED(status
)) {
624 "userv-ipif service: %s unexpectedly killed by signal %s%s\n",
625 taskfail
, strsignal(WTERMSIG(status
)),
626 WCOREDUMP(status
) ?
" (core dumped)" : "");
628 fprintf(stderr
, "userv-ipif service: %s unexpectedly terminated"
629 " with unknown status code %d\n", taskfail
, status
);
634 "userv-ipif service: received signal %d, terminating\n",
641 static void startup(void) {
645 sigfillset(&fullset
);
646 sigemptyset(&emptyset
);
648 ptmaster
= getpt(); if (ptmaster
==-1) sysfatal("allocate pty master");
649 r
= grantpt(ptmaster
); if (r
) sysfatal("grab/grant pty slave");
650 ptyname
= ptsname(ptmaster
); if (!ptyname
) sysfatal("get pty slave name");
651 r
= chmod(ptyname
,0600); if (r
) sysfatal("chmod pty slave");
652 r
= unlockpt(ptmaster
); if (r
) sysfatal("unlock pty");
654 sigfillset(&sa
.sa_mask
);
655 setsignals(sighandler
,&sa
,SA_NOCLDSTOP
);
656 setsigmask(&fullset
);
659 static void startslattach(void) {
660 static char ifnbuf
[200];
665 r
= pipe(slpipe
); if (r
) sysfatal("create pipe");
666 piper
= fdopen(slpipe
[0],"r"); if (!piper
) sysfatal("fdopen pipe");
669 pids
.byname
.sl
= makesubproc(sl_entry
);
672 setsigmask(&emptyset
);
673 if (!fgets(ifnbuf
,sizeof(ifnbuf
),piper
)) {
674 if (ferror(piper
)) sysfatal("cannot read ifname from slattach");
675 else fatal("cannot read ifname from slattach");
677 setsigmask(&fullset
);
679 if (l
<0 || ifnbuf
[l
-1] != '\n') fatal("slattach gave strange output `%s'",ifnbuf
);
681 for (k
=l
; k
>0 && ifnbuf
[k
-1]!=' '; k
--);
685 static void netconfigure(void) {
690 sprintf(mtutxt
,"%lu",mtu
);
692 execlp("ifconfig", "ifconfig", ifname
, localtxt
,
693 "netmask","255.255.255.255", "-broadcast", "pointopoint",peertxt
,
694 "mtu",mtutxt
, "up", (char*)0);
695 sysfatal("cannot exec ifconfig");
698 for (i
=0; i
<nexroutes
; i
++) {
700 execlp("route","route", "add", "-net",exroutes
[i
].prefixtxt
,
701 "netmask",exroutes
[i
].masktxt
,
702 "gw",peertxt
, "dev",ifname
, (char*)0);
703 sysfatal("cannot exec route (for route)");
708 static void copydata(void) __attribute__((noreturn
));
709 static void copydata(void) {
712 pids
.byname
.cin
= makesubproc(cin_entry
);
714 r
= write(1, "\300", 1); if (r
==1) break;
715 assert(r
==-1); if (errno
!= EINTR
) sysfatal("send initial delim to confirm");
717 pids
.byname
.cout
= makesubproc(cout_entry
);
719 for (;;) sigsuspend(&emptyset
);
722 int main(int argc
, const char *const *argv
) {
723 parseargs(argc
,argv
);
724 pconfig(configstr
,0);
726 if (!proto
) dumpdebug();