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+1];
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     "!tun*","!tap*","!sl*","!userv*", "*", 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 #ifdef POLYPATH_DEBUG
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     const char *ifaddr=space+1;
182     *space=0;
183     undospace=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,m) \
207         if (IN6_IS_ADDR_##X(i6)) DONT("IPv6 address is " m)
208         DONTKIND(UNSPECIFIED, "unspecified");
209         DONTKIND(MULTICAST  , "multicast"  );
210         DONTKIND(LINKLOCAL  , "link local" );
211         DONTKIND(SITELOCAL  , "site local" );
212         DONTKIND(V4MAPPED   , "v4-mapped"  );
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     FILLZERO(interf->experienced_xmit_noaf);
262     LIST_INSERT_HEAD(&st->interfs,interf,entry);
263     udp_socks_register(&st->uc,&interf->socks);
264     interf->name=strdup(ifname);
265     if (!interf->name) BADE("strdup interface name",errno);
266  found_interf:
267
268     if (add) {
269         if (interf->socks.n_socks == UDP_MAX_SOCKETS)
270             BAD("too many addresses on this interface");
271         struct udpsock *us=&interf->socks.socks[interf->socks.n_socks];
272         us->fd=-1;
273         COPY_OBJ(us->addr,ia);
274         bool_t ok=udp_make_socket(&st->uc,us,M_WARNING);
275         if (!ok) BAD("unable to set up socket");
276         r=setsockopt(us->fd,SOL_SOCKET,SO_BINDTODEVICE,
277                      ifname,strlen(ifname)+1);
278         if (r) BADE("setsockopt(,,SO_BINDTODEVICE,)",errno);
279         interf->socks.n_socks++;
280         us=0; /* do not destroy this socket during `out' */
281         lg_perror(LG,M_INFO,0,"using %s %s",ifname,ifaddr);
282     } else {
283         int i;
284         for (i=0; i<interf->socks.n_socks; i++)
285             if (!memcmp(&interf->socks.socks[i].addr,&ia,sizeof(ia)))
286                 goto address_remove_found;
287         BAD("address to remove not found");
288     address_remove_found:
289         lg_perror(LG,M_INFO,0,"removed %s %s",ifname,ifaddr);
290         udp_destroy_socket(&st->uc,&interf->socks.socks[i]);
291         interf->socks.socks[i]=
292             interf->socks.socks[--interf->socks.n_socks];
293     }
294
295  out:
296     if (us)
297         udp_destroy_socket(uc,us);
298     if (interf && !interf->socks.n_socks) {
299         udp_socks_deregister(&st->uc,&interf->socks);
300         LIST_REMOVE(interf,entry);
301         free(interf->name);
302         free(interf);
303     }
304
305     dump_ppml(st,0);
306
307 #undef BAD
308 #undef BADE
309 #undef DONT
310 }
311
312 static void polypath_afterpoll(void *state, struct pollfd *fds, int nfds)
313 {
314     struct polypath *st=state;
315     enum async_linebuf_result alr;
316     const char *emsg;
317     int status;
318
319     if (nfds<1) return;
320
321     while ((alr=async_linebuf_read(fds,&st->lbuf,&emsg)) == async_linebuf_ok)
322         polypath_process_monitor_line(st,st->lbuf.base);
323
324     if (alr==async_linebuf_nothing)
325         return;
326
327     assert(st->monitor_pid);
328
329     pid_t gotpid=waitpid(st->monitor_pid,&status,WNOHANG);
330     if (gotpid==st->monitor_pid) {
331         st->monitor_pid=0;
332         lg_exitstatus(LG,M_FATAL,status,"interface monitor");
333     } else if (gotpid<0)
334         lg_perror(LG,M_ERR,errno,"unable to reap interface monitor");
335     else
336         assert(gotpid==0);
337
338     if (alr==async_linebuf_eof)
339         lg_perror(LG,M_FATAL,0,"unexpected EOF from interface monitor");
340     else
341         lg_perror(LG,M_FATAL,0,"bad output from interface monitor: %s",emsg);
342
343     assert(!"not reached");
344 }
345
346 /* Actual udp packet sending work */
347 static bool_t polypath_sendmsg(void *commst, struct buffer_if *buf,
348                           const struct comm_addr *dest)
349 {
350     struct polypath *st=commst;
351     struct interf *interf;
352     bool_t allreasonable=True;
353     int af=dest->ia.sa.sa_family;
354
355     LIST_FOREACH(interf,&st->interfs,entry) {
356         int i;
357         bool_t attempted=False, reasonable=False;
358         for (i=0; i<interf->socks.n_socks; i++) {
359             struct udpsock *us=&interf->socks.socks[i];
360             if (af != us->addr.sa.sa_family)
361                 continue;
362             attempted=True;
363             int r=sendto(us->fd,buf->start,buf->size,
364                          0,&dest->ia.sa,iaddr_socklen(&dest->ia));
365             udp_sock_experienced(0,&st->uc, interf->name,us,
366                                  1,af, r,errno);
367             if (r>=0) {
368                 reasonable=True;
369                 break;
370             }
371             if (!(errno==EAFNOSUPPORT || errno==ENETUNREACH))
372                 reasonable=True;
373             lg_perror(LG,M_DEBUG,errno,"%s [%s] xmit %"PRIu32" bytes to %s",
374                       interf->name,iaddr_to_string(&us->addr),
375                       buf->size,iaddr_to_string(&dest->ia));
376         }
377         if (!attempted)
378             if (!interf->experienced_xmit_noaf[af]++)
379                 lg_perror(LG,M_WARNING,0,
380                           "%s has no suitable address to transmit %s",
381                           interf->name, af_name(af));
382         allreasonable *= reasonable;
383     }
384     return allreasonable;
385 }
386
387 static void polypath_phase_startmonitor(void *sst, uint32_t newphase)
388 {
389     struct polypath *st=sst;
390     int pfds[2];
391
392     assert(!st->monitor_pid);
393     assert(st->monitor_fd<0);
394
395     pipe_cloexec(pfds);
396
397     pid_t pid=fork();
398     if (!pid) {
399         afterfork();
400         dup2(pfds[1],1);
401         execvp(st->monitor_command[0],(char**)st->monitor_command);
402         fprintf(stderr,"secnet: cannot execute %s: %s\n",
403                 st->monitor_command[0], strerror(errno));
404         exit(-1);
405     }
406     if (pid<0)
407         fatal_perror("%s: failed to fork for interface monitor",
408                      st->uc.cc.cl.description);
409
410     close(pfds[1]);
411     st->monitor_pid=pid;
412     st->monitor_fd=pfds[0];
413     setnonblock(st->monitor_fd);
414
415     register_for_poll(st,polypath_beforepoll,polypath_afterpoll,"polypath");
416 }
417
418 static void polypath_phase_shutdown(void *sst, uint32_t newphase)
419 {
420     struct polypath *st=sst;
421     if (st->monitor_pid) {
422         assert(st->monitor_pid>0);
423         kill(st->monitor_pid,SIGTERM);
424     }
425 }
426
427 static list_t *polypath_apply(closure_t *self, struct cloc loc,
428                               dict_t *context, list_t *args)
429 {
430     struct polypath *st;
431
432     COMM_APPLY(st,&st->uc.cc,polypath_,"polypath",loc);
433     COMM_APPLY_STANDARD(st,&st->uc.cc,"polypath",args);
434     UDP_APPLY_STANDARD(st,&st->uc,"polypath");
435
436     struct udpcommon *uc=&st->uc;
437     struct commcommon *cc=&uc->cc;
438
439     st->max_interfs=dict_read_number(d,"max-interfaces",False,"polypath",loc,3);
440
441     st->ifname_pats=dict_read_string_array(d,"interfaces",False,"polypath",
442                                            cc->loc,0);
443     st->permit_loopback=0; /* ifname_wanted reads this */
444     ifname_wanted(st,st->uc.cc.loc," "); /* try to check each pattern */
445
446     st->monitor_command=dict_read_string_array(d,"monitor-command",False,
447                                "polypath",cc->loc, default_monitor_command);
448     if (!st->monitor_command[0])
449         cfgfatal(loc,"polypath","no polypath interface monitor-command"
450                  " (polypath unsupported on this platform?)\n");
451
452     st->permit_loopback=dict_read_bool(d,"permit-loopback",False,
453                                        "polypath",cc->loc,False);
454
455     LIST_INIT(&st->interfs);
456     buffer_new(&st->lbuf,ADNS_ADDR2TEXT_BUFLEN+100);
457     BUF_ALLOC(&st->lbuf,"polypath lbuf");
458
459     st->monitor_fd=-1;
460     st->monitor_pid=0;
461
462     add_hook(PHASE_RUN,         polypath_phase_startmonitor,st);
463     add_hook(PHASE_SHUTDOWN,    polypath_phase_shutdown,    st);
464
465     return new_closure(&cc->cl);
466 }
467
468 #endif /* CONFIG_IPV6 */
469
470 void polypath_module(dict_t *dict)
471 {
472 #ifdef CONFIG_IPV6
473     add_closure(dict,"polypath",polypath_apply);
474 #endif /* CONFIG_IPV6 */
475 }