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