chiark / gitweb /
Changes to make it appear to work on chiark
[userv-utils.git] / ipif / service.c
index b76c75473b04a5a1e98129c7997fc6f750beec92..08b0ed9f61a40859d37f531231940433db77d76c 100644 (file)
 /*
- * userv service (or standalone program)
- * for per-user IP subranges.
+ * userv service (or standalone program) for per-user IP subranges.
+ *
+ * When invoked appropriately, it creates a point-to-point network
+ * interface with specified parameters.  It arranges for packets sent out
+ * via that interface by the kernel to appear on its own stdout in SLIP or
+ * CSLIP encoding, and packets injected into its own stdin to be given to
+ * the kernel as if received on that interface.  Optionally, additional
+ * routes can be set up to arrange for traffic for other address ranges to
+ * be routed through the new interface.
+ *
+ * This is the service program, which is invoked as root from userv (or may
+ * be invoked firectly).
+ *
+ * Its arguments are supposed to be, in order, as follows:
+ *
+ *  The first two arguments are usually supplied by the userv
+ *  configuration.  See the file `ipif/ipif' in the source tree, which
+ *  is installed in /etc/userv/services.d/ipif by `make install':
  *
- * This is invoked as root, directly from userv.
- * Its arguments are supposed to be, in order:
  *  <config>
- *      Specifies address ranges and gids which own them.
- *  --  Indicates that the remaining arguments are user-supplied
- *      and therefore untrusted.
+ *
+ *      Specifies address ranges and gids which own them.  The default
+ *      configuration supplies /etc/userv/ipif-networks, which is then read
+ *      for a list of entries, one per line.
+ *
+ *  --
+ *      Serves to separate the user-supplied and therefore untrusted
+ *      arguments from the trusted first argument.
+ *
+ *  The remaining arguments are supplied by the (untrusted) caller:
+ *
  *  <local-addr>,<peer-addr>,<mtu>,<proto>
+ *
  *      As for slattach.  Supported protocols are slip, cslip, and
- *      adaptive.  Alternatively, set to `debug' to print debugging
- *      info.  <local-addr> is address of the interface on chiark;
- *      <peer-addr> is the address of the point-to-point peer.
+ *      adaptive.  Alternatively, set to `debug' to print debugging info
+ *      and exit.  <local-addr> is address of the interface to be created
+ *      on the local system; <peer-addr> is the address of the
+ *      point-to-point peer.  They must be actual addresses (not
+ *      hostnames).
+ *
  *  <prefix>/<mask>,<prefix>/<mask>,...
- *      List of additional routes to add for this interface.
- *      May be the empty argument.
  *
- * <config> is either
- *    <gid>,<prefix>/<len>[,<junk>]
- *      indicating that that gid may allocate addresses in
- *      the relevant subspace (<junk> is ignored)
- * or #...
- *      which is a comment
- * or /<config-file-name> or ./<config-file-name> or ../<config-file-name>
- *      which refers to a file which contains lines which
- *      are each <config>
- * or *
- *      which means that anything is permitted
- * 
- * Should be run from userv with no-disconnect-hup.
+ *      List of additional routes to add for this interface.  routes will
+ *      be set up on the local system arranging for packets for those
+ *      networks to be sent via the created interface.  <prefix> must be an
+ *      IPv4 address, and mask must be an integer (dotted-quad masks are
+ *      not supported).  If no additional routes are to be set up, use `-'
+ *      or supply an empty argument.
+ *
+ * Each <config> item - whether a line file such as
+ * /etc/userv/ipif-networks, or supplied on the service program
+ * command line - is one of:
+ *
+ *   /<config-file-name>
+ *   ./<config-file-name>
+ *   ../<config-file-name>
+ *
+ *      Reads a file which contains lines which are each <config>
+ *      items.
+ *
+ *   <gid>,[=][-|+]<prefix>/<len>(-|+<prefix>/<len>...)[,<junk>]
+ *
+ *      Indicates that <gid> may allocate addresses in the relevant address
+ *      range (<junk> is ignored).  <gid> must be numeric.  To specify a
+ *      single host address, you must specify a mask of /32.  If `=' is
+ *      specified then the specific subrange is only allowed for the local
+ *      endpoint address, but not for remote addresses.
+ *
+ *      More than one range may be given, with each range prefixed
+ *      by + or -.  In this case each address range in the rule will
+ *      scanned in order, and the first range in the rule that matches
+ *      any desired rule will count: if that first matching range is
+ *      prefixed by `+' (or nothing) then the rule applies, if it
+ *      is prefixed by `-' (or nothing matches), the rule does not.
+ *
+ *   *
+ *      Means that anything is to be permitted.  This should not appear in
+ *      /etc/userv/ipif-networks, as that would permit any user on the
+ *      system to create any interfaces with any addresses and routes
+ *      attached.  It is provided so that root can usefully invoke the ipif
+ *      service program directly (not via userv), without needing to set up
+ *      permissions in /etc/userv/ipif-networks.
+ *
+ *   #...
+ *
+ *      Comment.  Blank lines are also ignored.
+ *
+ *   NB: Permission is granted if _any_ config entry matches the request.
+ *
+ * The service program should be run from userv with no-disconnect-hup.
+ */
+/*
+ * Copyright (C) 1999-2000,2003 Ian Jackson
+ * This file is part of ipif, part of userv-utils
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with userv-utils; if not, write to the Free Software
+ * Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * $Id$
  */
 
 #include <stdio.h>
 #include <sys/stat.h>
 
 #define NARGS 4
