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