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