-#define MAXEXROUTES 5
-#define ATXTLEN 12
+#define MAXEXROUTES 50
+#define ATXTLEN 16
 
 static const unsigned long gidmaxval= (unsigned long)((gid_t)-2);
 static const char *const protos_ok[]= { "slip", "cslip", "adaptive", 0 };
@@ -57,11 +136,12 @@ static const int signals[]= { SIGHUP, SIGINT, SIGTERM, 0 };
 
 static const char *configstr, *proto;
 static unsigned long localaddr, peeraddr, mtu;
+static int localpming, peerpming;
 static int localallow, peerallow, allallow;
 static int nexroutes;
 static struct exroute {
   unsigned long prefix, mask;
-  int allow;
+  int allow, pming;
   char prefixtxt[ATXTLEN], masktxt[ATXTLEN];
 } exroutes[MAXEXROUTES];
 
@@ -202,13 +282,13 @@ static unsigned long eat_number(const char **argp, const char *what,
   char *ep;
   int endchar;
 
-  if (!*argp) { badusage("missing number %s\n",what); }
+  if (!*argp) { badusage("missing number %s",what); }
   rv= strtoul(*argp,&ep,0);
   if ((endchar= *ep)) {
-    if (!endchars) badusage("junk after number %s\n",what);
+    if (!endchars) badusage("junk after number %s",what);
     if (!strchr(endchars,endchar))
       badusage("invalid character or delimiter `%c' in or after number, %s:"
-              " expected %s (or none?)\n", endchar,what,endchars);
+              " expected %s (or none?)", endchar,what,endchars);
     *argp= ep+1;
   } else {
     *argp= 0;
@@ -219,12 +299,17 @@ static unsigned long eat_number(const char **argp, const char *what,
   return rv;
 }
 
-static void addrnet_mustdiffer(const char *w1, unsigned long p1, unsigned long m1,
-                              const char *w2, unsigned long p2, unsigned long m2) {
+static int addrnet_overlap(unsigned long p1, unsigned long m1,
+                          unsigned long p2, unsigned long m2) {
   unsigned long mask;
 
   mask= m1&m2;
-  if ((p1 & mask) != (p2 & mask)) return;
+  return (p1 & mask) == (p2 & mask);
+}
+
+static void addrnet_mustdiffer(const char *w1, unsigned long p1, unsigned long m1,
+                              const char *w2, unsigned long p2, unsigned long m2) {
+  if (!addrnet_overlap(p1,m1,p2,m2)) return;
   badusage("%s %08lx/%08lx overlaps/clashes with %s %08lx/%08lx",
           w1,p1,m1, w2,p2,m2);
 }
@@ -258,8 +343,8 @@ static void eat_prefixmask(const char **argp, const char *what,
   sprintf(whatbuf,"%s length",what);
   len= eat_number(argp,whatbuf, 0,32, endchars,endchar_r);
 
-  mask= (~0UL << (32-len));
-  if (prefix & ~mask) badusage("%s prefix %08lx not fully contained in mask %08lx\n",
+  mask= len ? (~0UL << (32-len)) : 0UL;
+  if (prefix & ~mask) badusage("%s prefix %08lx not fully contained in mask %08lx",
                               what,prefix,mask);
   *prefix_r= prefix;
   if (mask_r) *mask_r= mask;
@@ -270,32 +355,66 @@ static int addrnet_isin(unsigned long prefix, unsigned long mask,
                        unsigned long mprefix, unsigned long mmask) {
   return  !(~mask & mmask)  &&  (prefix & mmask) == mprefix;
 }
+
+/* Totally hideous algorithm for parsing the config file lines.
+ * For each config file line, we first see if its gid applies.  If not
+ * we skip it.  Otherwise, we do
+ *  permit_begin
+ *     which sets <foo>pming to 1
+ * for each range.  <foo>pming may be 0 if we've determined that
+ * this line does not apply to <foo>.
+ *  permit_range
+ *     which calls permit_range_thing for each <foo>
+ *        which checks to see if <foo> is inside the relevant
+ *        range (for +) or overlaps it (for -) and updates
+ *        <foo>allow and <foo>pming.
+ */
+
+static void permit_begin(void) {
+  int i;
   
+  localpming= peerpming= 1;
+  for (i=0; i<nexroutes; i++) exroutes[i].pming= 1;
+}
+
+static void permit_range_thing(unsigned long tprefix, unsigned long tmask,
+                              const char *what, int *tallow, int *tpming,
+                              unsigned long pprefix, unsigned long pmask,
+                              int plus, int *any) {
+  if (plus) {
+    if (!addrnet_isin(tprefix,tmask, pprefix,pmask)) return;
+    if (*tpming) *tallow= 1;
+  } else {
+    if (!addrnet_overlap(tprefix,tmask, pprefix,pmask)) return;
+    *tpming= 0;
+  }
+  if (!proto) printf(" %c%s", plus?'+':'-', what);
+  *any= 1;
+}
 
-static void permit(unsigned long pprefix, unsigned long pmask) {
+static void permit_range(unsigned long prefix, unsigned long mask,
+                        int plus, int localonly) {
   int i, any;
+  char idbuf[40];
   
-  assert(!(pprefix & ~pmask));
+  assert(!(prefix & ~mask));
+  any= 0;
 
-  if (!proto) fputs("permits",stdout);
-  if (addrnet_isin(localaddr,~0UL, pprefix,pmask)) {
-    if (!proto) fputs(" local-addr",stdout);
-    any= localallow= 1;
-  }
-  if (addrnet_isin(peeraddr,~0UL, pprefix,pmask)) {
-    if (!proto) fputs(" peer-addr",stdout);
-    any= peerallow= 1;
-  }
-  for (i=0; i<nexroutes; i++) {
-    if (addrnet_isin(exroutes[i].prefix,exroutes[i].mask, pprefix,pmask)) {
-      if (!proto) printf(" route#%d",i);
-      any= exroutes[i].allow= 1;
+  permit_range_thing(localaddr,~0UL,"local", &localallow,&localpming,
+                    prefix,mask, plus,&any);
+
+  if (!localonly) {
+    permit_range_thing(peeraddr,~0UL, "peer-addr", &peerallow,&peerpming,
+                      prefix,mask, plus,&any);
+    for (i=0; i<nexroutes; i++) {
+      sprintf(idbuf,"route#%d",i);
+      permit_range_thing(exroutes[i].prefix,exroutes[i].mask, idbuf,
+                        &exroutes[i].allow,&exroutes[i].pming,
+                        prefix,mask, plus,&any);
     }
   }
-  if (!proto) {
-    if (!any) fputs(" nothing!",stderr);
-    putchar('\n');
-  }
+  if (!proto)
+    if (!any) fputs(" nothing",stdout);
 }
 
 static void pconfig(const char *configstr, int truncated);
@@ -347,14 +466,15 @@ static void pfile(const char *filename) {
 
 static void pconfig(const char *configstr, int truncated) {
   unsigned long fgid, tgid, pprefix, pmask;
-  int plen;
+  int plen, localonly, plus, rangeix, delim;
   char ptxt[ATXTLEN];
+  char whattxt[100];
   const char *gidlist;
   
   switch (configstr[0]) {
   case '*':
-    if (strcmp(configstr,"*")) badusage("`*' directive must be only thing on line");
-    permit(0UL,0UL);
+    permit_begin();
+    permit_range(0UL,0UL,1,0);
     return;
     
   case '#':
@@ -370,22 +490,57 @@ static void pconfig(const char *configstr, int truncated) {
       badusage("unknown configuration directive");
     
     fgid= eat_number(&configstr,"gid", 0,gidmaxval, ",",0);
-    eat_prefixmask(&configstr,"permitted-prefix", ",",0, &pprefix,&pmask,&plen);
-    if (!configstr && truncated) badusage("gid,prefix/len,... spec too long");
 
-    if (!proto) printf(" %5lu,%s/%d: ", fgid, ip2txt(pprefix,ptxt), plen);
+    if (!proto) printf(" %5lu", fgid);
 
     gidlist= getenv("USERV_GID");
     if (!gidlist) fatal("USERV_GID not set");
     for (;;) {
       if (!gidlist) {
-       if (!proto) printf("no matching gid\n");
+       if (!proto) printf(" no matching gid\n");
        return;
       }
       tgid= eat_number(&gidlist,"userv-gid", 0,gidmaxval, " ",0);
       if (tgid == fgid) break;
     }
-    permit(pprefix,pmask);
+
+    if (configstr[0] == '=') {
+      localonly= 1;
+      configstr++;
+    } else {
+      localonly= 0;
+    }
+
+    permit_begin();
+
+    rangeix= 0;
+    plus= 1;
+    switch (configstr[0]) {
+    case '-': plus= 0;     /* fall through */
+    case '+': configstr++;
+    default:;
+    }
+
+    for (;;) {
+      sprintf(whattxt, "%s-prefix#%d",
+             plus ? "permitted" : "notpermitted",
+             rangeix);
+      eat_prefixmask(&configstr,whattxt, ",+-",&delim,
+                    &pprefix,&pmask,&plen);
+      if (!configstr && truncated)
+       badusage("gid,prefix/len,... spec too long");
+
+      if (!proto)
+       printf("  %c%s/%d:", plus?'+':'-',ip2txt(pprefix,ptxt), plen);
+
+      permit_range(pprefix,pmask,plus,localonly);
+      if (delim==',') break;
+
+      plus= delim=='-' ? 0 : 1;
+      rangeix++;
+    }
+
+    putchar('\n');
     return;
   }
 }
@@ -431,29 +586,32 @@ static void parseargs(int argc, const char *const *argv) {
   addrnet_mustdiffer("local-addr",localaddr,~0UL, "peer-addr",peeraddr,~0UL);
   
   carg= *++argv;
-  for (nexroutes=0;
-       carg;
-       nexroutes++) {
-    if (nexroutes == MAXEXROUTES)
-      fatal("too many extra routes (only %d allowed)",MAXEXROUTES);
-    sprintf(erwhatbuf,"route#%d",nexroutes);
+  if (strcmp(carg,"-")) {
+    for (nexroutes=0;
+        carg && *carg;
+        nexroutes++) {
+      if (nexroutes == MAXEXROUTES)
+       fatal("too many extra routes (only %d allowed)",MAXEXROUTES);
+      sprintf(erwhatbuf,"route#%d",nexroutes);
     
-    eat_prefixmask(&carg,erwhatbuf, ",",0, &routeaddr,&routemask,0);
-    if (routemask == ~0UL) {
-      addrnet_mustdiffer(erwhatbuf,routeaddr,routemask, "local-addr",localaddr,~0UL);
-      addrnet_mustdiffer(erwhatbuf,routeaddr,routemask, "peer-addr",peeraddr,~0UL);
-    }
-    for (i=0; i<nexroutes; i++) {
-      sprintf(erwhatbuf2,"route#%d",i);
-      addrnet_mustdiffer(erwhatbuf,routeaddr,routemask,
-                        erwhatbuf2,exroutes[i].prefix,exroutes[i].mask);
+      eat_prefixmask(&carg,erwhatbuf, ",",0, &routeaddr,&routemask,0);
+      if (routemask == ~0UL) {
+       addrnet_mustdiffer(erwhatbuf,routeaddr,routemask, "local-addr",localaddr,~0UL);
+       addrnet_mustdiffer(erwhatbuf,routeaddr,routemask, "peer-addr",peeraddr,~0UL);
+      }
+      for (i=0; i<nexroutes; i++) {
+       sprintf(erwhatbuf2,"route#%d",i);
+       addrnet_mustdiffer(erwhatbuf,routeaddr,routemask,
+                          erwhatbuf2,exroutes[i].prefix,exroutes[i].mask);
+      }
+      exroutes[nexroutes].prefix= routeaddr;
+      exroutes[nexroutes].mask= routemask;
+      exroutes[nexroutes].allow= 0;
+      ip2txt(routeaddr,exroutes[nexroutes].prefixtxt);
+      ip2txt(routemask,exroutes[nexroutes].masktxt);
     }
-    exroutes[nexroutes].prefix= routeaddr;
-    exroutes[nexroutes].mask= routemask;
-    exroutes[nexroutes].allow= 0;
-    ip2txt(routeaddr,exroutes[nexroutes].prefixtxt);
-    ip2txt(routemask,exroutes[nexroutes].masktxt);
   }
+
   ip2txt(localaddr,localtxt);
   ip2txt(peeraddr,peertxt);
 }
@@ -676,7 +834,7 @@ static void startslattach(void) {
   }
   setsigmask(&fullset);
   l= strlen(ifnbuf);
-  if (l<0 || ifnbuf[l-1] != '\n') fatal("slattach gave strange output `%s'",ifnbuf);
+  if (l<=0 || ifnbuf[l-1] != '\n') fatal("slattach gave strange output `%s'",ifnbuf);
   ifnbuf[l-1]= 0;
   for (k=l; k>0 && ifnbuf[k-1]!=' '; k--);
   ifname= ifnbuf+k;
@@ -695,18 +853,6 @@ static void netconfigure(void) {
     sysfatal("cannot exec ifconfig");
   }
 
-  if (task()) {
-    execlp("route","route", "add", "-host",localtxt,
-          "dev",ifname, (char*)0);
-    sysfatal("cannot exec route (for local)");
-  }
-
-  if (task()) {
-    execlp("route","route", "add", "-host",peertxt,
-          "dev",ifname, (char*)0);
-    sysfatal("cannot exec route (for peer)");
-  }
-
   for (i=0; i<nexroutes; i++) {
     if (task()) {
       execlp("route","route", "add", "-net",exroutes[i].prefixtxt,
@@ -718,8 +864,14 @@ static void netconfigure(void) {
 }
 
 static void copydata(void) __attribute__((noreturn));
-static void copydata(void) {  
+static void copydata(void) {
+  int r;
+  
   pids.byname.cin= makesubproc(cin_entry);
+  for (;;) {
+    r= write(1, "\300", 1); if (r==1) break;
+    assert(r==-1);  if (errno != EINTR) sysfatal("send initial delim to confirm");
+  }
   pids.byname.cout= makesubproc(cout_entry);
 
   for (;;) sigsuspend(&emptyset);