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.
35 * Copyright (C) 1999 Ian Jackson
37 * This is free software; you can redistribute it and/or modify it
38 * under the terms of the GNU General Public License as published by
39 * the Free Software Foundation; either version 2 of the License, or
40 * (at your option) any later version.
42 * This program is distributed in the hope that it will be useful, but
43 * WITHOUT ANY WARRANTY; without even the implied warranty of
44 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
45 * General Public License for more details.
47 * You should have received a copy of the GNU General Public License
48 * along with userv-utils; if not, write to the Free Software
49 * Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
65 #include <sys/types.h>
73 static const unsigned long gidmaxval
= (unsigned long)((gid_t
)-2);
74 static const char *const protos_ok
[]= { "slip", "cslip", "adaptive", 0 };
75 static const int signals
[]= { SIGHUP
, SIGINT
, SIGTERM
, 0 };
77 static const char *configstr
, *proto
;
78 static unsigned long localaddr
, peeraddr
, mtu
;
79 static int localallow
, peerallow
, allallow
;
81 static struct exroute
{
82 unsigned long prefix
, mask
;
84 char prefixtxt
[ATXTLEN
], masktxt
[ATXTLEN
];
85 } exroutes
[MAXEXROUTES
];
87 static char localtxt
[ATXTLEN
];
88 static char peertxt
[ATXTLEN
];
90 static struct pplace
{
91 struct pplace
*parent
;
97 static int slpipe
[2], ptmaster
, undoslattach
;
98 static const char *ifname
;
99 static const char *ptyname
;
104 struct { pid_t sl
, cout
, cin
, task
; } byname
;
105 pid_t bynumber
[NPIDS
];
107 sigset_t emptyset
, fullset
;
110 static int cleantask(void) {
115 if (pid
== (pid_t
)-1)
116 perror("userv-ipif: fork for undo slattach failed - cannot clean up properly");
120 static void terminate(int estatus
) {
124 for (i
=0; i
<NPIDS
; i
++)
125 if (pids
.bynumber
[i
]) kill(pids
.bynumber
[i
], SIGTERM
);
129 execlp("slattach", "slattach", "-p", "tty", ptyname
, (char*)0);
130 perror("userv-ipif: exec slattach for undo slattach failed");
133 if (ifname
&& cleantask()) {
134 execlp("ifconfig", "ifconfig", ifname
, "down", (char*)0);
135 perror("userv-ipif: exec ifconfig for undo ifconfig failed");
141 pid
= waitpid(-1,&status
,0);
142 if (pid
== (pid_t
)-1) break;
148 static void fatal(const char *fmt
, ...)
149 __attribute__((format(printf
,1,2)));
150 static void fatal(const char *fmt
, ...) {
154 fputs("userv-ipif service: fatal error: ",stderr
);
155 vfprintf(stderr
, fmt
, al
);
160 static void sysfatal(const char *fmt
, ...)
161 __attribute__((format(printf
,1,2)));
162 static void sysfatal(const char *fmt
, ...) {
169 fputs("userv-ipif service: fatal system error: ",stderr
);
170 vfprintf(stderr
, fmt
, al
);
171 fprintf(stderr
,": %s\n", strerror(e
));
176 static void badusage(const char *fmt
, ...)
177 __attribute__((format(printf
,1,2)));
178 static void badusage(const char *fmt
, ...) {
184 "userv-ipif service: %s:%d: ",
185 cpplace
->filename
, cpplace
->lineno
);
187 fputs("userv-ipif service: invalid usage: ",stderr
);
190 vfprintf(stderr
, fmt
, al
);
194 for (cpp
=cpplace
->parent
; cpp
; cpp
=cpp
->parent
) {
196 "userv-ipif service: %s:%d: ... in file included from here\n",
197 cpp
->filename
, cpp
->lineno
);
203 static char *ip2txt(unsigned long addr
, char *buf
) {
204 sprintf(buf
, "%lu.%lu.%lu.%lu",
212 static unsigned long eat_number(const char **argp
, const char *what
,
213 unsigned long min
, unsigned long max
,
214 const char *endchars
, int *endchar_r
) {
215 /* If !endchars then the endchar must be a nul, otherwise it may be
216 * a nul (resulting in *argp set to 0) or something else (*argp set
217 * to point to after delim, *endchar_r set to delim).
218 * *endchar_r may be 0.
224 if (!*argp
) { badusage("missing number %s",what
); }
225 rv
= strtoul(*argp
,&ep
,0);
226 if ((endchar
= *ep
)) {
227 if (!endchars
) badusage("junk after number %s",what
);
228 if (!strchr(endchars
,endchar
))
229 badusage("invalid character or delimiter `%c' in or after number, %s:"
230 " expected %s (or none?)", endchar
,what
,endchars
);
235 if (endchar_r
) *endchar_r
= endchar
;
236 if (rv
< min
|| rv
> max
) badusage("number %s value %lu out of range %lu..%lu",
241 static void addrnet_mustdiffer(const char *w1
, unsigned long p1
, unsigned long m1
,
242 const char *w2
, unsigned long p2
, unsigned long m2
) {
246 if ((p1
& mask
) != (p2
& mask
)) return;
247 badusage("%s %08lx/%08lx overlaps/clashes with %s %08lx/%08lx",
251 static unsigned long eat_addr(const char **argp
, const char *what
,
252 const char *endchars
, int *endchar_r
) {
261 sprintf(whatbuf
,"%s byte #%d",what
,i
);
262 rv
|= eat_number(argp
,whatbuf
, 0,255, i
<3 ?
"." : endchars
, endchar_r
);
268 static void eat_prefixmask(const char **argp
, const char *what
,
269 const char *endchars
, int *endchar_r
,
270 unsigned long *prefix_r
, unsigned long *mask_r
, int *len_r
) {
271 /* mask_r and len_r may be 0 */
274 unsigned long prefix
, mask
;
276 prefix
= eat_addr(argp
,what
, "/",0);
277 sprintf(whatbuf
,"%s length",what
);
278 len
= eat_number(argp
,whatbuf
, 0,32, endchars
,endchar_r
);
280 mask
= (~0UL << (32-len
));
281 if (prefix
& ~mask
) badusage("%s prefix %08lx not fully contained in mask %08lx",
284 if (mask_r
) *mask_r
= mask
;
285 if (len_r
) *len_r
= len
;
288 static int addrnet_isin(unsigned long prefix
, unsigned long mask
,
289 unsigned long mprefix
, unsigned long mmask
) {
290 return !(~mask
& mmask
) && (prefix
& mmask
) == mprefix
;
294 static void permit(unsigned long pprefix
, unsigned long pmask
) {
297 assert(!(pprefix
& ~pmask
));
300 if (!proto
) fputs("permits",stdout
);
301 if (addrnet_isin(localaddr
,~0UL, pprefix
,pmask
)) {
302 if (!proto
) fputs(" local-addr",stdout
);
305 if (addrnet_isin(peeraddr
,~0UL, pprefix
,pmask
)) {
306 if (!proto
) fputs(" peer-addr",stdout
);
309 for (i
=0; i
<nexroutes
; i
++) {
310 if (addrnet_isin(exroutes
[i
].prefix
,exroutes
[i
].mask
, pprefix
,pmask
)) {
311 if (!proto
) printf(" route#%d",i
);
312 any
= exroutes
[i
].allow
= 1;
316 if (!any
) fputs(" nothing",stdout
);
321 static void pconfig(const char *configstr
, int truncated
);
323 static void pfile(const char *filename
) {
327 struct pplace npp
, *cpp
;
329 for (cpp
=cpplace
; cpp
; cpp
=cpp
->parent
) {
330 if (!strcmp(cpp
->filename
,filename
))
331 badusage("recursive configuration file `%s'",filename
);
334 file
= fopen(filename
,"r");
336 badusage("cannot open configuration file `%s': %s", filename
, strerror(errno
));
338 if (!proto
) printf("config file `%s':\n",filename
);
341 npp
.filename
= filename
;
345 while (fgets(buf
, sizeof(buf
), file
)) {
350 truncated
= (buf
[l
-1] != '\n');
351 while (l
>0 && isspace((unsigned char) buf
[l
-1])) l
--;
356 while ((c
= getc(file
)) != EOF
&& c
!= '\n');
360 pconfig(buf
,truncated
);
363 badusage("failed while reading configuration file: %s", strerror(errno
));
368 static void pconfig(const char *configstr
, int truncated
) {
369 unsigned long fgid
, tgid
, pprefix
, pmask
;
374 switch (configstr
[0]) {
376 if (strcmp(configstr
,"*")) badusage("`*' directive must be only thing on line");
384 if (truncated
) badusage("filename too long (`%.100s...')",configstr
);
389 if (!isdigit((unsigned char)configstr
[0]))
390 badusage("unknown configuration directive");
392 fgid
= eat_number(&configstr
,"gid", 0,gidmaxval
, ",",0);
393 eat_prefixmask(&configstr
,"permitted-prefix", ",",0, &pprefix
,&pmask
,&plen
);
394 if (!configstr
&& truncated
) badusage("gid,prefix/len,... spec too long");
396 if (!proto
) printf(" %5lu,%s/%d: ", fgid
, ip2txt(pprefix
,ptxt
), plen
);
398 gidlist
= getenv("USERV_GID");
399 if (!gidlist
) fatal("USERV_GID not set");
402 if (!proto
) printf("no matching gid\n");
405 tgid
= eat_number(&gidlist
,"userv-gid", 0,gidmaxval
, " ",0);
406 if (tgid
== fgid
) break;
408 permit(pprefix
,pmask
);
413 static void checkallow(int allow
, const char *what
,
414 const char *prefixtxt
, const char *masktxt
) {
416 fprintf(stderr
,"userv-ipif service: access denied for %s, %s/%s\n",
417 what
, prefixtxt
, masktxt
);
421 static void parseargs(int argc
, const char *const *argv
) {
422 unsigned long routeaddr
, routemask
;
424 const char *const *cprotop
;
426 char erwhatbuf
[100], erwhatbuf2
[100];
428 if (argc
< NARGS
+1) { badusage("too few arguments"); }
429 if (argc
> NARGS
+1) { badusage("too many arguments"); }
434 if (strcmp(carg
,"--")) badusage("separator argument `--' not found, got `%s'",carg
);
437 localaddr
= eat_addr(&carg
,"local-addr", ",",0);
438 peeraddr
= eat_addr(&carg
,"peer-addr", ",",0);
439 mtu
= eat_number(&carg
,"mtu", 576,65536, ",",0);
440 localallow
= peerallow
= 0;
442 if (!strcmp(carg
,"debug")) {
445 for (cprotop
= protos_ok
;
446 (proto
= *cprotop
) && strcmp(proto
,carg
);
448 if (!proto
) fatal("invalid protocol");
451 addrnet_mustdiffer("local-addr",localaddr
,~0UL, "peer-addr",peeraddr
,~0UL);
454 if (strcmp(carg
,"-")) {
458 if (nexroutes
== MAXEXROUTES
)
459 fatal("too many extra routes (only %d allowed)",MAXEXROUTES
);
460 sprintf(erwhatbuf
,"route#%d",nexroutes
);
462 eat_prefixmask(&carg
,erwhatbuf
, ",",0, &routeaddr
,&routemask
,0);
463 if (routemask
== ~0UL) {
464 addrnet_mustdiffer(erwhatbuf
,routeaddr
,routemask
, "local-addr",localaddr
,~0UL);
465 addrnet_mustdiffer(erwhatbuf
,routeaddr
,routemask
, "peer-addr",peeraddr
,~0UL);
467 for (i
=0; i
<nexroutes
; i
++) {
468 sprintf(erwhatbuf2
,"route#%d",i
);
469 addrnet_mustdiffer(erwhatbuf
,routeaddr
,routemask
,
470 erwhatbuf2
,exroutes
[i
].prefix
,exroutes
[i
].mask
);
472 exroutes
[nexroutes
].prefix
= routeaddr
;
473 exroutes
[nexroutes
].mask
= routemask
;
474 exroutes
[nexroutes
].allow
= 0;
475 ip2txt(routeaddr
,exroutes
[nexroutes
].prefixtxt
);
476 ip2txt(routemask
,exroutes
[nexroutes
].masktxt
);
480 ip2txt(localaddr
,localtxt
);
481 ip2txt(peeraddr
,peertxt
);
484 static void checkpermit(void) {
489 checkallow(localallow
,"local-addr", localtxt
,"32");
490 checkallow(peerallow
,"peer-addr", peertxt
,"32");
491 for (i
=0; i
<nexroutes
; i
++) {
492 sprintf(erwhatbuf
, "route#%d", i
);
493 checkallow(exroutes
[i
].allow
, erwhatbuf
, exroutes
[i
].prefixtxt
, exroutes
[i
].masktxt
);
495 if (!allallow
) fatal("access denied");
498 static void dumpdebug(void) __attribute__((noreturn
));
499 static void dumpdebug(void) {
503 printf("protocol: debug\n"
504 "local: %08lx == %s\n"
505 "peer: %08lx == %s\n"
512 for (i
=0; i
<nexroutes
; i
++) {
513 sprintf(erwhatbuf
, "route#%d:", i
);
514 printf("%-9s %08lx/%08lx == %s/%s\n",
516 exroutes
[i
].prefix
, exroutes
[i
].mask
,
517 exroutes
[i
].prefixtxt
, exroutes
[i
].masktxt
);
519 if (ferror(stdout
) || fclose(stdout
)) sysfatal("flush stdout");
524 static void setsigmask(const sigset_t
*ss
) {
527 r
= sigprocmask(SIG_SETMASK
, ss
, 0);
528 if (r
) sysfatal("[un]block signals");
531 static void setsignals(void (*handler
)(int), struct sigaction
*sa
, int chldflags
) {
535 sa
->sa_handler
= handler
;
537 for (signalp
=signals
; (sig
=*signalp
); signalp
++) {
538 r
= sigaction(sig
, sa
, 0); if (r
) sysfatal("uncatch signal");
540 sa
->sa_flags
= chldflags
;
541 r
= sigaction(SIGCHLD
, sa
, 0); if (r
) sysfatal("uncatch children");
544 static void infork(void) {
547 memset(&pids
,0,sizeof(pids
));
548 sigemptyset(&sa
.sa_mask
);
549 setsignals(SIG_DFL
,&sa
,0);
550 setsigmask(&emptyset
);
554 static pid_t
makesubproc(void (*entry
)(void)) {
557 pid
= fork(); if (pid
== (pid_t
)-1) sysfatal("fork for subprocess");
565 static int task(void) {
569 if (pid
== (pid_t
)-1) sysfatal("fork for task");
570 if (!pid
) { infork(); return 1; }
572 pids
.byname
.task
= pid
;
573 while (pids
.byname
.task
) sigsuspend(&emptyset
);
577 static void mdup2(int fd1
, int fd2
, const char *what
) {
581 r
= dup2(fd1
,fd2
); if (r
==fd2
) return;
582 if (r
!=-1) fatal("dup2 in %s gave wrong answer %d instead of %d",what
,r
,fd2
);
583 if (errno
!= EINTR
) sysfatal("dup2 failed in %s",what
);
587 static void sl_entry(void) {
588 mdup2(slpipe
[1],1,"slattach child");
589 execlp("slattach", "slattach", "-v", "-L", "-p",proto
, ptyname
, (char*)0);
590 sysfatal("cannot exec slattach");
593 static void cin_entry(void) {
594 mdup2(ptmaster
,1,"cat input child");
595 execlp("cat", "cat", (char*)0);
596 sysfatal("cannot exec cat input");
599 static void cout_entry(void) {
600 mdup2(ptmaster
,0,"cat output child");
601 execlp("cat", "cat", (char*)0);
602 sysfatal("cannot exec cat output");
605 static void sighandler(int signum
) {
608 const char *taskfail
;
612 if (signum
== SIGCHLD
) {
614 pid
= waitpid(-1,&status
,WNOHANG
);
615 if (!pid
|| pid
== (pid_t
)-1) return;
617 if (pid
== pids
.byname
.task
) {
621 } else if (pid
== pids
.byname
.cin
) {
624 taskfail
= "input cat";
629 } else if (pid
== pids
.byname
.cout
) {
631 taskfail
= "output cat";
632 } else if (pid
== pids
.byname
.sl
) {
634 taskfail
= "slattach";
641 if (WIFEXITED(status
)) {
643 "userv-ipif service: %s unexpectedly exited with exit status %d\n",
644 taskfail
, WEXITSTATUS(status
));
645 } else if (WIFSIGNALED(status
)) {
647 "userv-ipif service: %s unexpectedly killed by signal %s%s\n",
648 taskfail
, strsignal(WTERMSIG(status
)),
649 WCOREDUMP(status
) ?
" (core dumped)" : "");
651 fprintf(stderr
, "userv-ipif service: %s unexpectedly terminated"
652 " with unknown status code %d\n", taskfail
, status
);
657 "userv-ipif service: received signal %d, terminating\n",
664 static void startup(void) {
668 sigfillset(&fullset
);
669 sigemptyset(&emptyset
);
671 ptmaster
= getpt(); if (ptmaster
==-1) sysfatal("allocate pty master");
672 r
= grantpt(ptmaster
); if (r
) sysfatal("grab/grant pty slave");
673 ptyname
= ptsname(ptmaster
); if (!ptyname
) sysfatal("get pty slave name");
674 r
= chmod(ptyname
,0600); if (r
) sysfatal("chmod pty slave");
675 r
= unlockpt(ptmaster
); if (r
) sysfatal("unlock pty");
677 sigfillset(&sa
.sa_mask
);
678 setsignals(sighandler
,&sa
,SA_NOCLDSTOP
);
679 setsigmask(&fullset
);
682 static void startslattach(void) {
683 static char ifnbuf
[200];
688 r
= pipe(slpipe
); if (r
) sysfatal("create pipe");
689 piper
= fdopen(slpipe
[0],"r"); if (!piper
) sysfatal("fdopen pipe");
692 pids
.byname
.sl
= makesubproc(sl_entry
);
695 setsigmask(&emptyset
);
696 if (!fgets(ifnbuf
,sizeof(ifnbuf
),piper
)) {
697 if (ferror(piper
)) sysfatal("cannot read ifname from slattach");
698 else fatal("cannot read ifname from slattach");
700 setsigmask(&fullset
);
702 if (l
<=0 || ifnbuf
[l
-1] != '\n') fatal("slattach gave strange output `%s'",ifnbuf
);
704 for (k
=l
; k
>0 && ifnbuf
[k
-1]!=' '; k
--);
708 static void netconfigure(void) {
713 sprintf(mtutxt
,"%lu",mtu
);
715 execlp("ifconfig", "ifconfig", ifname
, localtxt
,
716 "netmask","255.255.255.255", "-broadcast", "pointopoint",peertxt
,
717 "mtu",mtutxt
, "up", (char*)0);
718 sysfatal("cannot exec ifconfig");
721 for (i
=0; i
<nexroutes
; i
++) {
723 execlp("route","route", "add", "-net",exroutes
[i
].prefixtxt
,
724 "netmask",exroutes
[i
].masktxt
,
725 "gw",peertxt
, "dev",ifname
, (char*)0);
726 sysfatal("cannot exec route (for route)");
731 static void copydata(void) __attribute__((noreturn
));
732 static void copydata(void) {
735 pids
.byname
.cin
= makesubproc(cin_entry
);
737 r
= write(1, "\300", 1); if (r
==1) break;
738 assert(r
==-1); if (errno
!= EINTR
) sysfatal("send initial delim to confirm");
740 pids
.byname
.cout
= makesubproc(cout_entry
);
742 for (;;) sigsuspend(&emptyset
);
745 int main(int argc
, const char *const *argv
) {
746 parseargs(argc
,argv
);
747 pconfig(configstr
,0);
749 if (!proto
) dumpdebug();