chiark / gitweb /
ipif: Permit specifying interface name, if * is allowed
[userv-utils.git] / 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>][,[<ifnamepat>]]]
34  *
35  *      As for slattach.  The only supported protocol is slip.
36  *      Alternatively, set to `debug' to print debugging info and
37  *      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 in a file such as
52  * /etc/userv/ipif-networks, or the single trusted argument supplied
53  * on the service program 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  *      Only `*' permits interface name patterns other than the default
86  *      value of `userv%d'.
87  *
88  *   #...
89  *
90  *      Comment.  Blank lines are also ignored.
91  *
92  *   NB: Permission is granted if _any_ config entry matches the request.
93  *
94  * The service program should be run from userv with no-disconnect-hup.
95  */
96 /*
97  * This file is part of ipif, part of userv-utils
98  *
99  * Copyright 1996-2013 Ian Jackson <ijackson@chiark.greenend.org.uk>
100  * Copyright 1998 David Damerell <damerell@chiark.greenend.org.uk>
101  * Copyright 1999,2003
102  *    Chancellor Masters and Scholars of the University of Cambridge
103  * Copyright 2010 Tony Finch <fanf@dotat.at>
104  *
105  * This is free software; you can redistribute it and/or modify it
106  * under the terms of the GNU General Public License as published by
107  * the Free Software Foundation; either version 3 of the License, or
108  * (at your option) any later version.
109  *
110  * This program is distributed in the hope that it will be useful, but
111  * WITHOUT ANY WARRANTY; without even the implied warranty of
112  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
113  * General Public License for more details.
114  *
115  * You should have received a copy of the GNU General Public License
116  * along with userv-utils; if not, see http://www.gnu.org/licenses/.
117  */
118
119 #include <stdio.h>
120 #include <string.h>
121 #include <stdlib.h>
122 #include <assert.h>
123 #include <errno.h>
124 #include <stdarg.h>
125 #include <ctype.h>
126 #include <limits.h>
127 #include <signal.h>
128 #include <unistd.h>
129 #include <stdint.h>
130 #include <poll.h>
131 #include <stddef.h>
132
133 #include <sys/types.h>
134 #include <sys/wait.h>
135 #include <sys/stat.h>
136
137 #include <sys/types.h>
138 #include <sys/ioctl.h>
139 #include <sys/socket.h>
140
141 #include <sys/stat.h>
142 #include <fcntl.h>
143
144 #include <linux/if.h>
145 #include <linux/if_tun.h>
146
147 #define NARGS 4
148 #define MAXEXROUTES 50
149 #define ATXTLEN 16
150
151 static const unsigned long gidmaxval= (unsigned long)((gid_t)-2);
152 static const char *const protos_ok[]= { "slip", 0 };
153 static const int signals[]= { SIGHUP, SIGINT, SIGTERM, 0 };
154 static const char default_ifnamepat[]= "userv%d";
155
156 static const char *configstr, *proto;
157 static unsigned long localaddr, peeraddr, mtu;
158 static int localpming, peerpming;
159 static int localallow, peerallow, ifnameallow, allallow;
160 static char *ifnamepat;
161 static int nexroutes;
162 static struct exroute {
163   unsigned long prefix, mask;
164   int allow, pming;
165   char prefixtxt[ATXTLEN], masktxt[ATXTLEN];
166 } exroutes[MAXEXROUTES];
167
168 static char localtxt[ATXTLEN];
169 static char peertxt[ATXTLEN];
170
171 static struct pplace {
172   struct pplace *parent;
173   const char *filename;
174   int lineno;
175 } *cpplace;
176
177
178 static int tunfd;
179 static char *ifname;
180
181
182 static void terminate(int estatus) {
183   exit(estatus);
184 }
185
186
187 static void fatal(const char *fmt, ...)
188      __attribute__((format(printf,1,2)));
189 static void fatal(const char *fmt, ...) {
190   va_list al;
191   va_start(al,fmt);
192
193   fputs("userv-ipif service: fatal error: ",stderr);
194   vfprintf(stderr, fmt, al);
195   putc('\n',stderr);
196   terminate(8);
197 }
198   
199 static void sysfatal(const char *fmt, ...)
200      __attribute__((format(printf,1,2)));
201 static void sysfatal(const char *fmt, ...) {
202   va_list al;
203   int e;
204
205   e= errno;
206   va_start(al,fmt);
207
208   fputs("userv-ipif service: fatal system error: ",stderr);
209   vfprintf(stderr, fmt, al);
210   fprintf(stderr,": %s\n", strerror(e));
211   terminate(12);
212 }
213
214
215 static void badusage(const char *fmt, ...)
216      __attribute__((format(printf,1,2)));
217 static void badusage(const char *fmt, ...) {
218   va_list al;
219   struct pplace *cpp;
220   
221   if (cpplace) {
222     fprintf(stderr,
223             "userv-ipif service: %s:%d: ",
224             cpplace->filename, cpplace->lineno);
225   } else {
226     fputs("userv-ipif service: invalid usage: ",stderr);
227   }
228   va_start(al,fmt);
229   vfprintf(stderr, fmt, al);
230   putc('\n',stderr);
231
232   if (cpplace) {
233     for (cpp=cpplace->parent; cpp; cpp=cpp->parent) {
234       fprintf(stderr,
235               "userv-ipif service: %s:%d: ... in file included from here\n",
236               cpp->filename, cpp->lineno);
237     }
238   }
239   terminate(16);
240 }
241
242 static char *ip2txt(unsigned long addr, char *buf) {
243   sprintf(buf, "%lu.%lu.%lu.%lu",
244           (addr>>24) & 0x0ff,
245           (addr>>16) & 0x0ff,
246           (addr>>8) & 0x0ff,
247           (addr) & 0x0ff);
248   return buf;
249 }
250
251 static unsigned long eat_number(const char **argp, const char *what,
252                                 unsigned long min, unsigned long max,
253                                 const char *endchars, int *endchar_r) {
254   /* If !endchars then the endchar must be a nul, otherwise it may be
255    * a nul (resulting in *argp set to 0) or something else (*argp set
256    * to point to after delim, *endchar_r set to delim).
257    * *endchar_r may be 0.
258    */
259   unsigned long rv;
260   char *ep;
261   int endchar;
262
263   if (!*argp) { badusage("missing number %s",what); }
264   rv= strtoul(*argp,&ep,0);
265   if ((endchar= *ep)) {
266     if (!endchars) badusage("junk after number %s",what);
267     if (!strchr(endchars,endchar))
268       badusage("invalid character or delimiter `%c' in or after number, %s:"
269                " expected %s (or none?)", endchar,what,endchars);
270     *argp= ep+1;
271   } else {
272     *argp= 0;
273   }
274   if (endchar_r) *endchar_r= endchar;
275   if (rv < min || rv > max) badusage("number %s value %lu out of range %lu..%lu",
276                                      what, rv, min, max);
277   return rv;
278 }
279
280 static int addrnet_overlap(unsigned long p1, unsigned long m1,
281                            unsigned long p2, unsigned long m2) {
282   unsigned long mask;
283
284   mask= m1&m2;
285   return (p1 & mask) == (p2 & mask);
286 }
287
288 static void addrnet_mustdiffer(const char *w1, unsigned long p1, unsigned long m1,
289                                const char *w2, unsigned long p2, unsigned long m2) {
290   if (!addrnet_overlap(p1,m1,p2,m2)) return;
291   badusage("%s %08lx/%08lx overlaps/clashes with %s %08lx/%08lx",
292            w1,p1,m1, w2,p2,m2);
293 }
294   
295 static unsigned long eat_addr(const char **argp, const char *what,
296                               const char *endchars, int *endchar_r) {
297   char whatbuf[100];
298   unsigned long rv;
299   int i;
300
301   for (rv=0, i=0;
302        i<4;
303        i++) {
304     rv <<= 8;
305     sprintf(whatbuf,"%s byte #%d",what,i);
306     rv |= eat_number(argp,whatbuf, 0,255, i<3 ? "." : endchars, endchar_r);
307   }
308
309   return rv;
310 }
311
312 static void eat_prefixmask(const char **argp, const char *what,
313                            const char *endchars, int *endchar_r,
314                            unsigned long *prefix_r, unsigned long *mask_r, int *len_r) {
315   /* mask_r and len_r may be 0 */
316   char whatbuf[100];
317   int len;
318   unsigned long prefix, mask;
319
320   prefix= eat_addr(argp,what, "/",0);
321   sprintf(whatbuf,"%s length",what);
322   len= eat_number(argp,whatbuf, 0,32, endchars,endchar_r);
323
324   mask= len ? (~0UL << (32-len)) : 0UL;
325   if (prefix & ~mask) badusage("%s prefix %08lx not fully contained in mask %08lx",
326                                what,prefix,mask);
327   *prefix_r= prefix;
328   if (mask_r) *mask_r= mask;
329   if (len_r) *len_r= len;
330 }
331
332 static char *eat_optionalstr(const char **argp,
333                              const char *what,
334                              const char *def) {
335   ptrdiff_t len;
336   const char *start= *argp;
337   if (!start) {
338     len = 0;
339   } else {
340     const char *comma= strchr(start, ',');
341     if (comma) {
342       len= comma - start;
343       *argp= comma + 1;
344     } else {
345       len= strlen(start);
346       *argp= 0;
347     }
348   }
349   if (!len) {
350     start= def;
351     len= strlen(def);
352   }
353   char *r = malloc(len+1);
354   if (!r) sysfatal("malloc for command line string");
355   memcpy(r,start,len);
356   r[len]= 0;
357   return r;
358 }
359
360 static int addrnet_isin(unsigned long prefix, unsigned long mask,
361                         unsigned long mprefix, unsigned long mmask) {
362   return  !(~mask & mmask)  &&  (prefix & mmask) == mprefix;
363 }
364
365 /* Totally hideous algorithm for parsing the config file lines.
366  * For each config file line, we first see if its gid applies.  If not
367  * we skip it.  Otherwise, we do
368  *  permit_begin
369  *     which sets <foo>pming to 1
370  * for each range.  <foo>pming may be 0 if we've determined that
371  * this line does not apply to <foo>.
372  *  permit_range
373  *     which calls permit_range_thing for each <foo>
374  *        which checks to see if <foo> is inside the relevant
375  *        range (for +) or overlaps it (for -) and updates
376  *        <foo>allow and <foo>pming.
377  */
378
379 static void permit_begin(void) {
380   int i;
381   
382   localpming= peerpming= 1;
383   for (i=0; i<nexroutes; i++) exroutes[i].pming= 1;
384 }
385
386 static void permit_range_thing(unsigned long tprefix, unsigned long tmask,
387                                const char *what, int *tallow, int *tpming,
388                                unsigned long pprefix, unsigned long pmask,
389                                int plus, int *any) {
390   if (plus) {
391     if (!addrnet_isin(tprefix,tmask, pprefix,pmask)) return;
392     if (*tpming) *tallow= 1;
393   } else {
394     if (!addrnet_overlap(tprefix,tmask, pprefix,pmask)) return;
395     *tpming= 0;
396   }
397   if (!proto) printf(" %c%s", plus?'+':'-', what);
398   *any= 1;
399 }
400
401 static void permit_range(unsigned long prefix, unsigned long mask,
402                          int plus, int localonly) {
403   int i, any;
404   char idbuf[40];
405   
406   assert(!(prefix & ~mask));
407   any= 0;
408
409   permit_range_thing(localaddr,~0UL,"local", &localallow,&localpming,
410                      prefix,mask, plus,&any);
411
412   if (!localonly) {
413     permit_range_thing(peeraddr,~0UL, "peer-addr", &peerallow,&peerpming,
414                        prefix,mask, plus,&any);
415     for (i=0; i<nexroutes; i++) {
416       sprintf(idbuf,"route#%d",i);
417       permit_range_thing(exroutes[i].prefix,exroutes[i].mask, idbuf,
418                          &exroutes[i].allow,&exroutes[i].pming,
419                          prefix,mask, plus,&any);
420     }
421   }
422   if (!proto)
423     if (!any) fputs(" nothing",stdout);
424 }
425
426 static void pconfig(const char *configstr, int truncated);
427
428 static void pfile(const char *filename) {
429   FILE *file;
430   char buf[PATH_MAX];
431   int l, truncated, c;
432   struct pplace npp, *cpp;
433
434   for (cpp=cpplace; cpp; cpp=cpp->parent) {
435     if (!strcmp(cpp->filename,filename))
436       badusage("recursive configuration file `%s'",filename);
437   }
438
439   file= fopen(filename,"r");
440   if (!file)
441     badusage("cannot open configuration file `%s': %s", filename, strerror(errno));
442
443   if (!proto) printf("config file `%s':\n",filename);
444
445   npp.parent= cpplace;
446   npp.filename= filename;
447   npp.lineno= 0;
448   cpplace= &npp;
449
450   while (fgets(buf, sizeof(buf), file)) {
451     npp.lineno++;
452     l= strlen(buf);
453     if (!l) continue;
454
455     truncated= (buf[l-1] != '\n');
456     while (l>0 && isspace((unsigned char) buf[l-1])) l--;
457     if (!l) continue;
458     buf[l]= 0;
459
460     if (truncated) {
461       while ((c= getc(file)) != EOF && c != '\n');
462       if (c == EOF) break;
463     }
464
465     pconfig(buf,truncated);
466   }
467   if (ferror(file))
468     badusage("failed while reading configuration file: %s", strerror(errno));
469
470   cpplace= npp.parent;
471 }
472
473 static void pconfig(const char *configstr, int truncated) {
474   unsigned long fgid, tgid, pprefix, pmask;
475   int plen, localonly, plus, rangeix, delim;
476   char ptxt[ATXTLEN];
477   char whattxt[100];
478   const char *gidlist;
479   
480   switch (configstr[0]) {
481   case '*':
482     permit_begin();
483     permit_range(0UL,0UL,1,0);
484     ifnameallow= 1;
485     return;
486     
487   case '#':
488     return;
489     
490   case '/': case '.':
491     if (truncated) badusage("filename too long (`%.100s...')",configstr);
492     pfile(configstr);
493     return;
494     
495   default:
496     if (!isdigit((unsigned char)configstr[0]))
497       badusage("unknown configuration directive");
498     
499     fgid= eat_number(&configstr,"gid", 0,gidmaxval, ",",0);
500
501     if (!proto) printf(" %5lu", fgid);
502
503     gidlist= getenv("USERV_GID");
504     if (!gidlist) fatal("USERV_GID not set");
505     for (;;) {
506       if (!gidlist) {
507         if (!proto) printf(" no matching gid\n");
508         return;
509       }
510       tgid= eat_number(&gidlist,"userv-gid", 0,gidmaxval, " ",0);
511       if (tgid == fgid) break;
512     }
513
514     if (configstr[0] == '=') {
515       localonly= 1;
516       configstr++;
517     } else {
518       localonly= 0;
519     }
520
521     permit_begin();
522
523     rangeix= 0;
524     plus= 1;
525     switch (configstr[0]) {
526     case '-': plus= 0;     /* fall through */
527     case '+': configstr++;
528     default:;
529     }
530
531     for (;;) {
532       sprintf(whattxt, "%s-prefix#%d",
533               plus ? "permitted" : "notpermitted",
534               rangeix);
535       eat_prefixmask(&configstr,whattxt, ",+-",&delim,
536                      &pprefix,&pmask,&plen);
537       if (!configstr && truncated)
538         badusage("gid,prefix/len,... spec too long");
539
540       if (!proto)
541         printf("  %c%s/%d:", plus?'+':'-',ip2txt(pprefix,ptxt), plen);
542
543       permit_range(pprefix,pmask,plus,localonly);
544       if (delim==',') break;
545
546       plus= delim=='-' ? 0 : 1;
547       rangeix++;
548     }
549
550     putchar('\n');
551     return;
552   }
553 }
554
555 static void checkallow(int allow, const char *what,
556                        const char *prefixtxt, const char *masktxt) {
557   if (allow) return;
558   fprintf(stderr,"userv-ipif service: access denied for %s, %s/%s\n",
559           what, prefixtxt, masktxt);
560   allallow= 0;
561 }
562
563 static void parseargs(int argc, const char *const *argv) {
564   unsigned long routeaddr, routemask;
565   const char *carg;
566   const char *const *cprotop;
567   int i;
568   char erwhatbuf[100], erwhatbuf2[100];
569   
570   if (argc < NARGS+1) { badusage("too few arguments"); }
571   if (argc > NARGS+1) { badusage("too many arguments"); }
572
573   configstr= *++argv;
574   
575   carg= *++argv;
576   if (strcmp(carg,"--")) badusage("separator argument `--' not found, got `%s'",carg);
577
578   carg= *++argv;
579   localaddr= eat_addr(&carg,"local-addr", ",",0);
580   peeraddr= eat_addr(&carg,"peer-addr", ",",0);
581   mtu= eat_number(&carg,"mtu", 576,65536, ",",0);
582   localallow= peerallow= 0;
583
584   char *protostr= eat_optionalstr(&carg,"protocol","slip");
585   if (!strcmp(protostr,"debug")) {
586     proto= 0;
587   } else {
588     for (cprotop= protos_ok;
589          (proto= *cprotop) && strcmp(proto,protostr);
590          cprotop++);
591     if (!proto) fatal("invalid protocol");
592   }
593
594   ifnamepat= eat_optionalstr(&carg,"ifname pattern",default_ifnamepat);
595   
596   addrnet_mustdiffer("local-addr",localaddr,~0UL, "peer-addr",peeraddr,~0UL);
597   
598   carg= *++argv;
599   if (strcmp(carg,"-")) {
600     for (nexroutes=0;
601          carg && *carg;
602          nexroutes++) {
603       if (nexroutes == MAXEXROUTES)
604         fatal("too many extra routes (only %d allowed)",MAXEXROUTES);
605       sprintf(erwhatbuf,"route#%d",nexroutes);
606     
607       eat_prefixmask(&carg,erwhatbuf, ",",0, &routeaddr,&routemask,0);
608       if (routemask == ~0UL) {
609         addrnet_mustdiffer(erwhatbuf,routeaddr,routemask, "local-addr",localaddr,~0UL);
610         addrnet_mustdiffer(erwhatbuf,routeaddr,routemask, "peer-addr",peeraddr,~0UL);
611       }
612       for (i=0; i<nexroutes; i++) {
613         sprintf(erwhatbuf2,"route#%d",i);
614         addrnet_mustdiffer(erwhatbuf,routeaddr,routemask,
615                            erwhatbuf2,exroutes[i].prefix,exroutes[i].mask);
616       }
617       exroutes[nexroutes].prefix= routeaddr;
618       exroutes[nexroutes].mask= routemask;
619       exroutes[nexroutes].allow= 0;
620       ip2txt(routeaddr,exroutes[nexroutes].prefixtxt);
621       ip2txt(routemask,exroutes[nexroutes].masktxt);
622     }
623   }
624
625   ip2txt(localaddr,localtxt);
626   ip2txt(peeraddr,peertxt);
627 }
628
629 static void checkpermit(void) {
630   int i;
631   char erwhatbuf[100];
632   
633   allallow= 1;
634   checkallow(localallow,"local-addr", localtxt,"32");
635   checkallow(peerallow,"peer-addr", peertxt,"32");
636   for (i=0; i<nexroutes; i++) {
637     sprintf(erwhatbuf, "route#%d", i);
638     checkallow(exroutes[i].allow, erwhatbuf, exroutes[i].prefixtxt, exroutes[i].masktxt);
639   }
640   if (!strcmp(ifnamepat,default_ifnamepat))
641     ifnameallow= 1;
642   if (!ifnameallow) {
643     fprintf(stderr,
644             "userv-ipif service: access denied for interface name %s\n",
645             ifnamepat);
646     allallow= 0;
647   }
648   if (!allallow) fatal("access denied");
649 }
650
651 static void dumpdebug(void) __attribute__((noreturn));
652 static void dumpdebug(void) {
653   int i;
654   char erwhatbuf[100];
655   
656   printf("protocol: debug\n"
657          "local:    %08lx == %s\n"
658          "peer:     %08lx == %s\n"
659          "mtu:      %ld\n"
660          "routes:   %d\n",
661          localaddr, localtxt,
662          peeraddr, peertxt,
663          mtu,
664          nexroutes);
665   for (i=0; i<nexroutes; i++) {
666     sprintf(erwhatbuf, "route#%d:", i);
667     printf("%-9s %08lx/%08lx == %s/%s\n",
668            erwhatbuf,
669            exroutes[i].prefix, exroutes[i].mask,
670            exroutes[i].prefixtxt, exroutes[i].masktxt);
671   }
672   if (ferror(stdout) || fclose(stdout)) sysfatal("flush stdout");
673   exit(0);
674 }
675
676
677 static int task(const char *desc) {
678   pid_t pid, pidr;
679   int status;
680
681   pid= fork();
682   if (pid == (pid_t)-1) sysfatal("fork for task");
683   if (!pid) return 1;
684
685   for (;;) {
686     pidr= waitpid(pid,&status,0);
687     if (pidr!=(pid_t)-1) break;
688     if (errno==EINTR) continue;
689     sysfatal("waitpid for task");
690   }
691   assert(pidr==pid);
692
693   if (WIFEXITED(status)) {
694     if (WEXITSTATUS(status))
695       fatal("userv-ipif service: %s exited with error exit status %d\n",
696             desc, WEXITSTATUS(status));
697   } else if (WIFSIGNALED(status)) {
698     fatal("userv-ipif service: %s died due to signal %s%s\n",
699           desc, strsignal(WTERMSIG(status)),
700           WCOREDUMP(status) ? " (core dumped)" : "");
701   } else {
702     fatal("userv-ipif service: %s unexpectedly terminated"
703           " with unknown status code %d\n", desc, status);
704   }
705
706   return 0;
707 }
708
709 static void createif(void) {
710   struct ifreq ifr;
711   int r;
712
713   memset(&ifr,0,sizeof(ifr));
714   ifr.ifr_flags= IFF_TUN | IFF_NO_PI;
715
716   assert(sizeof(ifr.ifr_name) >= strlen(ifnamepat)+1);
717   strcpy(ifr.ifr_name, ifnamepat);
718
719   tunfd= open("/dev/net/tun", O_RDWR);
720   if (!tunfd) sysfatal("open /dev/net/tun");
721
722   r= fcntl(tunfd, F_GETFD);
723   if (r==-1) sysfatal("fcntl(tunfd,F_GETFD)");
724   r= fcntl(tunfd, F_SETFD, r|FD_CLOEXEC);
725   if (r==-1) sysfatal("fcntl(tunfd,F_SETFD,|FD_CLOEXEC)");
726
727   r= ioctl(tunfd, TUNSETIFF, (void*)&ifr);
728   if (r) sysfatal("ioctl TUNSETIFF");
729
730   /* ifr.ifr_name might not be null-terminated.  crazy abi. */
731   ifname= malloc(sizeof(ifr.ifr_name)+1);
732   if (!ifname) sysfatal("malloc for interface name");
733   memcpy(ifname, ifr.ifr_name, sizeof(ifr.ifr_name));
734   ifname[sizeof(ifr.ifr_name)]= 0;
735 }
736
737 static void netconfigure(void) {
738   char mtutxt[100];
739   int i;
740
741   if (task("ifconfig")) {
742     sprintf(mtutxt,"%lu",mtu);
743   
744     execlp("ifconfig", "ifconfig", ifname, localtxt,
745            "netmask","255.255.255.255", "pointopoint",peertxt, "-broadcast",
746            "mtu",mtutxt, "up", (char*)0);
747     sysfatal("cannot exec ifconfig");
748   }
749
750   for (i=0; i<nexroutes; i++) {
751     if (task("route")) {
752       execlp("route","route", "add", "-net",exroutes[i].prefixtxt,
753              "netmask",exroutes[i].masktxt,
754              "gw",peertxt, "dev",ifname, (char*)0);
755       sysfatal("cannot exec route (for route)");
756     }
757   }
758 }
759
760 static void setnonblock(int fd) {
761   int r;
762   r= fcntl(fd,F_GETFL); 
763   if (r==-1) sysfatal("fcntl F_GETFL");
764   r= fcntl(fd,F_SETFL, r|O_NONBLOCK);
765   if (r==-1) sysfatal("fcntl F_SETFL O_NONBLOCK");
766 }
767
768 static void rx_packet(const uint8_t *packet, int len) {
769   if (!len)
770     return;
771   for (;;) {
772     int r= write(tunfd, packet, len);
773     if (r<0) {
774       if (errno==EINTR) continue;
775       if (errno==EAGAIN || errno==ENOMEM) return; /* oh well */
776       sysfatal("error writing packet to tun (transmitting)");
777     }
778     assert(r==len);
779     return;
780   }
781 }
782
783 static int output_waiting, input_waiting;
784
785 #define SLIP_END     0300
786 #define SLIP_ESC     0333
787 #define SLIP_ESC_END 0334
788 #define SLIP_ESC_ESC 0335
789
790 static void more_rx_data(uint8_t *input_buf, uint8_t *output_buf) {
791   /* we make slip_data never contain continuation of a packet */
792   /* input_buf is passed as a parameter since it's in copydata's stack frame */
793   static int scanned;
794   static int output_len;
795
796   uint8_t *op= output_buf + output_len;
797   const uint8_t *ip= input_buf + scanned;
798   const uint8_t *ip_end= input_buf + input_waiting;
799   int eaten= 0;
800   
801   for (;;) {
802     if (ip>=ip_end) break;
803     uint8_t c= *ip++;
804     if (c==SLIP_END) {
805       rx_packet(output_buf, op-output_buf);
806       op= output_buf;
807       eaten= ip - input_buf;
808       continue;
809     }
810     if (c==SLIP_ESC) {
811       if (ip>=ip_end) { /* rescan this when there's more */ ip--; break; }
812       c= *ip++;
813       if (c==SLIP_ESC_END) c=SLIP_END;
814       else if (c==SLIP_ESC_ESC) c=SLIP_ESC;
815       else fatal("unexpected byte 0%o after SLIP_ESC",c);
816     }
817     if (op == output_buf+mtu)
818       fatal("SLIP packet exceeds mtu");
819     *op++= c;
820   }
821
822   output_len= op - output_buf;
823   scanned= ip - input_buf;
824
825   input_waiting -= eaten;
826   memmove(input_buf, input_buf+eaten, input_waiting);
827   scanned -= eaten;
828 }
829
830 static void tx_packet(uint8_t *output_buf, const uint8_t *ip, int inlen) {
831   /* output_buf is passed as a parameter since it's in copydata's stack frame */
832   assert(!output_waiting);
833   uint8_t *op= output_buf;
834
835   *op++= SLIP_END;
836   while (inlen-- >0) {
837     uint8_t c= *ip++;
838     if (c==SLIP_END) { *op++= SLIP_ESC; *op++= SLIP_ESC_END; }
839     else if (c==SLIP_ESC) { *op++= SLIP_ESC; *op++= SLIP_ESC_ESC; }
840     else *op++= c;
841   }
842   *op++= SLIP_END;
843   assert(op <= output_buf + mtu*2+2);
844
845   output_waiting= op - output_buf;
846 }
847
848 static void copydata(void) __attribute__((noreturn));
849 static void copydata(void) {
850   uint8_t output_buf[mtu*2+2];
851   uint8_t input_buf[mtu*2+2];
852   uint8_t rx_packet_buf[mtu];
853
854   int r, i;
855
856   struct pollfd polls[3];
857   memset(polls, 0, sizeof(polls));
858   
859   polls[0].fd= 0;      polls[0].events= POLLIN;
860   polls[1].fd= 1;
861   polls[2].fd= tunfd;
862
863   /* We don't do flow control on input packets; instead, we just throw
864    * away ones which the kernel doesn't accept.  So we always poll for
865    * those.
866    *
867    * Output packets we buffer, so we poll only as appropriate for those.
868    */
869
870   /* Start by transmitting one END byte to say we're ready. */
871   output_buf[0]= SLIP_END;
872   output_waiting= 1;
873
874   for (;;) {
875     if (output_waiting) {
876       r= write(1, output_buf, output_waiting);
877       if (r<0) {
878         if (errno==EINTR) continue;
879         if (errno!=EAGAIN)
880           sysfatal("error writing SLIP output (packets being received)");
881       } else {
882         assert(r>0);
883         output_waiting -= r;
884         memmove(output_buf, output_buf+r, output_waiting);
885       }
886     }
887     if (output_waiting) {
888       polls[1].events |= POLLOUT;
889       polls[2].events &= ~POLLIN;
890     } else {
891       polls[1].events &= ~POLLOUT;
892       polls[2].events |= POLLIN;
893     }
894     r= poll(polls,3,-1);
895
896     if (r<0) {
897       if (errno==EINTR) continue;
898       sysfatal("poll() failed");
899     }
900     assert(r>0); /* we used an infinite timeout */
901
902     for (i=0; i<sizeof(polls)/sizeof(polls[0]); i++)
903       if (polls[i].revents & ~polls[i].events)
904         fatal("unexpected revents 0x%x for fd=%d",
905               polls[i].revents, polls[i].fd);
906
907     if (polls[0].events & POLLIN) {
908       int want= sizeof(input_buf) - input_waiting;
909       if (want<0) fatal("incoming packet necessarily exceeds MTU");
910       r= read(0, input_buf + input_waiting, want);
911       if (r>0) {
912         input_waiting += r;
913         assert(input_waiting <= sizeof(input_buf));
914         more_rx_data(input_buf, rx_packet_buf);
915       } else if (r==0) {
916         terminate(0);
917       } else {
918         if (!(errno==EINTR || errno==EAGAIN))
919           sysfatal("error reading input SLIP data (packets to transmit)");
920       }
921     }
922
923     /* We handle what would be (polls[1].events & POLLOUT) above,
924      * unconditionally.  That eliminates the need to poll in the usual case */
925       
926     if (polls[2].events & POLLIN) {
927       uint8_t packet_buf[mtu];
928       r= read(tunfd, packet_buf, mtu);
929       if (r>0) {
930         tx_packet(output_buf, packet_buf, r);
931       } else {
932         assert(r<0);
933         if (!(errno==EAGAIN || errno==EWOULDBLOCK))
934           sysfatal("error reading packet (being transmitted) from tun");
935       }
936     }
937   } 
938 }
939
940 int main(int argc, const char *const *argv) {
941   parseargs(argc,argv);
942   pconfig(configstr,0);
943   checkpermit();
944   if (!proto) dumpdebug();
945
946   createif();
947   netconfigure();
948   setnonblock(tunfd);
949   setnonblock(0);
950   setnonblock(1);
951   copydata();
952 }