polypath: Reorganise to break up ifaddr handling
[secnet] / 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 inline bool_t matches32(uint32_t word, uint32_t prefix, int prefixlen)
112 {
113 assert(prefixlen>0);
114 assert(prefixlen<=32);
115 uint32_t mask = ~(((uint32_t)1 << (32-prefixlen)) - 1);
116 assert(!(prefix & ~mask));
117 return (word & mask) == prefix;
118 }
119
120 /* These macros expect
121 * bad_fn_type *const bad;
122 * void *badctx;
123 * and
124 * out:
125 */
126 #define BAD(m) do{ bad(st,badctx,m,0); goto out; }while(0)
127 #define BADE(m,ev) do{ bad(st,badctx,m,ev); goto out; }while(0)
128 typedef void bad_fn_type(struct polypath *st, void *badctx,
129 const char* m, int ev);
130
131 typedef void polypath_ppml_callback_type(struct polypath *st,
132 bad_fn_type *bad, void *badctx,
133 bool_t add, const char *ifname, const char *ifaddr,
134 const union iaddr *ia, int fd /* -1 if none yet */);
135
136 struct ppml_bad_ctx {
137 const char *orgl;
138 char *undospace;
139 };
140
141 static void ppml_bad(struct polypath *st, void *badctx, const char *m, int ev)
142 {
143 struct ppml_bad_ctx *bc=badctx;
144 if (bc->undospace)
145 *(bc->undospace)=' ';
146 lg_perror(LG,M_WARNING,ev,
147 "error processing polypath state change: %s"
148 " (while processing `%s')",
149 m,bc->orgl);
150 }
151
152 static void polypath_process_monitor_line(struct polypath *st, char *orgl,
153 polypath_ppml_callback_type *callback)
154 /* always calls callback with fd==-1 */
155 {
156 struct udpcommon *uc=&st->uc;
157 char *l=orgl;
158 bad_fn_type (*const bad)=ppml_bad;
159 struct ppml_bad_ctx badctx[1]={{
160 .orgl=orgl,
161 .undospace=0
162 }};
163
164 bool_t add;
165 int c=*l++;
166 if (c=='+') add=True;
167 else if (c=='-') add=False;
168 else BAD("bad +/-");
169
170 int proto;
171 c=*l++;
172 if (c=='4') proto=AF_INET;
173 else if (c=='6') proto=AF_INET6;
174 else BAD("bad proto");
175
176 char *space=strchr(l,' ');
177 if (!space) BAD("no first space");
178 const char *ifname=space+1;
179
180 space=strchr(ifname,' ');
181 if (!space) BAD("no second space");
182 const char *ifaddr=space+1;
183 *space=0;
184 badctx->undospace=space;
185
186 union iaddr ia;
187 FILLZERO(ia);
188 socklen_t salen=sizeof(ia);
189 int r=adns_text2addr(ifaddr,uc->port, adns_qf_addrlit_ipv4_quadonly,
190 &ia.sa, &salen);
191 assert(r!=ENOSPC);
192 if (r) BADE("adns_text2addr",r);
193 if (ia.sa.sa_family!=proto) BAD("address family mismatch");
194
195 #define DONT(m) do{ \
196 if (add) \
197 lg_perror(LG,M_INFO,0,"ignoring %s [%s]: %s",ifname,ifaddr,m); \
198 goto out; \
199 }while(0)
200
201 if (!ifname_wanted(st,st->uc.cc.loc,ifname))
202 DONT("unwanted interface name");
203
204 switch (ia.sa.sa_family) {
205 case AF_INET6: {
206 const struct in6_addr *i6=&ia.sin6.sin6_addr;
207 #define DONTKIND(X,m) \
208 if (IN6_IS_ADDR_##X(i6)) DONT("IPv6 address is " m)
209 DONTKIND(UNSPECIFIED, "unspecified");
210 DONTKIND(MULTICAST , "multicast" );
211 DONTKIND(LINKLOCAL , "link local" );
212 DONTKIND(SITELOCAL , "site local" );
213 DONTKIND(V4MAPPED , "v4-mapped" );
214 if (!st->permit_loopback)
215 DONTKIND(LOOPBACK , "loopback" );
216 #undef DONTKIND
217 #define DONTMASK(w7x,w6x,prefixlen,m) \
218 if (matches32(get_uint32(i6->s6_addr), \
219 ((uint32_t)0x##w7x << 16) | (uint32_t)0x##w6x, \
220 prefixlen)) \
221 DONT("IPv6 address is " m)
222 DONTMASK( 100, 0, 8, "Discard-Only (RFC6666)");
223 DONTMASK(2001, 0, 23, "in IETF protocol block (RFC2928)");
224 #undef DONTMASK
225 break;
226 }
227 case AF_INET: {
228 const uint32_t i4=htonl(ia.sin.sin_addr.s_addr);
229 if (i4==INADDR_ANY) DONT("IPv4 address is any/unspecified");
230 if (i4==INADDR_BROADCAST) DONT("IPv4 address is all hosts broadcast");
231 #define DONTMASK(b3,b2,b1,b0,prefixlen,m) do{ \
232 const uint8_t prefixbytes[4] = { (b3),(b2),(b1),(b0) }; \
233 if (matches32(i4,get_uint32(prefixbytes),prefixlen)) \
234 DONT("IPv4 address is " m); \
235 }while(0)
236 DONTMASK(169,254,0,0, 16, "link local");
237 DONTMASK(224, 0,0,0, 4, "multicast");
238 DONTMASK(192, 0,0,0, 24, "in IETF protocol block (RFC6890)");
239 DONTMASK(240, 0,0,0, 4, "in reserved addressing block (RFC1112)");
240 if (!st->permit_loopback)
241 DONTMASK(127, 0,0,0, 8, "loopback");
242 #undef DONTMASK
243 break;
244 }
245 default:
246 abort();
247 }
248
249 #undef DONT
250
251 /* OK, process it */
252 callback(st, bad,badctx, add,ifname,ifaddr,&ia,-1);
253
254 out:;
255 }
256
257 static void dump_pria(struct polypath *st, const char *ifname)
258 {
259 #ifdef POLYPATH_DEBUG
260 struct interf *interf;
261 if (ifname)
262 lg_perror(LG,M_DEBUG,0, "polypath record ifaddr `%s'",ifname);
263 LIST_FOREACH(interf, &st->interfs, entry) {
264 lg_perror(LG,M_DEBUG,0, " polypath interface `%s', nsocks=%d",
265 interf->name, interf->socks.n_socks);
266 int i;
267 for (i=0; i<interf->socks.n_socks; i++) {
268 struct udpsock *us=&interf->socks.socks[i];
269 lg_perror(LG,M_DEBUG,0, " polypath sock fd=%d addr=%s",
270 us->fd, iaddr_to_string(&us->addr));
271 }
272 }
273 #endif
274 }
275
276 static bool_t polypath_make_socket(struct polypath *st,
277 bad_fn_type *bad, void *badctx,
278 struct udpsock *us, const char *ifname)
279 /* on error exit has called bad; might leave us->fd as -1 */
280 {
281 assert(us->fd==-1);
282
283 bool_t ok=udp_make_socket(&st->uc,us,M_WARNING);
284 if (!ok) BAD("unable to set up socket");
285 int r=setsockopt(us->fd,SOL_SOCKET,SO_BINDTODEVICE,
286 ifname,strlen(ifname)+1);
287 if (r) BADE("setsockopt(,,SO_BINDTODEVICE,)",errno);
288 return True;
289
290 out:
291 return False;
292 }
293
294 static void polypath_record_ifaddr(struct polypath *st,
295 bad_fn_type *bad, void *badctx,
296 bool_t add, const char *ifname,
297 const char *ifaddr,
298 const union iaddr *ia, int fd)
299 {
300 struct udpcommon *uc=&st->uc;
301 struct interf *interf=0;
302 struct udpsock *us=0;
303
304 dump_pria(st,ifname);
305
306 int n_ifs=0;
307 LIST_FOREACH(interf,&st->interfs,entry) {
308 if (!strcmp(interf->name,ifname))
309 goto found_interf;
310 n_ifs++;
311 }
312 /* not found */
313 if (n_ifs==st->max_interfs) BAD("too many interfaces");
314 interf=malloc(sizeof(*interf));
315 if (!interf) BADE("malloc for new interface",errno);
316 interf->name=0;
317 interf->socks.n_socks=0;
318 FILLZERO(interf->experienced_xmit_noaf);
319 LIST_INSERT_HEAD(&st->interfs,interf,entry);
320 udp_socks_register(&st->uc,&interf->socks);
321 interf->name=strdup(ifname);
322 if (!interf->name) BADE("strdup interface name",errno);
323 found_interf:
324
325 if (add) {
326 if (interf->socks.n_socks == UDP_MAX_SOCKETS)
327 BAD("too many addresses on this interface");
328 struct udpsock *us=&interf->socks.socks[interf->socks.n_socks];
329 us->fd=-1;
330 COPY_OBJ(us->addr,*ia);
331 if (fd<0) {
332 bool_t ok=polypath_make_socket(st,bad,badctx, us,ifname);
333 if (!ok) goto out;
334 } else {
335 FILLZERO(us->experienced);
336 us->fd=fd;
337 fd=-1;
338 }
339 interf->socks.n_socks++;
340 us=0; /* do not destroy this socket during `out' */
341 lg_perror(LG,M_INFO,0,"using %s %s",ifname,ifaddr);
342 } else {
343 int i;
344 for (i=0; i<interf->socks.n_socks; i++)
345 if (!memcmp(&interf->socks.socks[i].addr,ia,sizeof(*ia)))
346 goto address_remove_found;
347 BAD("address to remove not found");
348 address_remove_found:
349 lg_perror(LG,M_INFO,0,"removed %s %s",ifname,ifaddr);
350 udp_destroy_socket(&st->uc,&interf->socks.socks[i]);
351 interf->socks.socks[i]=
352 interf->socks.socks[--interf->socks.n_socks];
353 }
354
355 out:
356 if (us)
357 udp_destroy_socket(uc,us);
358 if (fd>=0)
359 close(fd);
360 if (interf && !interf->socks.n_socks) {
361 udp_socks_deregister(&st->uc,&interf->socks);
362 LIST_REMOVE(interf,entry);
363 free(interf->name);
364 free(interf);
365 }
366
367 dump_pria(st,0);
368 }
369
370 static void polypath_afterpoll(void *state, struct pollfd *fds, int nfds)
371 {
372 struct polypath *st=state;
373 enum async_linebuf_result alr;
374 const char *emsg;
375 int status;
376
377 if (nfds<1) return;
378
379 while ((alr=async_linebuf_read(fds,&st->lbuf,&emsg)) == async_linebuf_ok)
380 polypath_process_monitor_line(st,st->lbuf.base,
381 polypath_record_ifaddr);
382
383 if (alr==async_linebuf_nothing)
384 return;
385
386 assert(st->monitor_pid);
387
388 pid_t gotpid=waitpid(st->monitor_pid,&status,WNOHANG);
389 if (gotpid==st->monitor_pid) {
390 st->monitor_pid=0;
391 lg_exitstatus(LG,M_FATAL,status,"interface monitor");
392 } else if (gotpid<0)
393 lg_perror(LG,M_ERR,errno,"unable to reap interface monitor");
394 else
395 assert(gotpid==0);
396
397 if (alr==async_linebuf_eof)
398 lg_perror(LG,M_FATAL,0,"unexpected EOF from interface monitor");
399 else
400 lg_perror(LG,M_FATAL,0,"bad output from interface monitor: %s",emsg);
401
402 assert(!"not reached");
403 }
404
405 /* Actual udp packet sending work */
406 static bool_t polypath_sendmsg(void *commst, struct buffer_if *buf,
407 const struct comm_addr *dest)
408 {
409 struct polypath *st=commst;
410 struct interf *interf;
411 bool_t allreasonable=True;
412 int af=dest->ia.sa.sa_family;
413
414 LIST_FOREACH(interf,&st->interfs,entry) {
415 int i;
416 bool_t attempted=False, reasonable=False;
417 for (i=0; i<interf->socks.n_socks; i++) {
418 struct udpsock *us=&interf->socks.socks[i];
419 if (af != us->addr.sa.sa_family)
420 continue;
421 attempted=True;
422 int r=sendto(us->fd,buf->start,buf->size,
423 0,&dest->ia.sa,iaddr_socklen(&dest->ia));
424 udp_sock_experienced(0,&st->uc, interf->name,us,
425 1,af, r,errno);
426 if (r>=0) {
427 reasonable=True;
428 break;
429 }
430 if (!(errno==EAFNOSUPPORT || errno==ENETUNREACH))
431 reasonable=True;
432 lg_perror(LG,M_DEBUG,errno,"%s [%s] xmit %"PRIu32" bytes to %s",
433 interf->name,iaddr_to_string(&us->addr),
434 buf->size,iaddr_to_string(&dest->ia));
435 }
436 if (!attempted)
437 if (!interf->experienced_xmit_noaf[af]++)
438 lg_perror(LG,M_WARNING,0,
439 "%s has no suitable address to transmit %s",
440 interf->name, af_name(af));
441 allreasonable *= reasonable;
442 }
443 return allreasonable;
444 }
445
446 static void polypath_phase_startmonitor(void *sst, uint32_t newphase)
447 {
448 struct polypath *st=sst;
449 int pfds[2];
450
451 assert(!st->monitor_pid);
452 assert(st->monitor_fd<0);
453
454 pipe_cloexec(pfds);
455
456 pid_t pid=fork();
457 if (!pid) {
458 afterfork();
459 dup2(pfds[1],1);
460 execvp(st->monitor_command[0],(char**)st->monitor_command);
461 fprintf(stderr,"secnet: cannot execute %s: %s\n",
462 st->monitor_command[0], strerror(errno));
463 exit(-1);
464 }
465 if (pid<0)
466 fatal_perror("%s: failed to fork for interface monitor",
467 st->uc.cc.cl.description);
468
469 close(pfds[1]);
470 st->monitor_pid=pid;
471 st->monitor_fd=pfds[0];
472 setnonblock(st->monitor_fd);
473
474 register_for_poll(st,polypath_beforepoll,polypath_afterpoll,"polypath");
475 }
476
477 static void polypath_phase_shutdown(void *sst, uint32_t newphase)
478 {
479 struct polypath *st=sst;
480 if (st->monitor_pid) {
481 assert(st->monitor_pid>0);
482 kill(st->monitor_pid,SIGTERM);
483 }
484 }
485
486 #undef BAD
487 #undef BADE
488
489 static list_t *polypath_apply(closure_t *self, struct cloc loc,
490 dict_t *context, list_t *args)
491 {
492 struct polypath *st;
493
494 COMM_APPLY(st,&st->uc.cc,polypath_,"polypath",loc);
495 COMM_APPLY_STANDARD(st,&st->uc.cc,"polypath",args);
496 UDP_APPLY_STANDARD(st,&st->uc,"polypath");
497
498 struct udpcommon *uc=&st->uc;
499 struct commcommon *cc=&uc->cc;
500
501 st->max_interfs=dict_read_number(d,"max-interfaces",False,"polypath",loc,3);
502
503 st->ifname_pats=dict_read_string_array(d,"interfaces",False,"polypath",
504 cc->loc,0);
505 st->permit_loopback=0; /* ifname_wanted reads this */
506 ifname_wanted(st,st->uc.cc.loc," "); /* try to check each pattern */
507
508 st->monitor_command=dict_read_string_array(d,"monitor-command",False,
509 "polypath",cc->loc, default_monitor_command);
510 if (!st->monitor_command[0])
511 cfgfatal(loc,"polypath","no polypath interface monitor-command"
512 " (polypath unsupported on this platform?)\n");
513
514 st->permit_loopback=dict_read_bool(d,"permit-loopback",False,
515 "polypath",cc->loc,False);
516
517 LIST_INIT(&st->interfs);
518 buffer_new(&st->lbuf,ADNS_ADDR2TEXT_BUFLEN+100);
519 BUF_ALLOC(&st->lbuf,"polypath lbuf");
520
521 st->monitor_fd=-1;
522 st->monitor_pid=0;
523
524 add_hook(PHASE_RUN, polypath_phase_startmonitor,st);
525 add_hook(PHASE_SHUTDOWN, polypath_phase_shutdown, st);
526
527 return new_closure(&cc->cl);
528 }
529
530 #endif /* CONFIG_IPV6 */
531
532 void polypath_module(dict_t *dict)
533 {
534 #ifdef CONFIG_IPV6
535 add_closure(dict,"polypath",polypath_apply);
536 #endif /* CONFIG_IPV6 */
537 }