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