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