copyright notices
[userv-utils] / ipif / service.c
1 /*
2 * userv service (or standalone program) for per-user IP subranges.
3 *
4 * When invoked appropriately, it creates a point-to-point network
5 * interface with specified parameters. It arranges for packets sent out
6 * via that interface by the kernel to appear on its own stdout in SLIP or
7 * CSLIP encoding, and packets injected into its own stdin to be given to
8 * the kernel as if received on that interface. Optionally, additional
9 * routes can be set up to arrange for traffic for other address ranges to
10 * be routed through the new interface.
11 *
12 * This is the service program, which is invoked as root from userv (or may
13 * be invoked firectly).
14 *
15 * Its arguments are supposed to be, in order, as follows:
16 *
17 * The first two arguments are usually supplied by the userv
18 * configuration. See the file `ipif/ipif' in the source tree, which
19 * is installed in /etc/userv/services.d/ipif by `make install':
20 *
21 * <config>
22 *
23 * Specifies address ranges and gids which own them. The default
24 * configuration supplies /etc/userv/ipif-networks, which is then read
25 * for a list of entries, one per line.
26 *
27 * --
28 * Serves to separate the user-supplied and therefore untrusted
29 * arguments from the trusted first argument.
30 *
31 * The remaining arguments are supplied by the (untrusted) caller:
32 *
33 * <local-addr>,<peer-addr>,<mtu>,<proto>
34 *
35 * As for slattach. Supported protocols are slip, cslip, and
36 * adaptive. Alternatively, set to `debug' to print debugging info
37 * and exit. <local-addr> is address of the interface to be created
38 * on the local system; <peer-addr> is the address of the
39 * point-to-point peer. They must be actual addresses (not
40 * hostnames).
41 *
42 * <prefix>/<mask>,<prefix>/<mask>,...
43 *
44 * List of additional routes to add for this interface. routes will
45 * be set up on the local system arranging for packets for those
46 * networks to be sent via the created interface. <prefix> must be an
47 * IPv4 address, and mask must be an integer (dotted-quad masks are
48 * not supported). If no additional routes are to be set up, use `-'
49 * or supply an empty argument.
50 *
51 * Each <config> item - whether a line file such as
52 * /etc/userv/ipif-networks, or supplied on the service program
53 * command line - is one of:
54 *
55 * /<config-file-name>
56 * ./<config-file-name>
57 * ../<config-file-name>
58 *
59 * Reads a file which contains lines which are each <config>
60 * items.
61 *
62 * <gid>,[=][-|+]<prefix>/<len>(-|+<prefix>/<len>...)[,<junk>]
63 *
64 * Indicates that <gid> may allocate addresses in the relevant address
65 * range (<junk> is ignored). <gid> must be numeric. To specify a
66 * single host address, you must specify a mask of /32. If `=' is
67 * specified then the specific subrange is only allowed for the local
68 * endpoint address, but not for remote addresses.
69 *
70 * More than one range may be given, with each range prefixed
71 * by + or -. In this case each address range in the rule will
72 * scanned in order, and the first range in the rule that matches
73 * any desired rule will count: if that first matching range is
74 * prefixed by `+' (or nothing) then the rule applies, if it
75 * is prefixed by `-' (or nothing matches), the rule does not.
76 *
77 * *
78 * Means that anything is to be permitted. This should not appear in
79 * /etc/userv/ipif-networks, as that would permit any user on the
80 * system to create any interfaces with any addresses and routes
81 * attached. It is provided so that root can usefully invoke the ipif
82 * service program directly (not via userv), without needing to set up
83 * permissions in /etc/userv/ipif-networks.
84 *
85 * #...
86 *
87 * Comment. Blank lines are also ignored.
88 *
89 * NB: Permission is granted if _any_ config entry matches the request.
90 *
91 * The service program should be run from userv with no-disconnect-hup.
92 */
93 /*
94 * Copyright (C) 1999-2000,2003 Ian Jackson
95 * This file is part of ipif, part of userv-utils
96 *
97 * This is free software; you can redistribute it and/or modify it
98 * under the terms of the GNU General Public License as published by
99 * the Free Software Foundation; either version 2 of the License, or
100 * (at your option) any later version.
101 *
102 * This program is distributed in the hope that it will be useful, but
103 * WITHOUT ANY WARRANTY; without even the implied warranty of
104 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
105 * General Public License for more details.
106 *
107 * You should have received a copy of the GNU General Public License
108 * along with userv-utils; if not, write to the Free Software
109 * Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
110 *
111 * $Id$
112 */
113
114 #include <stdio.h>
115 #include <string.h>
116 #include <stdlib.h>
117 #include <assert.h>
118 #include <errno.h>
119 #include <stdarg.h>
120 #include <ctype.h>
121 #include <limits.h>
122 #include <signal.h>
123 #include <unistd.h>
124
125 #include <sys/types.h>
126 #include <sys/wait.h>
127 #include <sys/stat.h>
128
129 #define NARGS 4
130 #define MAXEXROUTES 50
131 #define ATXTLEN 16
132
133 static const unsigned long gidmaxval= (unsigned long)((gid_t)-2);
134 static const char *const protos_ok[]= { "slip", "cslip", "adaptive", 0 };
135 static const int signals[]= { SIGHUP, SIGINT, SIGTERM, 0 };
136
137 static const char *configstr, *proto;
138 static unsigned long localaddr, peeraddr, mtu;
139 static int localpming, peerpming;
140 static int localallow, peerallow, allallow;
141 static int nexroutes;
142 static struct exroute {
143 unsigned long prefix, mask;
144 int allow, pming;
145 char prefixtxt[ATXTLEN], masktxt[ATXTLEN];
146 } exroutes[MAXEXROUTES];
147
148 static char localtxt[ATXTLEN];
149 static char peertxt[ATXTLEN];
150
151 static struct pplace {
152 struct pplace *parent;
153 const char *filename;
154 int lineno;
155 } *cpplace;
156
157
158 static int slpipe[2], ptmaster, undoslattach;
159 static const char *ifname;
160 static const char *ptyname;
161
162 #define NPIDS 4
163
164 static union {
165 struct { pid_t sl, cout, cin, task; } byname;
166 pid_t bynumber[NPIDS];
167 } pids;
168 sigset_t emptyset, fullset;
169
170
171 static int cleantask(void) {
172 pid_t pid;
173
174 pid= fork();
175 if (!pid) return 1;
176 if (pid == (pid_t)-1)
177 perror("userv-ipif: fork for undo slattach failed - cannot clean up properly");
178 return 0;
179 }
180
181 static void terminate(int estatus) {
182 int i, status;
183 pid_t pid;
184
185 for (i=0; i<NPIDS; i++)
186 if (pids.bynumber[i]) kill(pids.bynumber[i], SIGTERM);
187
188 if (undoslattach) {
189 if (cleantask()) {
190 execlp("slattach", "slattach", "-p", "tty", ptyname, (char*)0);
191 perror("userv-ipif: exec slattach for undo slattach failed");
192 exit(-1);
193 }
194 if (ifname && cleantask()) {
195 execlp("ifconfig", "ifconfig", ifname, "down", (char*)0);
196 perror("userv-ipif: exec ifconfig for undo ifconfig failed");
197 exit(-1);
198 }
199 }
200
201 for (;;) {
202 pid= waitpid(-1,&status,0);
203 if (pid == (pid_t)-1) break;
204 }
205 exit(estatus);
206 }
207
208
209 static void fatal(const char *fmt, ...)
210 __attribute__((format(printf,1,2)));
211 static void fatal(const char *fmt, ...) {
212 va_list al;
213 va_start(al,fmt);
214
215 fputs("userv-ipif service: fatal error: ",stderr);
216 vfprintf(stderr, fmt, al);
217 putc('\n',stderr);
218 terminate(8);
219 }
220
221 static void sysfatal(const char *fmt, ...)
222 __attribute__((format(printf,1,2)));
223 static void sysfatal(const char *fmt, ...) {
224 va_list al;
225 int e;
226
227 e= errno;
228 va_start(al,fmt);
229
230 fputs("userv-ipif service: fatal system error: ",stderr);
231 vfprintf(stderr, fmt, al);
232 fprintf(stderr,": %s\n", strerror(e));
233 terminate(12);
234 }
235
236
237 static void badusage(const char *fmt, ...)
238 __attribute__((format(printf,1,2)));
239 static void badusage(const char *fmt, ...) {
240 va_list al;
241 struct pplace *cpp;
242
243 if (cpplace) {
244 fprintf(stderr,
245 "userv-ipif service: %s:%d: ",
246 cpplace->filename, cpplace->lineno);
247 } else {
248 fputs("userv-ipif service: invalid usage: ",stderr);
249 }
250 va_start(al,fmt);
251 vfprintf(stderr, fmt, al);
252 putc('\n',stderr);
253
254 if (cpplace) {
255 for (cpp=cpplace->parent; cpp; cpp=cpp->parent) {
256 fprintf(stderr,
257 "userv-ipif service: %s:%d: ... in file included from here\n",
258 cpp->filename, cpp->lineno);
259 }
260 }
261 terminate(16);
262 }
263
264 static char *ip2txt(unsigned long addr, char *buf) {
265 sprintf(buf, "%lu.%lu.%lu.%lu",
266 (addr>>24) & 0x0ff,
267 (addr>>16) & 0x0ff,
268 (addr>>8) & 0x0ff,
269 (addr) & 0x0ff);
270 return buf;
271 }
272
273 static unsigned long eat_number(const char **argp, const char *what,
274 unsigned long min, unsigned long max,
275 const char *endchars, int *endchar_r) {
276 /* If !endchars then the endchar must be a nul, otherwise it may be
277 * a nul (resulting in *argp set to 0) or something else (*argp set
278 * to point to after delim, *endchar_r set to delim).
279 * *endchar_r may be 0.
280 */
281 unsigned long rv;
282 char *ep;
283 int endchar;
284
285 if (!*argp) { badusage("missing number %s",what); }
286 rv= strtoul(*argp,&ep,0);
287 if ((endchar= *ep)) {
288 if (!endchars) badusage("junk after number %s",what);
289 if (!strchr(endchars,endchar))
290 badusage("invalid character or delimiter `%c' in or after number, %s:"
291 " expected %s (or none?)", endchar,what,endchars);
292 *argp= ep+1;
293 } else {
294 *argp= 0;
295 }
296 if (endchar_r) *endchar_r= endchar;
297 if (rv < min || rv > max) badusage("number %s value %lu out of range %lu..%lu",
298 what, rv, min, max);
299 return rv;
300 }
301
302 static int addrnet_overlap(unsigned long p1, unsigned long m1,
303 unsigned long p2, unsigned long m2) {
304 unsigned long mask;
305
306 mask= m1&m2;
307 return (p1 & mask) == (p2 & mask);
308 }
309
310 static void addrnet_mustdiffer(const char *w1, unsigned long p1, unsigned long m1,
311 const char *w2, unsigned long p2, unsigned long m2) {
312 if (!addrnet_overlap(p1,m1,p2,m2)) return;
313 badusage("%s %08lx/%08lx overlaps/clashes with %s %08lx/%08lx",
314 w1,p1,m1, w2,p2,m2);
315 }
316
317 static unsigned long eat_addr(const char **argp, const char *what,
318 const char *endchars, int *endchar_r) {
319 char whatbuf[100];
320 unsigned long rv;
321 int i;
322
323 for (rv=0, i=0;
324 i<4;
325 i++) {
326 rv <<= 8;
327 sprintf(whatbuf,"%s byte #%d",what,i);
328 rv |= eat_number(argp,whatbuf, 0,255, i<3 ? "." : endchars, endchar_r);
329 }
330
331 return rv;
332 }
333
334 static void eat_prefixmask(const char **argp, const char *what,
335 const char *endchars, int *endchar_r,
336 unsigned long *prefix_r, unsigned long *mask_r, int *len_r) {
337 /* mask_r and len_r may be 0 */
338 char whatbuf[100];
339 int len;
340 unsigned long prefix, mask;
341
342 prefix= eat_addr(argp,what, "/",0);
343 sprintf(whatbuf,"%s length",what);
344 len= eat_number(argp,whatbuf, 0,32, endchars,endchar_r);
345
346 mask= len ? (~0UL << (32-len)) : 0UL;
347 if (prefix & ~mask) badusage("%s prefix %08lx not fully contained in mask %08lx",
348 what,prefix,mask);
349 *prefix_r= prefix;
350 if (mask_r) *mask_r= mask;
351 if (len_r) *len_r= len;
352 }
353
354 static int addrnet_isin(unsigned long prefix, unsigned long mask,
355 unsigned long mprefix, unsigned long mmask) {
356 return !(~mask & mmask) && (prefix & mmask) == mprefix;
357 }
358
359 /* Totally hideous algorithm for parsing the config file lines.
360 * For each config file line, we first see if its gid applies. If not
361 * we skip it. Otherwise, we do
362 * permit_begin
363 * which sets <foo>pming to 1
364 * for each range. <foo>pming may be 0 if we've determined that
365 * this line does not apply to <foo>.
366 * permit_range
367 * which calls permit_range_thing for each <foo>
368 * which checks to see if <foo> is inside the relevant
369 * range (for +) or overlaps it (for -) and updates
370 * <foo>allow and <foo>pming.
371 */
372
373 static void permit_begin(void) {
374 int i;
375
376 localpming= peerpming= 1;
377 for (i=0; i<nexroutes; i++) exroutes[i].pming= 1;
378 }
379
380 static void permit_range_thing(unsigned long tprefix, unsigned long tmask,
381 const char *what, int *tallow, int *tpming,
382 unsigned long pprefix, unsigned long pmask,
383 int plus, int *any) {
384 if (plus) {
385 if (!addrnet_isin(tprefix,tmask, pprefix,pmask)) return;
386 if (*tpming) *tallow= 1;
387 } else {
388 if (!addrnet_overlap(tprefix,tmask, pprefix,pmask)) return;
389 *tpming= 0;
390 }
391 if (!proto) printf(" %c%s", plus?'+':'-', what);
392 *any= 1;
393 }
394
395 static void permit_range(unsigned long prefix, unsigned long mask,
396 int plus, int localonly) {
397 int i, any;
398 char idbuf[40];
399
400 assert(!(prefix & ~mask));
401 any= 0;
402
403 permit_range_thing(localaddr,~0UL,"local", &localallow,&localpming,
404 prefix,mask, plus,&any);
405
406 if (!localonly) {
407 permit_range_thing(peeraddr,~0UL, "peer-addr", &peerallow,&peerpming,
408 prefix,mask, plus,&any);
409 for (i=0; i<nexroutes; i++) {
410 sprintf(idbuf,"route#%d",i);
411 permit_range_thing(exroutes[i].prefix,exroutes[i].mask, idbuf,
412 &exroutes[i].allow,&exroutes[i].pming,
413 prefix,mask, plus,&any);
414 }
415 }
416 if (!proto)
417 if (!any) fputs(" nothing",stdout);
418 }
419
420 static void pconfig(const char *configstr, int truncated);
421
422 static void pfile(const char *filename) {
423 FILE *file;
424 char buf[PATH_MAX];
425 int l, truncated, c;
426 struct pplace npp, *cpp;
427
428 for (cpp=cpplace; cpp; cpp=cpp->parent) {
429 if (!strcmp(cpp->filename,filename))
430 badusage("recursive configuration file `%s'",filename);
431 }
432
433 file= fopen(filename,"r");
434 if (!file)
435 badusage("cannot open configuration file `%s': %s", filename, strerror(errno));
436
437 if (!proto) printf("config file `%s':\n",filename);
438
439 npp.parent= cpplace;
440 npp.filename= filename;
441 npp.lineno= 0;
442 cpplace= &npp;
443
444 while (fgets(buf, sizeof(buf), file)) {
445 npp.lineno++;
446 l= strlen(buf);
447 if (!l) continue;
448
449 truncated= (buf[l-1] != '\n');
450 while (l>0 && isspace((unsigned char) buf[l-1])) l--;
451 if (!l) continue;
452 buf[l]= 0;
453
454 if (truncated) {
455 while ((c= getc(file)) != EOF && c != '\n');
456 if (c == EOF) break;
457 }
458
459 pconfig(buf,truncated);
460 }
461 if (ferror(file))
462 badusage("failed while reading configuration file: %s", strerror(errno));
463
464 cpplace= npp.parent;
465 }
466
467 static void pconfig(const char *configstr, int truncated) {
468 unsigned long fgid, tgid, pprefix, pmask;
469 int plen, localonly, plus, rangeix, delim;
470 char ptxt[ATXTLEN];
471 char whattxt[100];
472 const char *gidlist;
473
474 switch (configstr[0]) {
475 case '*':
476 permit_begin();
477 permit_range(0UL,0UL,1,0);
478 return;
479
480 case '#':
481 return;
482
483 case '/': case '.':
484 if (truncated) badusage("filename too long (`%.100s...')",configstr);
485 pfile(configstr);
486 return;
487
488 default:
489 if (!isdigit((unsigned char)configstr[0]))
490 badusage("unknown configuration directive");
491
492 fgid= eat_number(&configstr,"gid", 0,gidmaxval, ",",0);
493
494 if (!proto) printf(" %5lu", fgid);
495
496 gidlist= getenv("USERV_GID");
497 if (!gidlist) fatal("USERV_GID not set");
498 for (;;) {
499 if (!gidlist) {
500 if (!proto) printf(" no matching gid\n");
501 return;
502 }
503 tgid= eat_number(&gidlist,"userv-gid", 0,gidmaxval, " ",0);
504 if (tgid == fgid) break;
505 }
506
507 if (configstr[0] == '=') {
508 localonly= 1;
509 configstr++;
510 } else {
511 localonly= 0;
512 }
513
514 permit_begin();
515
516 rangeix= 0;
517 plus= 1;
518 switch (configstr[0]) {
519 case '-': plus= 0; /* fall through */
520 case '+': configstr++;
521 default:;
522 }
523
524 for (;;) {
525 sprintf(whattxt, "%s-prefix#%d",
526 plus ? "permitted" : "notpermitted",
527 rangeix);
528 eat_prefixmask(&configstr,whattxt, ",+-",&delim,
529 &pprefix,&pmask,&plen);
530 if (!configstr && truncated)
531 badusage("gid,prefix/len,... spec too long");
532
533 if (!proto)
534 printf(" %c%s/%d:", plus?'+':'-',ip2txt(pprefix,ptxt), plen);
535
536 permit_range(pprefix,pmask,plus,localonly);
537 if (delim==',') break;
538
539 plus= delim=='-' ? 0 : 1;
540 rangeix++;
541 }
542
543 putchar('\n');
544 return;
545 }
546 }
547
548 static void checkallow(int allow, const char *what,
549 const char *prefixtxt, const char *masktxt) {
550 if (allow) return;
551 fprintf(stderr,"userv-ipif service: access denied for %s, %s/%s\n",
552 what, prefixtxt, masktxt);
553 allallow= 0;
554 }
555
556 static void parseargs(int argc, const char *const *argv) {
557 unsigned long routeaddr, routemask;
558 const char *carg;
559 const char *const *cprotop;
560 int i;
561 char erwhatbuf[100], erwhatbuf2[100];
562
563 if (argc < NARGS+1) { badusage("too few arguments"); }
564 if (argc > NARGS+1) { badusage("too many arguments"); }
565
566 configstr= *++argv;
567
568 carg= *++argv;
569 if (strcmp(carg,"--")) badusage("separator argument `--' not found, got `%s'",carg);
570
571 carg= *++argv;
572 localaddr= eat_addr(&carg,"local-addr", ",",0);
573 peeraddr= eat_addr(&carg,"peer-addr", ",",0);
574 mtu= eat_number(&carg,"mtu", 576,65536, ",",0);
575 localallow= peerallow= 0;
576
577 if (!strcmp(carg,"debug")) {
578 proto= 0;
579 } else {
580 for (cprotop= protos_ok;
581 (proto= *cprotop) && strcmp(proto,carg);
582 cprotop++);
583 if (!proto) fatal("invalid protocol");
584 }
585
586 addrnet_mustdiffer("local-addr",localaddr,~0UL, "peer-addr",peeraddr,~0UL);
587
588 carg= *++argv;
589 if (strcmp(carg,"-")) {
590 for (nexroutes=0;
591 carg && *carg;
592 nexroutes++) {
593 if (nexroutes == MAXEXROUTES)
594 fatal("too many extra routes (only %d allowed)",MAXEXROUTES);
595 sprintf(erwhatbuf,"route#%d",nexroutes);
596
597 eat_prefixmask(&carg,erwhatbuf, ",",0, &routeaddr,&routemask,0);
598 if (routemask == ~0UL) {
599 addrnet_mustdiffer(erwhatbuf,routeaddr,routemask, "local-addr",localaddr,~0UL);
600 addrnet_mustdiffer(erwhatbuf,routeaddr,routemask, "peer-addr",peeraddr,~0UL);
601 }
602 for (i=0; i<nexroutes; i++) {
603 sprintf(erwhatbuf2,"route#%d",i);
604 addrnet_mustdiffer(erwhatbuf,routeaddr,routemask,
605 erwhatbuf2,exroutes[i].prefix,exroutes[i].mask);
606 }
607 exroutes[nexroutes].prefix= routeaddr;
608 exroutes[nexroutes].mask= routemask;
609 exroutes[nexroutes].allow= 0;
610 ip2txt(routeaddr,exroutes[nexroutes].prefixtxt);
611 ip2txt(routemask,exroutes[nexroutes].masktxt);
612 }
613 }
614
615 ip2txt(localaddr,localtxt);
616 ip2txt(peeraddr,peertxt);
617 }
618
619 static void checkpermit(void) {
620 int i;
621 char erwhatbuf[100];
622
623 allallow= 1;
624 checkallow(localallow,"local-addr", localtxt,"32");
625 checkallow(peerallow,"peer-addr", peertxt,"32");
626 for (i=0; i<nexroutes; i++) {
627 sprintf(erwhatbuf, "route#%d", i);
628 checkallow(exroutes[i].allow, erwhatbuf, exroutes[i].prefixtxt, exroutes[i].masktxt);
629 }
630 if (!allallow) fatal("access denied");
631 }
632
633 static void dumpdebug(void) __attribute__((noreturn));
634 static void dumpdebug(void) {
635 int i;
636 char erwhatbuf[100];
637
638 printf("protocol: debug\n"
639 "local: %08lx == %s\n"
640 "peer: %08lx == %s\n"
641 "mtu: %ld\n"
642 "routes: %d\n",
643 localaddr, localtxt,
644 peeraddr, peertxt,
645 mtu,
646 nexroutes);
647 for (i=0; i<nexroutes; i++) {
648 sprintf(erwhatbuf, "route#%d:", i);
649 printf("%-9s %08lx/%08lx == %s/%s\n",
650 erwhatbuf,
651 exroutes[i].prefix, exroutes[i].mask,
652 exroutes[i].prefixtxt, exroutes[i].masktxt);
653 }
654 if (ferror(stdout) || fclose(stdout)) sysfatal("flush stdout");
655 exit(0);
656 }
657
658
659 static void setsigmask(const sigset_t *ss) {
660 int r;
661
662 r= sigprocmask(SIG_SETMASK, ss, 0);
663 if (r) sysfatal("[un]block signals");
664 }
665
666 static void setsignals(void (*handler)(int), struct sigaction *sa, int chldflags) {
667 const int *signalp;
668 int r, sig;
669
670 sa->sa_handler= handler;
671 sa->sa_flags= 0;
672 for (signalp=signals; (sig=*signalp); signalp++) {
673 r= sigaction(sig, sa, 0); if (r) sysfatal("uncatch signal");
674 }
675 sa->sa_flags= chldflags;
676 r= sigaction(SIGCHLD, sa, 0); if (r) sysfatal("uncatch children");
677 }
678
679 static void infork(void) {
680 struct sigaction sa;
681
682 memset(&pids,0,sizeof(pids));
683 sigemptyset(&sa.sa_mask);
684 setsignals(SIG_DFL,&sa,0);
685 setsigmask(&emptyset);
686 undoslattach= 0;
687 }
688
689 static pid_t makesubproc(void (*entry)(void)) {
690 pid_t pid;
691
692 pid= fork(); if (pid == (pid_t)-1) sysfatal("fork for subprocess");
693 if (pid) return pid;
694
695 infork();
696 entry();
697 abort();
698 }
699
700 static int task(void) {
701 pid_t pid;
702
703 pid= fork();
704 if (pid == (pid_t)-1) sysfatal("fork for task");
705 if (!pid) { infork(); return 1; }
706
707 pids.byname.task= pid;
708 while (pids.byname.task) sigsuspend(&emptyset);
709 return 0;
710 }
711
712 static void mdup2(int fd1, int fd2, const char *what) {
713 int r;
714
715 for (;;) {
716 r= dup2(fd1,fd2); if (r==fd2) return;
717 if (r!=-1) fatal("dup2 in %s gave wrong answer %d instead of %d",what,r,fd2);
718 if (errno != EINTR) sysfatal("dup2 failed in %s",what);
719 }
720 }
721
722 static void sl_entry(void) {
723 mdup2(slpipe[1],1,"slattach child");
724 execlp("slattach", "slattach", "-v", "-L", "-p",proto, ptyname, (char*)0);
725 sysfatal("cannot exec slattach");
726 }
727
728 static void cin_entry(void) {
729 mdup2(ptmaster,1,"cat input child");
730 execlp("cat", "cat", (char*)0);
731 sysfatal("cannot exec cat input");
732 }
733
734 static void cout_entry(void) {
735 mdup2(ptmaster,0,"cat output child");
736 execlp("cat", "cat", (char*)0);
737 sysfatal("cannot exec cat output");
738 }
739
740 static void sighandler(int signum) {
741 pid_t pid;
742 int estatus, status;
743 const char *taskfail;
744
745 estatus= 4;
746
747 if (signum == SIGCHLD) {
748 for (;;) {
749 pid= waitpid(-1,&status,WNOHANG);
750 if (!pid || pid == (pid_t)-1) return;
751
752 if (pid == pids.byname.task) {
753 pids.byname.task= 0;
754 if (!status) return;
755 taskfail= "task";
756 } else if (pid == pids.byname.cin) {
757 pids.byname.cin= 0;
758 if (status) {
759 taskfail= "input cat";
760 } else {
761 taskfail= 0;
762 estatus= 0;
763 }
764 } else if (pid == pids.byname.cout) {
765 pids.byname.cout= 0;
766 taskfail= "output cat";
767 } else if (pid == pids.byname.sl) {
768 pids.byname.sl= 0;
769 taskfail= "slattach";
770 } else {
771 continue;
772 }
773 break;
774 }
775 if (taskfail) {
776 if (WIFEXITED(status)) {
777 fprintf(stderr,
778 "userv-ipif service: %s unexpectedly exited with exit status %d\n",
779 taskfail, WEXITSTATUS(status));
780 } else if (WIFSIGNALED(status)) {
781 fprintf(stderr,
782 "userv-ipif service: %s unexpectedly killed by signal %s%s\n",
783 taskfail, strsignal(WTERMSIG(status)),
784 WCOREDUMP(status) ? " (core dumped)" : "");
785 } else {
786 fprintf(stderr, "userv-ipif service: %s unexpectedly terminated"
787 " with unknown status code %d\n", taskfail, status);
788 }
789 }
790 } else {
791 fprintf(stderr,
792 "userv-ipif service: received signal %d, terminating\n",
793 signum);
794 }
795
796 terminate(estatus);
797 }
798
799 static void startup(void) {
800 int r;
801 struct sigaction sa;
802
803 sigfillset(&fullset);
804 sigemptyset(&emptyset);
805
806 ptmaster= getpt(); if (ptmaster==-1) sysfatal("allocate pty master");
807 r= grantpt(ptmaster); if (r) sysfatal("grab/grant pty slave");
808 ptyname= ptsname(ptmaster); if (!ptyname) sysfatal("get pty slave name");
809 r= chmod(ptyname,0600); if (r) sysfatal("chmod pty slave");
810 r= unlockpt(ptmaster); if (r) sysfatal("unlock pty");
811
812 sigfillset(&sa.sa_mask);
813 setsignals(sighandler,&sa,SA_NOCLDSTOP);
814 setsigmask(&fullset);
815 }
816
817 static void startslattach(void) {
818 static char ifnbuf[200];
819
820 FILE *piper;
821 int r, l, k;
822
823 r= pipe(slpipe); if (r) sysfatal("create pipe");
824 piper= fdopen(slpipe[0],"r"); if (!piper) sysfatal("fdopen pipe");
825
826 undoslattach= 1;
827 pids.byname.sl= makesubproc(sl_entry);
828
829 close(slpipe[1]);
830 setsigmask(&emptyset);
831 if (!fgets(ifnbuf,sizeof(ifnbuf),piper)) {
832 if (ferror(piper)) sysfatal("cannot read ifname from slattach");
833 else fatal("cannot read ifname from slattach");
834 }
835 setsigmask(&fullset);
836 l= strlen(ifnbuf);
837 if (l<=0 || ifnbuf[l-1] != '\n') fatal("slattach gave strange output `%s'",ifnbuf);
838 ifnbuf[l-1]= 0;
839 for (k=l; k>0 && ifnbuf[k-1]!=' '; k--);
840 ifname= ifnbuf+k;
841 }
842
843 static void netconfigure(void) {
844 char mtutxt[100];
845 int i;
846
847 if (task()) {
848 sprintf(mtutxt,"%lu",mtu);
849
850 execlp("ifconfig", "ifconfig", ifname, localtxt,
851 "netmask","255.255.255.255", "-broadcast", "pointopoint",peertxt,
852 "mtu",mtutxt, "up", (char*)0);
853 sysfatal("cannot exec ifconfig");
854 }
855
856 for (i=0; i<nexroutes; i++) {
857 if (task()) {
858 execlp("route","route", "add", "-net",exroutes[i].prefixtxt,
859 "netmask",exroutes[i].masktxt,
860 "gw",peertxt, "dev",ifname, (char*)0);
861 sysfatal("cannot exec route (for route)");
862 }
863 }
864 }
865
866 static void copydata(void) __attribute__((noreturn));
867 static void copydata(void) {
868 int r;
869
870 pids.byname.cin= makesubproc(cin_entry);
871 for (;;) {
872 r= write(1, "\300", 1); if (r==1) break;
873 assert(r==-1); if (errno != EINTR) sysfatal("send initial delim to confirm");
874 }
875 pids.byname.cout= makesubproc(cout_entry);
876
877 for (;;) sigsuspend(&emptyset);
878 }
879
880 int main(int argc, const char *const *argv) {
881 parseargs(argc,argv);
882 pconfig(configstr,0);
883 checkpermit();
884 if (!proto) dumpdebug();
885
886 startup();
887 startslattach();
888 netconfigure();
889 copydata();
890 }