chiark / gitweb /
test-example: Provide a polypath test
[secnet.git] / polypath.c
1 /* polypath
2  * send/receive module for secnet
3  * for multi-route setups */
4
5 #include "secnet.h"
6 #include "util.h"
7 #include "unaligned.h"
8 #include "comm-common.h"
9
10 #include <adns.h>
11 #include <ctype.h>
12
13 #ifdef CONFIG_IPV6
14
15 static comm_sendmsg_fn polypath_sendmsg;
16
17 struct interf {
18     char *name; /* from malloc */
19     struct udpsocks socks;
20     bool_t experienced_xmit_noaf[MAX_AF];
21     LIST_ENTRY(interf) entry;
22 };
23
24 struct polypath {
25     struct udpcommon uc;
26     int max_interfs;
27     const char *const *ifname_pats;
28     const char *const *monitor_command;
29     bool_t permit_loopback;
30     LIST_HEAD(,interf) interfs;
31     struct buffer_if lbuf;
32     int monitor_fd;
33     pid_t monitor_pid;
34 };
35
36 #define LG 0, st->uc.cc.cl.description, &st->uc.cc.loc
37
38 static const char *const default_loopback_ifname_pats[] = {
39     "!lo", 0
40 };
41 static const char *const default_ifname_pats[] = {
42     "!userv*","!sl*","!tap*","!tun*", "*", 0
43 };
44
45 static const char *const default_monitor_command[] = {
46 #if __linux__
47     DATAROOTDIR "/secnet/" "polypath-interface-monitor-linux", 0
48 #else
49     0
50 #endif
51 };
52
53 static const char *polypath_addr_to_string(void *commst,
54                                            const struct comm_addr *ca)
55 {
56     static char sbuf[100];
57
58     snprintf(sbuf, sizeof(sbuf), "polypath:%s",
59              iaddr_to_string(&ca->ia));
60     return sbuf;
61 }
62
63 static bool_t ifname_search_pats(struct polypath *st, struct cloc loc,
64                                  const char *ifname, bool_t *want_io,
65                                  const char *const *pats) {
66     /* Returns True iff we found a list entry, in which case *want_io
67      * is set to the sense of that entry.  Otherwise *want_io is set
68      * to the sense of the last entry, or unchanged if there were no pats. */
69     if (!pats)
70         return False;
71     const char *const *pati;
72     for (pati=pats; *pati; pati++) {
73         const char *pat=*pati;
74         if (*pat=='!') { *want_io=False; pat++; }
75         else if (*pat=='+') { *want_io=True; pat++; }
76         else if (*pat=='*' || isalnum((unsigned char)*pat)) { *want_io=True; }
77         else cfgfatal(loc,"polypath","invalid interface name pattern `%s'",pat);
78         int match=fnmatch(pat,ifname,0);
79         if (match==0) return True;
80         if (match!=FNM_NOMATCH)
81             cfgfatal(loc,"polypath","fnmatch failed! (pattern `%s')",pat);
82     }
83     return False;
84 }
85
86 static bool_t ifname_wanted(struct polypath *st, struct cloc loc,
87                             const char *ifname) {
88     bool_t want=False; /* pretend an empty cfg ends with !<doesn'tmatch> */
89     if (ifname_search_pats(st,loc,ifname,&want, st->ifname_pats))
90         return want;
91     if (want) /* last pattern was positive, do not search default */
92         return False;
93     if (!st->permit_loopback &&
94         ifname_search_pats(st,loc,ifname,&want, default_loopback_ifname_pats))
95         return want;
96     if (ifname_search_pats(st,loc,ifname,&want, default_ifname_pats))
97         return want;
98     abort();
99 }
100
101 static int polypath_beforepoll(void *state, struct pollfd *fds, int *nfds_io,
102                                int *timeout_io)
103 {
104     struct polypath *st=state;
105     BEFOREPOLL_WANT_FDS(1);
106     fds[0].fd=st->monitor_fd;
107     fds[0].events=POLLIN;
108     return 0;
109 }
110
111 static void dump_ppml(struct polypath *st, const char *orgl)
112 {
113 #if 0
114     struct interf *interf;
115     if (orgl)
116         lg_perror(LG,M_DEBUG,0, "polypath monitor line `%s'",orgl);
117     LIST_FOREACH(interf, &st->interfs, entry) {
118         lg_perror(LG,M_DEBUG,0, "  polypath interface `%s', nsocks=%d",
119                   interf->name, interf->socks.n_socks);
120         int i;
121         for (i=0; i<interf->socks.n_socks; i++) {
122             struct udpsock *us=&interf->socks.socks[i];
123             lg_perror(LG,M_DEBUG,0, "    polypath sock fd=%d addr=%s",
124                       us->fd, iaddr_to_string(&us->addr));
125         }
126     }
127 #endif
128 }
129
130 static void bad(struct polypath *st, char *l, char *undospace,
131                 const char *m, int ev)
132 {
133     if (undospace)
134         *undospace=' ';
135     lg_perror(LG,M_WARNING,ev,
136                "error processing polypath state change: %s"
137                " (while processing `%s')",
138                m,l);
139 }
140
141 static inline bool_t matches32(uint32_t word, uint32_t prefix, int prefixlen)
142 {
143     assert(prefixlen>0);
144     assert(prefixlen<=32);
145     uint32_t mask = ~(((uint32_t)1 << (32-prefixlen)) - 1);
146     assert(!(prefix & ~mask));
147     return (word & mask) == prefix;
148 }
149
150 static void polypath_process_monitor_line(struct polypath *st, char *orgl)
151 {
152     struct interf *interf=0;
153     struct udpcommon *uc=&st->uc;
154     char *undospace=0;
155     char *l=orgl;
156     struct udpsock *us=0;
157
158     dump_ppml(st,orgl);
159
160 #define BAD(m)     do{ bad(st,orgl,undospace,m,0);  goto out; }while(0)
161 #define BADE(m,ev) do{ bad(st,orgl,undospace,m,ev); goto out; }while(0)
162
163     bool_t add;
164     int c=*l++;
165     if (c=='+') add=True;
166     else if (c=='-') add=False;
167     else BAD("bad +/-");
168
169     int proto;
170     c=*l++;
171     if (c=='4') proto=AF_INET;
172     else if (c=='6') proto=AF_INET6;
173     else BAD("bad proto");
174
175     char *space=strchr(l,' ');
176     if (!space) BAD("no first space");
177     const char *ifname=space+1;
178
179     space=strchr(ifname,' ');
180     if (!space) BAD("no second space");
181     undospace=space;
182     *space++=0;
183     const char *ifaddr=space;
184
185     union iaddr ia;
186     FILLZERO(ia);
187     socklen_t salen=sizeof(ia);
188     int r=adns_text2addr(ifaddr,uc->port, adns_qf_addrlit_ipv4_quadonly,
189                          &ia.sa, &salen);
190     assert(r!=ENOSPC);
191     if (r) BADE("adns_text2addr",r);
192     if (ia.sa.sa_family!=proto) BAD("address family mismatch");
193
194 #define DONT(m) do{                                                     \
195         if (add)                                                        \
196             lg_perror(LG,M_INFO,0,"ignoring %s [%s]: %s",ifname,ifaddr,m); \
197         goto out;                                                       \
198     }while(0)
199
200     if (!ifname_wanted(st,st->uc.cc.loc,ifname))
201         DONT("unwanted interface name");
202
203     switch (ia.sa.sa_family) {
204     case AF_INET6: {
205         const struct in6_addr *i6=&ia.sin6.sin6_addr;
206 #define DONTKIND(X,x) \
207         if (IN6_IS_ADDR_##X(i6)) DONT("IPv6 address is " #x)
208         DONTKIND(UNSPECIFIED,unspecified);
209         DONTKIND(MULTICAST  ,multicast  );
210         DONTKIND(LINKLOCAL  ,linklocal  );
211         DONTKIND(SITELOCAL  ,sitelocal  );
212         DONTKIND(V4MAPPED   ,v4mapped   );
213         if (!st->permit_loopback)
214             DONTKIND(LOOPBACK   ,loopback   );
215 #undef DONTKIND
216 #define DONTMASK(w7x,w6x,prefixlen,m)                                   \
217         if (matches32(get_uint32(i6->s6_addr),                          \
218                       ((uint32_t)0x##w7x << 16) | (uint32_t)0x##w6x,    \
219                       prefixlen))                                       \
220             DONT("IPv6 address is " m)
221         DONTMASK( 100,   0,  8, "Discard-Only (RFC6666)");
222         DONTMASK(2001,   0, 23, "in IETF protocol block (RFC2928)");
223 #undef DONTMASK
224         break;
225     }
226     case AF_INET: {
227         const uint32_t i4=htonl(ia.sin.sin_addr.s_addr);
228         if (i4==INADDR_ANY) DONT("IPv4 address is any/unspecified");
229         if (i4==INADDR_BROADCAST) DONT("IPv4 address is all hosts broadcast");
230 #define DONTMASK(b3,b2,b1,b0,prefixlen,m) do{                           \
231             const uint8_t prefixbytes[4] = { (b3),(b2),(b1),(b0) };     \
232             if (matches32(i4,get_uint32(prefixbytes),prefixlen))        \
233                 DONT("IPv4 address is " m);                             \
234         }while(0)
235         DONTMASK(169,254,0,0, 16, "link local");
236         DONTMASK(224,  0,0,0,  4, "multicast");
237         DONTMASK(192,  0,0,0, 24, "in IETF protocol block (RFC6890)");
238         DONTMASK(240,  0,0,0,  4, "in reserved addressing block (RFC1112)");
239         if (!st->permit_loopback)
240             DONTMASK(127,  0,0,0,  8, "loopback");
241 #undef DONTMASK
242         break;
243     }
244     default:
245         abort();
246     }
247
248     /* OK, process it */
249     int n_ifs=0;
250     LIST_FOREACH(interf,&st->interfs,entry) {
251         if (!strcmp(interf->name,ifname))
252             goto found_interf;
253         n_ifs++;
254     }
255     /* not found */
256     if (n_ifs==st->max_interfs) BAD("too many interfaces");
257     interf=malloc(sizeof(*interf));
258     if (!interf) BADE("malloc for new interface",errno);
259     interf->name=0;
260     interf->socks.n_socks=0;
261     LIST_INSERT_HEAD(&st->interfs,interf,entry);
262     udp_socks_register(&st->uc,&interf->socks);
263     interf->name=strdup(ifname);
264     if (!interf->name) BADE("strdup interface name",errno);
265  found_interf:
266
267     if (add) {
268         if (interf->socks.n_socks == UDP_MAX_SOCKETS)
269             BAD("too many addresses on this interface");
270         struct udpsock *us=&interf->socks.socks[interf->socks.n_socks];
271         us->fd=-1;
272         memcpy(&us->addr,&ia,sizeof(us->addr));
273         bool_t ok=udp_make_socket(&st->uc,us,M_WARNING);
274         if (!ok) BAD("unable to set up socket");
275         r=setsockopt(us->fd,SOL_SOCKET,SO_BINDTODEVICE,
276                      ifname,strlen(ifname)+1);
277         if (r) BADE("setsockopt(,,SO_BINDTODEVICE,)",errno);
278         interf->socks.n_socks++;
279         us=0; /* do not destroy this socket during `out' */
280         lg_perror(LG,M_INFO,0,"using %s [%s]",ifname,ifaddr);
281     } else {
282         int i;
283         for (i=0;i<interf->socks.n_socks;i++)
284             if (!memcmp(&interf->socks.socks[i].addr,&ia,sizeof(ia)))
285                 goto address_remove_found;
286         BAD("address to remove not found");
287     address_remove_found:
288         lg_perror(LG,M_INFO,0,"removed %s [%s]",ifname,ifaddr);
289         udp_destroy_socket(&st->uc,&interf->socks.socks[i]);
290         interf->socks.socks[i]=
291             interf->socks.socks[--interf->socks.n_socks];
292     }
293
294  out:
295     if (us)
296         udp_destroy_socket(uc,us);
297     if (interf && !interf->socks.n_socks) {
298         udp_socks_deregister(&st->uc,&interf->socks);
299         LIST_REMOVE(interf,entry);
300         free(interf->name);
301         free(interf);
302     }
303
304     dump_ppml(st,0);
305
306 #undef BAD
307 #undef BADE
308 #undef DONT
309 }
310
311 static void polypath_afterpoll(void *state, struct pollfd *fds, int nfds)
312 {
313     struct polypath *st=state;
314     enum async_linebuf_result alr;
315     const char *emsg;
316     int status;
317
318     if (nfds<1) return;
319
320     while ((alr=async_linebuf_read(fds,&st->lbuf,&emsg)) == async_linebuf_ok)
321         polypath_process_monitor_line(st,st->lbuf.base);
322
323     if (alr==async_linebuf_nothing)
324         return;
325
326     assert(st->monitor_pid);
327
328     pid_t gotpid=waitpid(st->monitor_pid,&status,WNOHANG);
329     if (gotpid==st->monitor_pid)
330         lg_exitstatus(LG,M_FATAL,status,"interface monitor");
331     else if (gotpid<0)
332         lg_perror(LG,M_ERR,errno,"unable to reap interface monitor");
333     else
334         assert(gotpid==0);
335
336     if (alr==async_linebuf_eof)
337         lg_perror(LG,M_FATAL,0,"unexpected EOF from interface monitor");
338     else
339         lg_perror(LG,M_FATAL,0,"bad output from interface monitor: %s",emsg);
340
341     assert(!"not reached");
342 }    
343
344 static bool_t polypath_sendmsg(void *commst, struct buffer_if *buf,
345                           const struct comm_addr *dest)
346 {
347     struct polypath *st=commst;
348     struct interf *interf;
349     bool_t allreasonable=True;
350     int af=dest->ia.sa.sa_family;
351
352     LIST_FOREACH(interf,&st->interfs,entry) {
353         int i;
354         bool_t attempted=False, reasonable=False;
355         for (i=0; i<interf->socks.n_socks; i++) {
356             struct udpsock *us=&interf->socks.socks[i];
357             if (af != us->addr.sa.sa_family)
358                 continue;
359             attempted=True;
360             int r=sendto(us->fd,buf->start,buf->size,
361                          0,&dest->ia.sa,iaddr_socklen(&dest->ia));
362             udp_sock_experienced(0,&st->uc, interf->name,us,
363                                  1,af, r,errno);
364             if (r>=0) {
365                 reasonable=True;
366                 break;
367             }
368             if (!(errno==EAFNOSUPPORT || errno==ENETUNREACH))
369                 reasonable=True;
370             lg_perror(LG,M_DEBUG,errno,"xmit %"PRIu32" bytes to %s",
371                       buf->size,iaddr_to_string(&dest->ia));
372         }
373         if (!attempted)
374             if (!interf->experienced_xmit_noaf[af]++)
375                 lg_perror(LG, M_WARNING,0,
376                           "%s has no suitable address to transmit %s",
377                           interf->name, af_name(af));
378         allreasonable &= reasonable;
379     }
380     return allreasonable;
381 }
382
383 static void polypath_phase_getresources(void *sst, uint32_t newphase)
384 {
385     struct polypath *st=sst;
386     int pfds[2];
387
388     assert(!st->monitor_pid);
389     assert(st->monitor_fd<0);
390
391     pipe_cloexec(pfds);
392
393     st->monitor_pid=fork();
394     if (!st->monitor_pid) {
395         dup2(pfds[1],1);
396         execvp(st->monitor_command[0],(char**)st->monitor_command);
397         fprintf(stderr,"secnet: cannot execute %s: %s\n",
398                 st->monitor_command[0], strerror(errno));
399         exit(-1);
400     }
401     if (st->monitor_pid<0)
402         fatal_perror("%s: failed to fork for interface monitor",
403                      st->uc.cc.cl.description);
404
405     close(pfds[1]);
406     st->monitor_fd=pfds[0];
407     setnonblock(st->monitor_fd);
408
409     register_for_poll(st,polypath_beforepoll,polypath_afterpoll,"polypath");
410 }
411
412 static void polypath_phase_shutdown(void *sst, uint32_t newphase)
413 {
414     struct polypath *st=sst;
415     if (st->monitor_pid)
416         kill(SIGTERM,st->monitor_pid);
417 }
418
419 static list_t *polypath_apply(closure_t *self, struct cloc loc,
420                               dict_t *context, list_t *args)
421 {
422     struct polypath *st;
423
424     COMM_APPLY(st,&st->uc.cc,polypath_,"polypath",loc);
425     COMM_APPLY_STANDARD(st,&st->uc.cc,"polypath",args);
426     UDP_APPLY_STANDARD(st,&st->uc,"polypath");
427
428     struct udpcommon *uc=&st->uc;
429     struct commcommon *cc=&uc->cc;
430
431     uc->authbind=dict_read_string(d,"authbind",False,"udp",cc->loc);
432     st->max_interfs=dict_read_number(d,"max-interfaces",False,"polypath",loc,3);
433
434     st->ifname_pats=dict_read_string_array(d,"interfaces",False,"polypath",
435                                            cc->loc,0);
436     ifname_wanted(st,st->uc.cc.loc,"dummy"); /* walks and checks */
437
438     st->monitor_command=dict_read_string_array(d,"monitor-command",False,
439                                "polypath",cc->loc, default_monitor_command);
440     if (!st->monitor_command[0])
441         cfgfatal(loc,"tun","no polypath interface monitor-command"
442                  " (polypath unsupported on this platform?)\n");
443
444     st->permit_loopback=dict_read_bool(d,"permit-loopback",False,
445                                        "polypath",cc->loc,False);
446
447     LIST_INIT(&st->interfs);
448     buffer_new(&st->lbuf,ADNS_ADDR2TEXT_BUFLEN+100);
449     BUF_ALLOC(&st->lbuf,"polypath lbuf");
450
451     st->monitor_fd=-1;
452     st->monitor_pid=0;
453
454     add_hook(PHASE_GETRESOURCES,polypath_phase_getresources,st);
455     add_hook(PHASE_SHUTDOWN,    polypath_phase_shutdown,    st);
456
457     return new_closure(&cc->cl);
458 }
459
460 #endif /* CONFIG_IPV6 */
461
462 void polypath_module(dict_t *dict)
463 {
464 #ifdef CONFIG_IPV6
465     add_closure(dict,"polypath",polypath_apply);
466 #endif /* CONFIG_IPV6 */
467 }