chiark / gitweb /
test-example: Provide test which uses unshare(8)
[secnet.git] / slip.c
1 /* When dealing with SLIP (to a pty, or ipif) we have separate rx, tx
2    and client buffers.  When receiving we may read() any amount, not
3    just whole packets.  When transmitting we need to bytestuff anyway,
4    and may be part-way through receiving. */
5
6 #include "secnet.h"
7 #include "util.h"
8 #include "netlink.h"
9 #include "process.h"
10 #include "unaligned.h"
11 #include <stdio.h>
12 #include <string.h>
13 #include <unistd.h>
14 #include <errno.h>
15 #include <fcntl.h>
16
17 #define SLIP_END    192
18 #define SLIP_ESC    219
19 #define SLIP_ESCEND 220
20 #define SLIP_ESCESC 221
21
22 struct slip {
23     struct netlink nl;
24     struct buffer_if *buff; /* We unstuff received packets into here
25                                and send them to the netlink code. */
26     bool_t pending_esc;
27     bool_t ignoring_packet; /* If this packet was corrupt or overlong,
28                                we ignore everything up to the next END */
29     netlink_deliver_fn *netlink_to_tunnel;
30     uint32_t local_address;
31 };
32
33 /* Generic SLIP mangling code */
34
35 static void slip_stuff(struct slip *st, struct buffer_if *buf, int fd)
36 {
37     uint8_t txbuf[DEFAULT_BUFSIZE];
38     uint8_t *i;
39     int32_t j=0;
40
41     BUF_ASSERT_USED(buf);
42
43     /* There's probably a much more efficient way of implementing this */
44     txbuf[j++]=SLIP_END;
45     for (i=buf->start; i<(buf->start+buf->size); i++) {
46         switch (*i) {
47         case SLIP_END:
48             txbuf[j++]=SLIP_ESC;
49             txbuf[j++]=SLIP_ESCEND;
50             break;
51         case SLIP_ESC:
52             txbuf[j++]=SLIP_ESC;
53             txbuf[j++]=SLIP_ESCESC;
54             break;
55         default:
56             txbuf[j++]=*i;
57             break;
58         }
59         if ((j+2)>DEFAULT_BUFSIZE) {
60             if (write(fd,txbuf,j)<0) {
61                 fatal_perror("slip_stuff: write()");
62             }
63             j=0;
64         }
65     }
66     txbuf[j++]=SLIP_END;
67     if (write(fd,txbuf,j)<0) {
68         fatal_perror("slip_stuff: write()");
69     }
70     BUF_FREE(buf);
71 }
72
73 static void slip_unstuff(struct slip *st, uint8_t *buf, uint32_t l)
74 {
75     uint32_t i;
76
77     BUF_ASSERT_USED(st->buff);
78     for (i=0; i<l; i++) {
79         int outputchr;
80         enum { OUTPUT_END = 256, OUTPUT_NOTHING = 257 };
81
82         if (!st->buff->size)
83             buffer_init(st->buff,calculate_max_start_pad());
84
85         if (st->pending_esc) {
86             st->pending_esc=False;
87             switch(buf[i]) {
88             case SLIP_ESCEND:
89                 outputchr=SLIP_END;
90                 break;
91             case SLIP_ESCESC:
92                 outputchr=SLIP_ESC;
93                 break;
94             default:
95                 if (!st->ignoring_packet) {
96                     Message(M_WARNING, "userv_afterpoll: bad SLIP escape"
97                             " character, dropping packet\n");
98                 }
99                 st->ignoring_packet=True;
100                 outputchr=OUTPUT_NOTHING;
101                 break;
102             }
103         } else {
104             switch (buf[i]) {
105             case SLIP_END:
106                 outputchr=OUTPUT_END;
107                 break;
108             case SLIP_ESC:
109                 st->pending_esc=True;
110                 outputchr=OUTPUT_NOTHING;
111                 break;
112             default:
113                 outputchr=buf[i];
114                 break;
115             }
116         }
117
118         if (st->ignoring_packet) {
119             if (outputchr == OUTPUT_END) {
120                 st->ignoring_packet=False;
121                 st->buff->size=0;
122             }
123         } else {
124             if (outputchr == OUTPUT_END) {
125                 if (st->buff->size>0) {
126                     st->netlink_to_tunnel(&st->nl,st->buff);
127                     BUF_ALLOC(st->buff,"userv_afterpoll");
128                 }
129                 st->buff->size=0;
130             } else if (outputchr != OUTPUT_NOTHING) {
131                 if (st->buff->size < st->buff->len) {
132                     buf_append_uint8(st->buff,outputchr);
133                 } else {
134                     Message(M_WARNING, "userv_afterpoll: dropping overlong"
135                             " SLIP packet\n");
136                     st->ignoring_packet=True;
137                 }
138             }
139         }
140     }
141 }
142
143 static void slip_init(struct slip *st, struct cloc loc, dict_t *dict,
144                       cstring_t name, netlink_deliver_fn *to_host)
145 {
146     st->netlink_to_tunnel=
147         netlink_init(&st->nl,st,loc,dict,
148                      "netlink-userv-ipif",NULL,to_host);
149     st->buff=find_cl_if(dict,"buffer",CL_BUFFER,True,"name",loc);
150     st->local_address=string_item_to_ipaddr(
151         dict_find_item(dict,"local-address", True, name, loc),"netlink");
152     BUF_ALLOC(st->buff,"slip_init");
153     st->pending_esc=False;
154     st->ignoring_packet=False;
155 }
156
157 /* Connection to the kernel through userv-ipif */
158
159 struct userv {
160     struct slip slip;
161     int txfd; /* We transmit to userv */
162     int rxfd; /* We receive from userv */
163     cstring_t userv_path;
164     cstring_t service_user;
165     cstring_t service_name;
166     pid_t pid;
167     bool_t expecting_userv_exit;
168 };
169
170 static int userv_beforepoll(void *sst, struct pollfd *fds, int *nfds_io,
171                             int *timeout_io)
172 {
173     struct userv *st=sst;
174
175     if (st->rxfd!=-1) {
176         *nfds_io=2;
177         fds[0].fd=st->txfd;
178         fds[0].events=0; /* Might want to pick up POLLOUT sometime */
179         fds[1].fd=st->rxfd;
180         fds[1].events=POLLIN;
181     } else {
182         *nfds_io=0;
183     }
184     return 0;
185 }
186
187 static void userv_afterpoll(void *sst, struct pollfd *fds, int nfds)
188 {
189     struct userv *st=sst;
190     uint8_t rxbuf[DEFAULT_BUFSIZE];
191     int l;
192
193     if (nfds==0) return;
194
195     if (fds[1].revents&POLLERR) {
196         Message(M_ERR,"%s: userv_afterpoll: POLLERR!\n",st->slip.nl.name);
197     }
198     if (fds[1].revents&POLLIN) {
199         l=read(st->rxfd,rxbuf,DEFAULT_BUFSIZE);
200         if (l<0) {
201             if (errno!=EINTR)
202                 fatal_perror("%s: userv_afterpoll: read(rxfd)",
203                              st->slip.nl.name);
204         } else if (l==0) {
205             fatal("%s: userv_afterpoll: read(rxfd)=0; userv gone away?",
206                   st->slip.nl.name);
207         } else slip_unstuff(&st->slip,rxbuf,l);
208     }
209 }
210
211 /* Send buf to the kernel. Free buf before returning. */
212 static void userv_deliver_to_kernel(void *sst, struct buffer_if *buf)
213 {
214     struct userv *st=sst;
215
216     slip_stuff(&st->slip,buf,st->txfd);
217 }
218
219 static void userv_userv_callback(void *sst, pid_t pid, int status)
220 {
221     struct userv *st=sst;
222
223     if (pid!=st->pid) {
224         Message(M_WARNING,"userv_callback called unexpectedly with pid %d "
225                 "(expected %d)\n",pid,st->pid);
226         return;
227     }
228     if (!st->expecting_userv_exit) {
229         if (WIFEXITED(status)) {
230             fatal("%s: userv exited unexpectedly with status %d",
231                   st->slip.nl.name,WEXITSTATUS(status));
232         } else if (WIFSIGNALED(status)) {
233             fatal("%s: userv exited unexpectedly: uncaught signal %d",
234                   st->slip.nl.name,WTERMSIG(status));
235         } else {
236             fatal("%s: userv stopped unexpectedly",
237                   st->slip.nl.name);
238         }
239     }
240     Message(M_WARNING,"%s: userv subprocess died with status %d\n",
241             st->slip.nl.name,WEXITSTATUS(status));
242     st->pid=0;
243 }
244
245 struct userv_entry_rec {
246     cstring_t path;
247     const char **argv;
248     int in;
249     int out;
250     /* XXX perhaps we should collect and log stderr? */
251 };
252
253 static void userv_entry(void *sst)
254 {
255     struct userv_entry_rec *st=sst;
256
257     dup2(st->in,0);
258     dup2(st->out,1);
259
260     /* XXX close all other fds */
261     setsid();
262     /* XXX We really should strdup() all of argv[] but because we'll just
263        exit anyway if execvp() fails it doesn't seem worth bothering. */
264     execvp(st->path,(char *const*)st->argv);
265     perror("userv-entry: execvp()");
266     exit(1);
267 }
268
269 static void userv_invoke_userv(struct userv *st)
270 {
271     struct userv_entry_rec *er;
272     int c_stdin[2];
273     int c_stdout[2];
274     string_t addrs;
275     string_t nets;
276     string_t s;
277     struct netlink_client *r;
278     struct ipset *allnets;
279     struct subnet_list *snets;
280     int i, nread;
281     uint8_t confirm;
282
283     if (st->pid) {
284         fatal("userv_invoke_userv: already running");
285     }
286
287     /* This is where we actually invoke userv - all the networks we'll
288        be using should already have been registered. */
289
290     addrs=safe_malloc(512,"userv_invoke_userv:addrs");
291     snprintf(addrs,512,"%s,%s,%d,slip",
292              ipaddr_to_string(st->slip.local_address),
293              ipaddr_to_string(st->slip.nl.secnet_address),st->slip.nl.mtu);
294
295     allnets=ipset_new();
296     for (r=st->slip.nl.clients; r; r=r->next) {
297         if (r->link_quality > LINK_QUALITY_UNUSED) {
298             struct ipset *nan;
299             r->kup=True;
300             nan=ipset_union(allnets,r->networks);
301             ipset_free(allnets);
302             allnets=nan;
303         }
304     }
305     snets=ipset_to_subnet_list(allnets);
306     ipset_free(allnets);
307     nets=safe_malloc(20*snets->entries,"userv_invoke_userv:nets");
308     *nets=0;
309     for (i=0; i<snets->entries; i++) {
310         s=subnet_to_string(snets->list[i]);
311         strcat(nets,s);
312         strcat(nets,",");
313         free(s);
314     }
315     nets[strlen(nets)-1]=0;
316     subnet_list_free(snets);
317
318     Message(M_INFO,"%s: about to invoke: %s %s %s %s %s\n",st->slip.nl.name,
319             st->userv_path,st->service_user,st->service_name,addrs,nets);
320
321     st->slip.pending_esc=False;
322
323     /* Invoke userv */
324     if (pipe(c_stdin)!=0) {
325         fatal_perror("userv_invoke_userv: pipe(c_stdin)");
326     }
327     if (pipe(c_stdout)!=0) {
328         fatal_perror("userv_invoke_userv: pipe(c_stdout)");
329     }
330     st->txfd=c_stdin[1];
331     st->rxfd=c_stdout[0];
332
333     er=safe_malloc(sizeof(*r),"userv_invoke_userv: er");
334
335     er->in=c_stdin[0];
336     er->out=c_stdout[1];
337     /* The arguments are:
338        userv
339        service-user
340        service-name
341        local-addr,secnet-addr,mtu,protocol
342        route1,route2,... */
343     er->argv=safe_malloc(sizeof(*er->argv)*6,"userv_invoke_userv:argv");
344     er->argv[0]=st->userv_path;
345     er->argv[1]=st->service_user;
346     er->argv[2]=st->service_name;
347     er->argv[3]=addrs;
348     er->argv[4]=nets;
349     er->argv[5]=NULL;
350     er->path=st->userv_path;
351
352     st->pid=makesubproc(userv_entry, userv_userv_callback,
353                         er, st, st->slip.nl.name);
354     close(er->in);
355     close(er->out);
356     free(er->argv);
357     free(er);
358     free(addrs);
359     free(nets);
360     Message(M_INFO,"%s: userv-ipif pid is %d\n",st->slip.nl.name,st->pid);
361     /* Read a single character from the pipe to confirm userv-ipif is
362        running. If we get a SIGCHLD at this point then we'll get EINTR. */
363     if ((nread=read(st->rxfd,&confirm,1))!=1) {
364         if (errno==EINTR) {
365             Message(M_WARNING,"%s: read of confirmation byte was "
366                     "interrupted\n",st->slip.nl.name);
367         } else {
368             if (nread<0) {
369                 fatal_perror("%s: error reading confirmation byte",
370                              st->slip.nl.name);
371             } else {
372                 fatal("%s: unexpected EOF instead of confirmation byte"
373                       " - userv ipif failed?", st->slip.nl.name);
374             }
375         }
376     } else {
377         if (confirm!=SLIP_END) {
378             fatal("%s: bad confirmation byte %d from userv-ipif",
379                   st->slip.nl.name,confirm);
380         }
381     }
382 }
383
384 static void userv_kill_userv(struct userv *st)
385 {
386     if (st->pid) {
387         kill(-st->pid,SIGTERM);
388         st->expecting_userv_exit=True;
389     }
390 }
391
392 static void userv_phase_hook(void *sst, uint32_t newphase)
393 {
394     struct userv *st=sst;
395     /* We must wait until signal processing has started before forking
396        userv */
397     if (newphase==PHASE_RUN) {
398         userv_invoke_userv(st);
399         /* Register for poll() */
400         register_for_poll(st, userv_beforepoll, userv_afterpoll, 2,
401                           st->slip.nl.name);
402     }
403     if (newphase==PHASE_SHUTDOWN) {
404         userv_kill_userv(st);
405     }
406 }
407
408 static list_t *userv_apply(closure_t *self, struct cloc loc, dict_t *context,
409                            list_t *args)
410 {
411     struct userv *st;
412     item_t *item;
413     dict_t *dict;
414
415     st=safe_malloc(sizeof(*st),"userv_apply");
416
417     /* First parameter must be a dict */
418     item=list_elem(args,0);
419     if (!item || item->type!=t_dict)
420         cfgfatal(loc,"userv-ipif","parameter must be a dictionary\n");
421     
422     dict=item->data.dict;
423
424     slip_init(&st->slip,loc,dict,"netlink-userv-ipif",
425               userv_deliver_to_kernel);
426
427     st->userv_path=dict_read_string(dict,"userv-path",False,"userv-netlink",
428                                     loc);
429     st->service_user=dict_read_string(dict,"service-user",False,
430                                       "userv-netlink",loc);
431     st->service_name=dict_read_string(dict,"service-name",False,
432                                       "userv-netlink",loc);
433     if (!st->userv_path) st->userv_path="userv";
434     if (!st->service_user) st->service_user="root";
435     if (!st->service_name) st->service_name="ipif";
436     st->rxfd=-1; st->txfd=-1;
437     st->pid=0;
438     st->expecting_userv_exit=False;
439     add_hook(PHASE_RUN,userv_phase_hook,st);
440     add_hook(PHASE_SHUTDOWN,userv_phase_hook,st);
441
442     return new_closure(&st->slip.nl.cl);
443 }
444
445 void slip_module(dict_t *dict)
446 {
447     add_closure(dict,"userv-ipif",userv_apply);
448 }