chiark / gitweb /
b7706235d6227e6943b0cf4d596aabff1423e16f
[userv-utils.git] / ipif / service.c
1 /*
2  * userv service (or standalone program)
3  * for per-user IP subranges.
4  *
5  * This is invoked as root, directly from userv.
6  * Its arguments are supposed to be, in order:
7  *  <config>
8  *      Specifies address ranges and gids which own them.
9  *  --  Indicates that the remaining arguments are user-supplied
10  *      and therefore untrusted.
11  *  <local-addr>,<peer-addr>,<mtu>,<proto>
12  *      As for slattach.  Supported protocols are slip, cslip, and
13  *      adaptive.  Alternatively, set to `debug' to print debugging
14  *      info.  <local-addr> is address of the interface on chiark;
15  *      <peer-addr> is the address of the point-to-point peer.
16  *  <prefix>/<mask>,<prefix>/<mask>,...
17  *      List of additional routes to add for this interface.
18  *      May be the empty argument.
19  *
20  * <config> is either
21  *    <gid>,<prefix>/<len>[,<junk>]
22  *      indicating that that gid may allocate addresses in
23  *      the relevant subspace (<junk> is ignored)
24  * or #...
25  *      which is a comment
26  * or /<config-file-name> or ./<config-file-name> or ../<config-file-name>
27  *      which refers to a file which contains lines which
28  *      are each <config>
29  * or *
30  *      which means that anything is permitted
31  * 
32  * Should be run from userv with no-disconnect-hup.
33  */
34
35 #include <stdio.h>
36 #include <string.h>
37 #include <stdlib.h>
38 #include <assert.h>
39 #include <errno.h>
40 #include <stdarg.h>
41 #include <ctype.h>
42 #include <limits.h>
43
44 #define NARGS 4
45 #define MAXEXROUTES 5
46 #define ATXTLEN 12
47
48 static const unsigned long gidmaxval= (unsigned long)((gid_t)-2);
49 static const char *const protos_ok[]= { "slip", "cslip", "adaptive", 0 };
50
51 static const char *configstr, *proto;
52 static unsigned long localaddr, peeraddr, mtu;
53 static int localallow, peerallow, allallow;
54 static int nexroutes;
55 static struct exroute {
56   unsigned long prefix, mask;
57   int allow;
58   char prefixtxt[ATXTLEN], masktxt[ATXTLEN];
59 } exroutes[MAXEXROUTES];
60
61 static char localtxt[ATXTLEN];
62 static char peertxt[ATXTLEN];
63
64 static struct pplace {
65   struct pplace *parent;
66   const char *filename;
67   int lineno;
68 } *cpplace;
69
70 static void fatal(const char *fmt, ...)
71      __attribute__((format(printf,1,2)));
72 static void fatal(const char *fmt, ...) {
73   va_list al;
74   va_start(al,fmt);
75
76   fputs("userv-ipif service: fatal error: ",stderr);
77   vfprintf(stderr, fmt, al);
78   putc('\n',stderr);
79   exit(8);
80 }
81   
82 static void sysfatal(const char *fmt, ...)
83      __attribute__((format(printf,1,2)));
84 static void sysfatal(const char *fmt, ...) {
85   va_list al;
86   int e;
87
88   e= errno;
89   va_start(al,fmt);
90
91   fputs("userv-ipif service: fatal system error",stderr);
92   vfprintf(stderr, fmt, al);
93   fprintf(stderr,"%s\n", strerror(e));
94   exit(12);
95 }
96
97
98 static void badusage(const char *fmt, ...)
99      __attribute__((format(printf,1,2)));
100 static void badusage(const char *fmt, ...) {
101   va_list al;
102   struct pplace *cpp;
103   
104   if (cpplace) {
105     fprintf(stderr,
106             "userv-ipif service: %s:%d: ",
107             cpplace->filename, cpplace->lineno);
108   } else {
109     fputs("userv-ipif service: invalid usage: ",stderr);
110   }
111   va_start(al,fmt);
112   vfprintf(stderr, fmt, al);
113   putc('\n',stderr);
114
115   if (cpplace) {
116     for (cpp=cpplace->parent; cpp; cpp=cpp->parent) {
117       fprintf(stderr,
118               "userv-ipif service: %s:%d: ... in file included from here\n",
119               cpp->filename, cpp->lineno);
120     }
121   }
122   exit(16);
123 }
124
125 static char *ip2txt(unsigned long addr, char *buf) {
126   sprintf(buf, "%lu.%lu.%lu.%lu",
127           (addr>>24) & 0x0ff,
128           (addr>>16) & 0x0ff,
129           (addr>>8) & 0x0ff,
130           (addr) & 0x0ff);
131   return buf;
132 }
133
134 static unsigned long eat_number(const char **argp, const char *what,
135                                 unsigned long min, unsigned long max,
136                                 const char *endchars, int *endchar_r) {
137   /* If !endchars then the endchar must be a nul, otherwise it may be
138    * a nul (resulting in *argp set to 0) or something else (*argp set
139    * to point to after delim, *endchar_r set to delim).
140    * *endchar_r may be 0.
141    */
142   unsigned long rv;
143   char *ep;
144   int endchar;
145
146   if (!*argp) { badusage("missing number %s\n",what); }
147   rv= strtoul(*argp,&ep,0);
148   if ((endchar= *ep)) {
149     if (!endchars) badusage("junk after number %s\n",what);
150     if (!strchr(endchars,endchar))
151       badusage("invalid character or delimiter `%c' in or after number, %s:"
152                " expected %s (or none?)\n", endchar,what,endchars);
153     *argp= ep+1;
154   } else {
155     *argp= 0;
156   }
157   if (endchar_r) *endchar_r= endchar;
158   if (rv < min || rv > max) badusage("number %s value %lu out of range %lu..%lu",
159                                      what, rv, min, max);
160   return rv;
161 }
162
163 static void addrnet_mustdiffer(const char *w1, unsigned long p1, unsigned long m1,
164                                const char *w2, unsigned long p2, unsigned long m2) {
165   unsigned long mask;
166
167   mask= m1&m2;
168   if ((p1 & mask) != (p2 & mask)) return;
169   badusage("%s %08lx/%08lx overlaps/clashes with %s %08lx/%08lx",
170            w1,p1,m1, w2,p2,m2);
171 }
172   
173 static unsigned long eat_addr(const char **argp, const char *what,
174                               const char *endchars, int *endchar_r) {
175   char whatbuf[100];
176   unsigned long rv;
177   int i;
178
179   for (rv=0, i=0;
180        i<4;
181        i++) {
182     rv <<= 8;
183     sprintf(whatbuf,"%s byte #%d",what,i);
184     rv |= eat_number(argp,whatbuf, 0,255, i<3 ? "." : endchars, endchar_r);
185   }
186
187   return rv;
188 }
189
190 static void eat_prefixmask(const char **argp, const char *what,
191                            const char *endchars, int *endchar_r,
192                            unsigned long *prefix_r, unsigned long *mask_r, int *len_r) {
193   /* mask_r and len_r may be 0 */
194   char whatbuf[100];
195   int len;
196   unsigned long prefix, mask;
197
198   prefix= eat_addr(argp,what, "/",0);
199   sprintf(whatbuf,"%s length",what);
200   len= eat_number(argp,whatbuf, 0,32, endchars,endchar_r);
201
202   mask= (~0UL << (32-len));
203   if (prefix & ~mask) badusage("%s prefix %08lx not fully contained in mask %08lx\n",
204                                what,prefix,mask);
205   *prefix_r= prefix;
206   if (mask_r) *mask_r= mask;
207   if (len_r) *len_r= len;
208 }
209
210 static int addrnet_isin(unsigned long prefix, unsigned long mask,
211                         unsigned long mprefix, unsigned long mmask) {
212   return  !(~mask & mmask)  &&  (prefix & mmask) == mprefix;
213 }
214   
215
216 static void permit(unsigned long pprefix, unsigned long pmask) {
217   int i, any;
218   
219   assert(!(pprefix & ~pmask));
220
221   if (!proto) fputs("permits",stdout);
222   if (addrnet_isin(localaddr,~0UL, pprefix,pmask)) {
223     if (!proto) fputs(" local-addr",stdout);
224     any= localallow= 1;
225   }
226   if (addrnet_isin(peeraddr,~0UL, pprefix,pmask)) {
227     if (!proto) fputs(" peer-addr",stdout);
228     any= peerallow= 1;
229   }
230   for (i=0; i<nexroutes; i++) {
231     if (addrnet_isin(exroutes[i].prefix,exroutes[i].mask, pprefix,pmask)) {
232       if (!proto) printf(" route#%d",i);
233       any= exroutes[i].allow= 1;
234     }
235   }
236   if (!proto) {
237     if (!any) fputs(" nothing!",stderr);
238     putchar('\n');
239   }
240 }
241
242 static void pconfig(const char *configstr, int truncated);
243
244 static void pfile(const char *filename) {
245   FILE *file;
246   char buf[PATH_MAX];
247   int l, truncated, c;
248   struct pplace npp, *cpp;
249
250   for (cpp=cpplace; cpp; cpp=cpp->parent) {
251     if (!strcmp(cpp->filename,filename))
252       badusage("recursive configuration file `%s'",filename);
253   }
254
255   file= fopen(filename,"r");
256   if (!file)
257     badusage("cannot open configuration file `%s': %s", filename, strerror(errno));
258
259   if (!proto) printf("config file `%s':\n",filename);
260
261   npp.parent= cpplace;
262   npp.filename= filename;
263   npp.lineno= 0;
264   cpplace= &npp;
265
266   while (fgets(buf, sizeof(buf), file)) {
267     npp.lineno++;
268     l= strlen(buf);
269     if (!l) continue;
270
271     truncated= (buf[l-1] != '\n');
272     while (l>0 && isspace((unsigned char) buf[l-1])) l--;
273     if (!l) continue;
274     buf[l]= 0;
275
276     if (truncated) {
277       while ((c= getc(file)) != EOF && c != '\n');
278       if (c == EOF) break;
279     }
280
281     pconfig(buf,truncated);
282   }
283   if (ferror(file))
284     badusage("failed while reading configuration file: %s", strerror(errno));
285
286   cpplace= npp.parent;
287 }
288
289 static void pconfig(const char *configstr, int truncated) {
290   unsigned long fgid, tgid, pprefix, pmask;
291   int plen;
292   char ptxt[ATXTLEN];
293   const char *gidlist;
294   
295   switch (configstr[0]) {
296   case '*':
297     if (strcmp(configstr,"*")) badusage("`*' directive must be only thing on line");
298     permit(0UL,0UL);
299     return;
300     
301   case '#':
302     return;
303     
304   case '/': case '.':
305     if (truncated) badusage("filename too long (`%.100s...')",configstr);
306     pfile(configstr);
307     return;
308     
309   default:
310     if (!isdigit((unsigned char)configstr[0]))
311       badusage("unknown configuration directive");
312     
313     fgid= eat_number(&configstr,"gid", 0,gidmaxval, ",",0);
314     eat_prefixmask(&configstr,"permitted-prefix", ",",0, &pprefix,&pmask,&plen);
315     if (!configstr && truncated) badusage("gid,prefix/len,... spec too long");
316
317     if (!proto) printf(" %5lu,%s/%d: ", fgid, ip2txt(pprefix,ptxt), plen);
318
319     gidlist= getenv("USERV_GID");
320     if (!gidlist) fatal("USERV_GID not set");
321     for (;;) {
322       if (!gidlist) {
323         if (!proto) printf("no matching gid\n");
324         return;
325       }
326       tgid= eat_number(&gidlist,"userv-gid", 0,gidmaxval, " ",0);
327       if (tgid == fgid) break;
328     }
329     permit(pprefix,pmask);
330     return;
331   }
332 }
333
334 static void checkallow(int allow, const char *what,
335                        const char *prefixtxt, const char *masktxt) {
336   if (allow) return;
337   fprintf(stderr,"userv-ipif service: access denied for %s, %s/%s\n",
338           what, prefixtxt, masktxt);
339   allallow= 0;
340 }
341
342 static void parseargs(int argc, const char *const *argv) {
343   unsigned long routeaddr, routemask;
344   const char *carg;
345   const char *const *cprotop;
346   int i;
347   char erwhatbuf[100], erwhatbuf2[100];
348   
349   if (argc < NARGS+1) { badusage("too few arguments"); }
350   if (argc > NARGS+1) { badusage("too many arguments"); }
351
352   configstr= *++argv;
353   
354   carg= *++argv;
355   if (strcmp(carg,"--")) badusage("separator argument `--' not found, got `%s'",carg);
356
357   carg= *++argv;
358   localaddr= eat_addr(&carg,"local-addr", ",",0);
359   peeraddr= eat_addr(&carg,"peer-addr", ",",0);
360   mtu= eat_number(&carg,"mtu", 576,65536, ",",0);
361   localallow= peerallow= 0;
362   
363   if (!strcmp(carg,"debug")) {
364     proto= 0;
365   } else {
366     for (cprotop= protos_ok;
367          (proto= *cprotop) && strcmp(proto,carg);
368          cprotop++);
369     if (!proto) fatal("invalid protocol");
370   }
371   
372   addrnet_mustdiffer("local-addr",localaddr,~0UL, "peer-addr",peeraddr,~0UL);
373   
374   carg= *++argv;
375   for (nexroutes=0;
376        carg;
377        nexroutes++) {
378     if (nexroutes == MAXEXROUTES)
379       fatal("too many extra routes (only %d allowed)",MAXEXROUTES);
380     sprintf(erwhatbuf,"route#%d",nexroutes);
381     
382     eat_prefixmask(&carg,erwhatbuf, ",",0, &routeaddr,&routemask,0);
383     if (routemask == ~0UL) {
384       addrnet_mustdiffer(erwhatbuf,routeaddr,routemask, "local-addr",localaddr,~0UL);
385       addrnet_mustdiffer(erwhatbuf,routeaddr,routemask, "peer-addr",peeraddr,~0UL);
386     }
387     for (i=0; i<nexroutes; i++) {
388       sprintf(erwhatbuf2,"route#%d",i);
389       addrnet_mustdiffer(erwhatbuf,routeaddr,routemask,
390                          erwhatbuf2,exroutes[i].prefix,exroutes[i].mask);
391     }
392     exroutes[nexroutes].prefix= routeaddr;
393     exroutes[nexroutes].mask= routemask;
394     exroutes[nexroutes].allow= 0;
395     ip2txt(routeaddr,exroutes[nexroutes].prefixtxt);
396     ip2txt(routemask,exroutes[nexroutes].masktxt);
397   }
398   ip2txt(localaddr,localtxt);
399   ip2txt(peeraddr,peertxt);
400 }
401
402 static void checkpermit(void) {
403   int i;
404   char erwhatbuf[100];
405   
406   allallow= 1;
407   checkallow(localallow,"local-addr", localtxt,"32");
408   checkallow(peerallow,"peer-addr", peertxt,"32");
409   for (i=0; i<nexroutes; i++) {
410     sprintf(erwhatbuf, "route#%d", i);
411     checkallow(exroutes[i].allow, erwhatbuf, exroutes[i].prefixtxt, exroutes[i].masktxt);
412   }
413   if (!allallow) fatal("access denied");
414 }
415
416 static void dumpdebug(void) __attribute__((noreturn));
417 static void dumpdebug(void) {
418   int i;
419   char erwhatbuf[100];
420   
421   printf("protocol: debug\n"
422          "local:    %08lx == %s\n"
423          "peer:     %08lx == %s\n"
424          "mtu:      %ld\n"
425          "routes:   %d\n",
426          localaddr, localtxt,
427          peeraddr, peertxt,
428          mtu,
429          nexroutes);
430   for (i=0; i<nexroutes; i++) {
431     sprintf(erwhatbuf, "route#%d:", i);
432     printf("%-9s %08lx/%08lx == %s/%s\n",
433            erwhatbuf,
434            exroutes[i].prefix, exroutes[i].mask,
435            exroutes[i].prefixtxt, exroutes[i].masktxt);
436   }
437   if (ferror(stdout) || fclose(stdout)) sysfatal("flush stdout");
438   exit(0);
439 }
440
441 int main(int argc, const char *const *argv) {
442   parseargs(argc,argv);
443   pconfig(configstr,0);
444   checkpermit();
445   if (!proto) dumpdebug();
446
447   abort();
448 }