polypath: Break out polypath_sendmsg_interf
[secnet] / polypath.c
CommitLineData
ce5c098f
IJ
1/* polypath
2 * send/receive module for secnet
3 * for multi-route setups */
c215a4bc
IJ
4/*
5 * This file is part of secnet.
6 * See README for full list of copyright holders.
7 *
8 * secnet is free software; you can redistribute it and/or modify it
9 * under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version d of the License, or
11 * (at your option) any later version.
12 *
13 * secnet is distributed in the hope that it will be useful, but
14 * WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * version 3 along with secnet; if not, see
20 * https://www.gnu.org/licenses/gpl.html.
21 */
ce5c098f
IJ
22
23#include "secnet.h"
24#include "util.h"
25#include "unaligned.h"
26#include "comm-common.h"
27
28#include <adns.h>
29#include <ctype.h>
30
31#ifdef CONFIG_IPV6
32
33static comm_sendmsg_fn polypath_sendmsg;
34
35struct interf {
36 char *name; /* from malloc */
37 struct udpsocks socks;
38 bool_t experienced_xmit_noaf[MAX_AF+1];
39 LIST_ENTRY(interf) entry;
40};
41
42struct polypath {
43 struct udpcommon uc;
44 int max_interfs;
45 const char *const *ifname_pats;
46 const char *const *monitor_command;
47 bool_t permit_loopback;
65d6d32e 48 LIST_HEAD(interf_list, interf) interfs;
ce5c098f
IJ
49 struct buffer_if lbuf;
50 int monitor_fd;
51 pid_t monitor_pid;
93cdea57
IJ
52 int privsep_incoming_fd;
53 int privsep_ipcsock_fd;
ce5c098f
IJ
54};
55
93cdea57
IJ
56static void polypath_phase_shutdown(void *sst, uint32_t newphase);
57
ce5c098f
IJ
58#define LG 0, st->uc.cc.cl.description, &st->uc.cc.loc
59
60static const char *const default_loopback_ifname_pats[] = {
61 "!lo", 0
62};
63static const char *const default_ifname_pats[] = {
64 "!tun*","!tap*","!sl*","!userv*", "*", 0
65};
66
67static const char *const default_monitor_command[] = {
e61a41a4
IJ
68#if __linux__
69 DATAROOTDIR "/secnet/" "polypath-interface-monitor-linux", 0
70#else
ce5c098f 71 0
e61a41a4 72#endif
ce5c098f
IJ
73};
74
75static const char *polypath_addr_to_string(void *commst,
76 const struct comm_addr *ca)
77{
78 static char sbuf[100];
79
80 snprintf(sbuf, sizeof(sbuf), "polypath:%s",
81 iaddr_to_string(&ca->ia));
82 return sbuf;
83}
84
85static bool_t ifname_search_pats(struct polypath *st, struct cloc loc,
7b713549 86 const char *ifname, char *want_io,
ce5c098f
IJ
87 const char *const *pats) {
88 /* Returns True iff we found a list entry, in which case *want_io
89 * is set to the sense of that entry. Otherwise *want_io is set
90 * to the sense of the last entry, or unchanged if there were no pats. */
91 if (!pats)
92 return False;
93 const char *const *pati;
94 for (pati=pats; *pati; pati++) {
95 const char *pat=*pati;
7b713549
IJ
96 if (*pat=='!' || *pat=='+') { *want_io=*pat; pat++; }
97 else if (*pat=='*' || isalnum((unsigned char)*pat)) { *want_io='+'; }
ce5c098f
IJ
98 else cfgfatal(loc,"polypath","invalid interface name pattern `%s'",pat);
99 int match=fnmatch(pat,ifname,0);
100 if (match==0) return True;
101 if (match!=FNM_NOMATCH)
102 cfgfatal(loc,"polypath","fnmatch failed! (pattern `%s')",pat);
103 }
104 return False;
105}
106
7b713549
IJ
107static char ifname_wanted(struct polypath *st, struct cloc loc,
108 const char *ifname) {
109 char want='!'; /* pretend an empty cfg ends with !<doesn'tmatch> */
ce5c098f
IJ
110 if (ifname_search_pats(st,loc,ifname,&want, st->ifname_pats))
111 return want;
7b713549
IJ
112 if (want!='!') /* last pattern was positive, do not search default */
113 return '!';
ce5c098f
IJ
114 if (!st->permit_loopback &&
115 ifname_search_pats(st,loc,ifname,&want, default_loopback_ifname_pats))
116 return want;
117 if (ifname_search_pats(st,loc,ifname,&want, default_ifname_pats))
118 return want;
119 abort();
120}
121
122static int polypath_beforepoll(void *state, struct pollfd *fds, int *nfds_io,
123 int *timeout_io)
124{
125 struct polypath *st=state;
126 BEFOREPOLL_WANT_FDS(1);
127 fds[0].fd=st->monitor_fd;
128 fds[0].events=POLLIN;
129 return 0;
130}
131
ce5c098f
IJ
132static inline bool_t matches32(uint32_t word, uint32_t prefix, int prefixlen)
133{
134 assert(prefixlen>0);
135 assert(prefixlen<=32);
136 uint32_t mask = ~(((uint32_t)1 << (32-prefixlen)) - 1);
137 assert(!(prefix & ~mask));
138 return (word & mask) == prefix;
139}
140
70ad8e2c
IJ
141/* These macros expect
142 * bad_fn_type *const bad;
143 * void *badctx;
144 * and
145 * out:
146 */
84dcd42d
IJ
147#define BAD(m) do{ bad(st,badctx,M_WARNING,m,0); goto out; }while(0)
148#define BADE(m,ev) do{ bad(st,badctx,M_WARNING,m,ev); goto out; }while(0)
70ad8e2c 149typedef void bad_fn_type(struct polypath *st, void *badctx,
84dcd42d 150 int mclass, const char* m, int ev);
70ad8e2c
IJ
151
152typedef void polypath_ppml_callback_type(struct polypath *st,
153 bad_fn_type *bad, void *badctx,
65d6d32e
IJ
154 bool_t add, char want,
155 const char *ifname, const char *ifaddr,
70ad8e2c
IJ
156 const union iaddr *ia, int fd /* -1 if none yet */);
157
158struct ppml_bad_ctx {
159 const char *orgl;
160 char *undospace;
161};
162
84dcd42d
IJ
163static void ppml_bad(struct polypath *st, void *badctx,
164 int mclass, const char *m, int ev)
70ad8e2c
IJ
165{
166 struct ppml_bad_ctx *bc=badctx;
167 if (bc->undospace)
168 *(bc->undospace)=' ';
84dcd42d 169 lg_perror(LG,mclass,ev,
70ad8e2c
IJ
170 "error processing polypath state change: %s"
171 " (while processing `%s')",
172 m,bc->orgl);
173}
174
175static void polypath_process_monitor_line(struct polypath *st, char *orgl,
176 polypath_ppml_callback_type *callback)
177 /* always calls callback with fd==-1 */
ce5c098f 178{
ce5c098f 179 struct udpcommon *uc=&st->uc;
ce5c098f 180 char *l=orgl;
70ad8e2c
IJ
181 bad_fn_type (*const bad)=ppml_bad;
182 struct ppml_bad_ctx badctx[1]={{
183 .orgl=orgl,
184 .undospace=0
185 }};
ce5c098f
IJ
186
187 bool_t add;
188 int c=*l++;
189 if (c=='+') add=True;
190 else if (c=='-') add=False;
191 else BAD("bad +/-");
192
193 int proto;
194 c=*l++;
195 if (c=='4') proto=AF_INET;
196 else if (c=='6') proto=AF_INET6;
197 else BAD("bad proto");
198
199 char *space=strchr(l,' ');
200 if (!space) BAD("no first space");
201 const char *ifname=space+1;
202
203 space=strchr(ifname,' ');
204 if (!space) BAD("no second space");
205 const char *ifaddr=space+1;
206 *space=0;
70ad8e2c 207 badctx->undospace=space;
ce5c098f
IJ
208
209 union iaddr ia;
210 FILLZERO(ia);
211 socklen_t salen=sizeof(ia);
212 int r=adns_text2addr(ifaddr,uc->port, adns_qf_addrlit_ipv4_quadonly,
213 &ia.sa, &salen);
214 assert(r!=ENOSPC);
215 if (r) BADE("adns_text2addr",r);
216 if (ia.sa.sa_family!=proto) BAD("address family mismatch");
217
218#define DONT(m) do{ \
219 if (add) \
220 lg_perror(LG,M_INFO,0,"ignoring %s [%s]: %s",ifname,ifaddr,m); \
221 goto out; \
222 }while(0)
223
7b713549
IJ
224 char want=ifname_wanted(st,st->uc.cc.loc,ifname);
225 if (want=='!') DONT("unwanted interface name");
ce5c098f
IJ
226
227 switch (ia.sa.sa_family) {
228 case AF_INET6: {
229 const struct in6_addr *i6=&ia.sin6.sin6_addr;
230#define DONTKIND(X,m) \
231 if (IN6_IS_ADDR_##X(i6)) DONT("IPv6 address is " m)
232 DONTKIND(UNSPECIFIED, "unspecified");
233 DONTKIND(MULTICAST , "multicast" );
234 DONTKIND(LINKLOCAL , "link local" );
235 DONTKIND(SITELOCAL , "site local" );
236 DONTKIND(V4MAPPED , "v4-mapped" );
237 if (!st->permit_loopback)
238 DONTKIND(LOOPBACK , "loopback" );
239#undef DONTKIND
240#define DONTMASK(w7x,w6x,prefixlen,m) \
241 if (matches32(get_uint32(i6->s6_addr), \
242 ((uint32_t)0x##w7x << 16) | (uint32_t)0x##w6x, \
243 prefixlen)) \
244 DONT("IPv6 address is " m)
245 DONTMASK( 100, 0, 8, "Discard-Only (RFC6666)");
246 DONTMASK(2001, 0, 23, "in IETF protocol block (RFC2928)");
b073e347 247 DONTMASK(fc00, 0, 7, "Uniqe Local unicast (RFC4193)");
ce5c098f
IJ
248#undef DONTMASK
249 break;
250 }
251 case AF_INET: {
252 const uint32_t i4=htonl(ia.sin.sin_addr.s_addr);
253 if (i4==INADDR_ANY) DONT("IPv4 address is any/unspecified");
254 if (i4==INADDR_BROADCAST) DONT("IPv4 address is all hosts broadcast");
255#define DONTMASK(b3,b2,b1,b0,prefixlen,m) do{ \
256 const uint8_t prefixbytes[4] = { (b3),(b2),(b1),(b0) }; \
257 if (matches32(i4,get_uint32(prefixbytes),prefixlen)) \
258 DONT("IPv4 address is " m); \
259 }while(0)
260 DONTMASK(169,254,0,0, 16, "link local");
261 DONTMASK(224, 0,0,0, 4, "multicast");
262 DONTMASK(192, 0,0,0, 24, "in IETF protocol block (RFC6890)");
263 DONTMASK(240, 0,0,0, 4, "in reserved addressing block (RFC1112)");
264 if (!st->permit_loopback)
265 DONTMASK(127, 0,0,0, 8, "loopback");
266#undef DONTMASK
267 break;
268 }
269 default:
270 abort();
271 }
272
70ad8e2c
IJ
273#undef DONT
274
ce5c098f 275 /* OK, process it */
65d6d32e 276 callback(st, bad,badctx, add,want, ifname,ifaddr,&ia,-1);
70ad8e2c
IJ
277
278 out:;
279}
280
65d6d32e
IJ
281static void dump_pria(struct polypath *st, struct interf_list *interfs,
282 const char *ifname, char want)
70ad8e2c
IJ
283{
284#ifdef POLYPATH_DEBUG
285 struct interf *interf;
286 if (ifname)
65d6d32e
IJ
287 lg_perror(LG,M_DEBUG,0, "polypath record ifaddr `%s' (%c)",
288 ifname, want);
289 LIST_FOREACH(interf, interfs, entry) {
70ad8e2c
IJ
290 lg_perror(LG,M_DEBUG,0, " polypath interface `%s', nsocks=%d",
291 interf->name, interf->socks.n_socks);
292 int i;
293 for (i=0; i<interf->socks.n_socks; i++) {
294 struct udpsock *us=&interf->socks.socks[i];
295 lg_perror(LG,M_DEBUG,0, " polypath sock fd=%d addr=%s",
296 us->fd, iaddr_to_string(&us->addr));
297 }
298 }
299#endif
300}
301
302static bool_t polypath_make_socket(struct polypath *st,
303 bad_fn_type *bad, void *badctx,
304 struct udpsock *us, const char *ifname)
305 /* on error exit has called bad; might leave us->fd as -1 */
306{
307 assert(us->fd==-1);
308
309 bool_t ok=udp_make_socket(&st->uc,us,M_WARNING);
310 if (!ok) BAD("unable to set up socket");
311 int r=setsockopt(us->fd,SOL_SOCKET,SO_BINDTODEVICE,
312 ifname,strlen(ifname)+1);
313 if (r) BADE("setsockopt(,,SO_BINDTODEVICE,)",errno);
314 return True;
315
316 out:
317 return False;
318}
319
320static void polypath_record_ifaddr(struct polypath *st,
321 bad_fn_type *bad, void *badctx,
65d6d32e
IJ
322 bool_t add, char want,
323 const char *ifname,
70ad8e2c
IJ
324 const char *ifaddr,
325 const union iaddr *ia, int fd)
326{
327 struct udpcommon *uc=&st->uc;
328 struct interf *interf=0;
65d6d32e 329 int max_interfs;
70ad8e2c
IJ
330 struct udpsock *us=0;
331
65d6d32e
IJ
332 struct interf_list *interfs;
333 switch (want) {
334 case '+': interfs=&st->interfs; max_interfs=st->max_interfs;
335 default: fatal("polypath: got bad want (%#x, %s)", want, ifname);
336 }
337
338 dump_pria(st,interfs,ifname,want);
70ad8e2c 339
ce5c098f 340 int n_ifs=0;
65d6d32e 341 LIST_FOREACH(interf,interfs,entry) {
ce5c098f
IJ
342 if (!strcmp(interf->name,ifname))
343 goto found_interf;
344 n_ifs++;
345 }
346 /* not found */
65d6d32e 347 if (n_ifs==max_interfs) BAD("too many interfaces");
ce5c098f
IJ
348 interf=malloc(sizeof(*interf));
349 if (!interf) BADE("malloc for new interface",errno);
350 interf->name=0;
351 interf->socks.n_socks=0;
352 FILLZERO(interf->experienced_xmit_noaf);
65d6d32e 353 LIST_INSERT_HEAD(interfs,interf,entry);
ce5c098f 354 interf->name=strdup(ifname);
c72d679d 355 udp_socks_register(&st->uc,&interf->socks,interf->name);
ce5c098f
IJ
356 if (!interf->name) BADE("strdup interface name",errno);
357 found_interf:
358
359 if (add) {
360 if (interf->socks.n_socks == UDP_MAX_SOCKETS)
361 BAD("too many addresses on this interface");
362 struct udpsock *us=&interf->socks.socks[interf->socks.n_socks];
363 us->fd=-1;
70ad8e2c
IJ
364 COPY_OBJ(us->addr,*ia);
365 if (fd<0) {
366 bool_t ok=polypath_make_socket(st,bad,badctx, us,ifname);
367 if (!ok) goto out;
368 } else {
9c44ef13
IJ
369 bool_t ok=udp_import_socket(uc,us,M_WARNING,fd);
370 if (!ok) goto out;
70ad8e2c
IJ
371 fd=-1;
372 }
ce5c098f 373 interf->socks.n_socks++;
9c44ef13
IJ
374 lg_perror(LG,M_INFO,0,"using %s %s",ifname,
375 iaddr_to_string(&us->addr));
ce5c098f 376 us=0; /* do not destroy this socket during `out' */
ce5c098f
IJ
377 } else {
378 int i;
379 for (i=0; i<interf->socks.n_socks; i++)
9c44ef13 380 if (iaddr_equal(&interf->socks.socks[i].addr,ia,True))
ce5c098f 381 goto address_remove_found;
c69b984e
IJ
382 bad(st,badctx,M_DEBUG,"address to remove not found",0);
383 goto out;
ce5c098f 384 address_remove_found:
9c44ef13
IJ
385 lg_perror(LG,M_INFO,0,"removed %s %s",ifname,
386 iaddr_to_string(&interf->socks.socks[i].addr));
ce5c098f
IJ
387 udp_destroy_socket(&st->uc,&interf->socks.socks[i]);
388 interf->socks.socks[i]=
389 interf->socks.socks[--interf->socks.n_socks];
390 }
391
392 out:
393 if (us)
394 udp_destroy_socket(uc,us);
70ad8e2c
IJ
395 if (fd>=0)
396 close(fd);
ce5c098f
IJ
397 if (interf && !interf->socks.n_socks) {
398 udp_socks_deregister(&st->uc,&interf->socks);
399 LIST_REMOVE(interf,entry);
400 free(interf->name);
401 free(interf);
402 }
403
65d6d32e 404 dump_pria(st,interfs,0,0);
ce5c098f
IJ
405}
406
23ca1537
IJ
407static void subproc_problem(struct polypath *st,
408 enum async_linebuf_result alr, const char *emsg)
ce5c098f 409{
ce5c098f 410 int status;
ce5c098f
IJ
411 assert(st->monitor_pid);
412
413 pid_t gotpid=waitpid(st->monitor_pid,&status,WNOHANG);
414 if (gotpid==st->monitor_pid) {
415 st->monitor_pid=0;
416 lg_exitstatus(LG,M_FATAL,status,"interface monitor");
417 } else if (gotpid<0)
418 lg_perror(LG,M_ERR,errno,"unable to reap interface monitor");
419 else
420 assert(gotpid==0);
421
422 if (alr==async_linebuf_eof)
423 lg_perror(LG,M_FATAL,0,"unexpected EOF from interface monitor");
424 else
425 lg_perror(LG,M_FATAL,0,"bad output from interface monitor: %s",emsg);
ce5c098f
IJ
426 assert(!"not reached");
427}
428
93cdea57 429/* Used in non-privsep case, and in privsep child */
23ca1537
IJ
430static void afterpoll_monitor(struct polypath *st, struct pollfd *fd,
431 polypath_ppml_callback_type *callback)
432{
433 enum async_linebuf_result alr;
434 const char *emsg;
435
436 while ((alr=async_linebuf_read(fd,&st->lbuf,&emsg)) == async_linebuf_ok)
437 polypath_process_monitor_line(st,st->lbuf.base,callback);
438
439 if (alr==async_linebuf_nothing)
440 return;
441
442 subproc_problem(st,alr,emsg);
443}
444
93cdea57 445/* Used in non-privsep case only - glue for secnet main loop */
23ca1537
IJ
446static void polypath_afterpoll_monitor(void *state, struct pollfd *fds,
447 int nfds)
448{
449 struct polypath *st=state;
450 if (nfds<1) return;
451 afterpoll_monitor(st,fds,polypath_record_ifaddr);
452}
453
ce5c098f 454/* Actual udp packet sending work */
bfd718e6
IJ
455
456static void polypath_sendmsg_interf(struct polypath *st,
457 struct interf *interf,
458 struct buffer_if *buf,
459 const struct comm_addr *dest,
460 bool_t *allreasonable)
461{
462 int i;
463 int af=dest->ia.sa.sa_family;
464 bool_t attempted=False, reasonable=False;
465
466 for (i=0; i<interf->socks.n_socks; i++) {
467 struct udpsock *us=&interf->socks.socks[i];
468 if (af != us->addr.sa.sa_family)
469 continue;
470 attempted=True;
471 int r=sendto(us->fd,buf->start,buf->size,
472 0,&dest->ia.sa,iaddr_socklen(&dest->ia));
473 udp_sock_experienced(0,&st->uc,&interf->socks,us,
474 &dest->ia,af, r,errno);
475 if (r>=0) {
476 reasonable=True;
477 break;
478 }
479 if (!(errno==EAFNOSUPPORT || errno==ENETUNREACH))
480 reasonable=True;
481 lg_perror(LG,M_DEBUG,errno,"%s [%s] xmit %"PRIu32" bytes to %s",
482 interf->name,iaddr_to_string(&us->addr),
483 buf->size,iaddr_to_string(&dest->ia));
484 }
485 if (!attempted)
486 if (!interf->experienced_xmit_noaf[af]++)
487 lg_perror(LG,M_WARNING,0,
488 "%s has no suitable address to transmit %s",
489 interf->name, af_name(af));
490
491 *allreasonable *= reasonable;
492}
493
ce5c098f 494static bool_t polypath_sendmsg(void *commst, struct buffer_if *buf,
2d80199d
IJ
495 const struct comm_addr *dest,
496 struct comm_clientinfo *clientinfo)
ce5c098f
IJ
497{
498 struct polypath *st=commst;
499 struct interf *interf;
500 bool_t allreasonable=True;
ce5c098f
IJ
501
502 LIST_FOREACH(interf,&st->interfs,entry) {
bfd718e6
IJ
503 polypath_sendmsg_interf(st,interf,buf,dest,
504 &allreasonable);
ce5c098f
IJ
505 }
506 return allreasonable;
507}
508
93cdea57 509/* Non-privsep: called in (sole) child. Privsep: in grandchild. */
23ca1537
IJ
510static void child_monitor(struct polypath *st, int childfd)
511{
512 dup2(childfd,1);
513 execvp(st->monitor_command[0],(char**)st->monitor_command);
514 fprintf(stderr,"secnet: cannot execute %s: %s\n",
515 st->monitor_command[0], strerror(errno));
516 exit(-1);
517}
518
93cdea57 519/* General utility function. */
23ca1537 520static void start_subproc(struct polypath *st, void (*make_fdpair)(int[2]),
83e03cac
IJ
521 void (*child)(struct polypath *st, int childfd),
522 const char *desc)
ce5c098f 523{
ce5c098f
IJ
524 int pfds[2];
525
526 assert(!st->monitor_pid);
527 assert(st->monitor_fd<0);
528
23ca1537 529 make_fdpair(pfds);
ce5c098f
IJ
530
531 pid_t pid=fork();
532 if (!pid) {
533 afterfork();
94a1d5fc 534 close(pfds[0]);
23ca1537
IJ
535 child(st,pfds[1]);
536 abort();
ce5c098f
IJ
537 }
538 if (pid<0)
23ca1537 539 fatal_perror("%s: failed to fork for interface monitoring",
ce5c098f
IJ
540 st->uc.cc.cl.description);
541
542 close(pfds[1]);
543 st->monitor_pid=pid;
544 st->monitor_fd=pfds[0];
545 setnonblock(st->monitor_fd);
83e03cac
IJ
546
547 lg_perror(LG,M_NOTICE,0, "%s: spawning %s [pid %ld]",
548 st->uc.cc.cl.description, desc, (long)st->monitor_pid);
23ca1537 549}
ce5c098f 550
93cdea57 551/* Non-privsep only: glue for forking the monitor, from the main loop */
23ca1537
IJ
552static void polypath_phase_startmonitor(void *sst, uint32_t newphase)
553{
554 struct polypath *st=sst;
93cdea57
IJ
555 start_subproc(st,pipe_cloexec,child_monitor,
556 "interface monitor (no privsep)");
23ca1537
IJ
557 register_for_poll(st,polypath_beforepoll,
558 polypath_afterpoll_monitor,"polypath");
ce5c098f
IJ
559}
560
93cdea57
IJ
561/*----- Privsep-only: -----*/
562
563/*
564 * We use two subprocesses, a child and a grandchild. These are
565 * forked before secnet drops privilege.
566 *
567 * The grandchild is the same interface monitor helper script as used
568 * in the non-privsep case. But its lines are read by the child
569 * instead of by the main secnet. The child is responsible for
570 * creating the actual socket (binding it, etc.). Each socket is
571 * passed to secnet proper via fd passing, along with a data message
572 * describing the interface name and address. The child does not
573 * retain a list of current interfaces and addresses - it trusts the
574 * interface monitor to get that right. secnet proper still maintains
575 * that data structure.
576 *
577 * The result is that much of the non-privsep code can be reused, but
578 * just plumbed together differently.
579 *
580 * The child does not retain the socket after passing it on.
581 * Interface removals are handled similarly but without any fd.
582 *
583 * The result is that the configuration's limits on which interfaces
584 * and ports secnet may use are enforced by the privileged child.
585 */
586
587struct privsep_mdata {
588 bool_t add;
589 char ifname[100];
590 union iaddr ia;
65d6d32e 591 char want; /* `+', for now */
93cdea57
IJ
592};
593
84dcd42d
IJ
594static void papp_bad(struct polypath *st, void *badctx,
595 int mclass, const char *m, int ev)
93cdea57
IJ
596{
597 const struct privsep_mdata *mdata=(const void*)st->lbuf.start;
598 const char *addr_str=badctx;
599
84dcd42d 600 lg_perror(LG,mclass,ev,
93cdea57
IJ
601 "error processing polypath address change %s %s [%s]: %s",
602 mdata->add ? "+" : "-",
603 mdata->ifname, addr_str, m);
604}
605
606static void polypath_afterpoll_privsep(void *state, struct pollfd *fds,
607 int nfds)
608/* In secnet proper; receives messages from child. */
609{
610 struct polypath *st=state;
611
612 if (nfds<1) return;
613
614 int revents=fds[0].revents;
615
616 const char *badbit=pollbadbit(revents);
617 if (badbit) subproc_problem(st,async_linebuf_broken,badbit);
618
619 if (!(revents & POLLIN)) return;
620
621 for (;;) {
622 if (st->lbuf.size==sizeof(struct privsep_mdata)) {
623 const struct privsep_mdata *mdata=(const void*)st->lbuf.start;
624 if (mdata->add && st->privsep_incoming_fd<0)
625 fatal("polypath (privsep): got add message data but no fd");
626 if (!mdata->add && st->privsep_incoming_fd>=0)
627 fatal("polypath (privsep): got remove message data with fd");
628 if (!memchr(mdata->ifname,0,sizeof(mdata->ifname)))
629 fatal("polypath (privsep): got ifname with no terminating nul");
630 int af=mdata->ia.sa.sa_family;
631 if (!(af==AF_INET6 || af==AF_INET))
632 fatal("polypath (privsep): got message data but bad AF %d",af);
633 const char *addr_str=iaddr_to_string(&mdata->ia);
634 polypath_record_ifaddr(st,papp_bad,(void*)addr_str,
65d6d32e
IJ
635 mdata->add,mdata->want,
636 mdata->ifname,addr_str,
93cdea57
IJ
637 &mdata->ia, st->privsep_incoming_fd);
638 st->privsep_incoming_fd=-1;
639 st->lbuf.size=0;
640 }
641 struct msghdr msg;
642 int fd;
643 size_t cmsgdatalen=sizeof(fd);
644 char cmsg_control_buf[CMSG_SPACE(cmsgdatalen)];
645 struct iovec iov;
646
647 FILLZERO(msg);
648 msg.msg_iov=&iov;
649 msg.msg_iovlen=1;
650
651 iov.iov_base=st->lbuf.start+st->lbuf.size;
652 iov.iov_len=sizeof(struct privsep_mdata)-st->lbuf.size;
653
654 if (st->privsep_incoming_fd<0) {
655 msg.msg_control=cmsg_control_buf;
656 msg.msg_controllen=sizeof(cmsg_control_buf);
657 }
658
659 ssize_t got=recvmsg(st->monitor_fd,&msg,0);
660 if (got<0) {
661 if (errno==EINTR) continue;
662 if (iswouldblock(errno)) break;
663 fatal_perror("polypath (privsep): recvmsg failed");
664 }
665 if (got==0)
666 subproc_problem(st,async_linebuf_eof,0);
667
668 st->lbuf.size+=got;
669
670 if (msg.msg_controllen) {
671 size_t cmsgdatalen=sizeof(st->privsep_incoming_fd);
672 struct cmsghdr *h=CMSG_FIRSTHDR(&msg);
673 if (!(st->privsep_incoming_fd==-1 &&
674 h &&
675 h->cmsg_level==SOL_SOCKET &&
676 h->cmsg_type==SCM_RIGHTS &&
677 h->cmsg_len==CMSG_LEN(cmsgdatalen) &&
678 !CMSG_NXTHDR(&msg,h)))
679 subproc_problem(st,async_linebuf_broken,"bad cmsg");
680 memcpy(&st->privsep_incoming_fd,CMSG_DATA(h),cmsgdatalen);
681 assert(st->privsep_incoming_fd>=0);
682 }
683
684 }
685}
686
687static void privsep_handle_ifaddr(struct polypath *st,
688 bad_fn_type *bad, void *badctx,
65d6d32e
IJ
689 bool_t add, char want,
690 const char *ifname,
93cdea57
IJ
691 const char *ifaddr,
692 const union iaddr *ia, int fd_dummy)
693/* In child: handles discovered wanted interfaces, making sockets
694 and sending them to secnet proper. */
695{
696 struct msghdr msg;
697 struct iovec iov;
698 struct udpsock us={ .fd=-1 };
699 size_t cmsgdatalen=sizeof(us.fd);
700 char cmsg_control_buf[CMSG_SPACE(cmsgdatalen)];
701
702 assert(fd_dummy==-1);
703
704 struct privsep_mdata mdata;
705 FILLZERO(mdata);
706 mdata.add=add;
707
708 size_t l=strlen(ifname);
709 if (l>=sizeof(mdata.ifname)) BAD("interface name too long");
710 strcpy(mdata.ifname,ifname);
65d6d32e 711 mdata.want=want;
93cdea57
IJ
712
713 COPY_OBJ(mdata.ia,*ia);
714
715 iov.iov_base=&mdata;
716 iov.iov_len =sizeof(mdata);
717
718 FILLZERO(msg);
719 msg.msg_iov=&iov;
720 msg.msg_iovlen=1;
721
722 if (add) {
723 COPY_OBJ(us.addr,*ia);
724 bool_t ok=polypath_make_socket(st,bad,badctx,&us,ifname);
725 if (!ok) goto out;
726
727 msg.msg_control=cmsg_control_buf;
728 msg.msg_controllen=sizeof(cmsg_control_buf);
729
730 struct cmsghdr *h=CMSG_FIRSTHDR(&msg);
731 h->cmsg_level=SOL_SOCKET;
732 h->cmsg_type =SCM_RIGHTS;
733 h->cmsg_len =CMSG_LEN(cmsgdatalen);
734 memcpy(CMSG_DATA(h),&us.fd,cmsgdatalen);
735 }
736
737 while (iov.iov_len) {
738 ssize_t got=sendmsg(st->privsep_ipcsock_fd,&msg,0);
739 if (got<0) {
740 if (errno!=EINTR) fatal_perror("polypath privsep sendmsg");
741 got=0;
742 } else {
743 assert(got>0);
744 assert((size_t)got<=iov.iov_len);
745 }
746 iov.iov_base=(char*)iov.iov_base+got;
747 iov.iov_len-=got;
748 msg.msg_control=0;
749 msg.msg_controllen=0;
750 }
751
752 out:
753 if (us.fd>=0) close(us.fd);
754}
755
756static void child_privsep(struct polypath *st, int ipcsockfd)
757/* Privsep child main loop. */
758{
759 struct pollfd fds[2];
760
761 enter_phase(PHASE_CHILDPERSIST);
762
763 st->privsep_ipcsock_fd=ipcsockfd;
764 start_subproc(st,pipe_cloexec,child_monitor,
765 "interface monitor (grandchild)");
766 for (;;) {
767 int nfds=1;
768 int r=polypath_beforepoll(st,fds,&nfds,0);
769 assert(nfds==1);
770 assert(!r);
771
772 fds[1].fd=st->privsep_ipcsock_fd;
773 fds[1].events=POLLIN;
774
775 r=poll(fds,ARRAY_SIZE(fds),-1);
776
777 if (r<0) {
778 if (errno==EINTR) continue;
779 fatal_perror("polypath privsep poll");
780 }
781 if (fds[1].revents) {
782 if (fds[1].revents & (POLLHUP|POLLIN)) {
783 polypath_phase_shutdown(st,PHASE_SHUTDOWN);
784 exit(0);
785 }
786 fatal("polypath privsep poll parent socket revents=%#x",
787 fds[1].revents);
788 }
789 if (fds[0].revents & POLLNVAL)
790 fatal("polypath privsep poll child socket POLLNVAL");
791 afterpoll_monitor(st,fds,privsep_handle_ifaddr);
792 }
793}
794
795static void privsep_socketpair(int *fd)
796{
797 int r=socketpair(AF_UNIX,SOCK_STREAM,0,fd);
798 if (r) fatal_perror("socketpair(AF_UNIX,SOCK_STREAM,,)");
799 setcloexec(fd[0]);
800 setcloexec(fd[1]);
801}
802
803static void polypath_phase_startprivsep(void *sst, uint32_t newphase)
804{
805 struct polypath *st=sst;
806
807 if (!will_droppriv()) {
808 add_hook(PHASE_RUN, polypath_phase_startmonitor,st);
809 return;
810 }
811
812 start_subproc(st,privsep_socketpair,child_privsep,
813 "socket generator (privsep interface handler)");
814
815 BUF_FREE(&st->lbuf);
816 buffer_destroy(&st->lbuf);
817 buffer_new(&st->lbuf,sizeof(struct privsep_mdata));
818 BUF_ALLOC(&st->lbuf,"polypath mdata buf");
819 st->privsep_incoming_fd=-1;
820
821 register_for_poll(st,polypath_beforepoll,
822 polypath_afterpoll_privsep,"polypath");
823}
824
ce5c098f
IJ
825static void polypath_phase_shutdown(void *sst, uint32_t newphase)
826{
827 struct polypath *st=sst;
828 if (st->monitor_pid) {
829 assert(st->monitor_pid>0);
830 kill(st->monitor_pid,SIGTERM);
831 }
832}
833
32654a31
IJ
834static void polypath_phase_childpersist(void *sst, uint32_t newphase)
835{
836 struct polypath *st=sst;
837 struct interf *interf;
838
839 LIST_FOREACH(interf,&st->interfs,entry)
840 udp_socks_childpersist(&st->uc,&interf->socks);
841}
842
70ad8e2c
IJ
843#undef BAD
844#undef BADE
845
93cdea57
IJ
846/*----- generic closure and module setup -----*/
847
ce5c098f
IJ
848static list_t *polypath_apply(closure_t *self, struct cloc loc,
849 dict_t *context, list_t *args)
850{
851 struct polypath *st;
852
853 COMM_APPLY(st,&st->uc.cc,polypath_,"polypath",loc);
854 COMM_APPLY_STANDARD(st,&st->uc.cc,"polypath",args);
855 UDP_APPLY_STANDARD(st,&st->uc,"polypath");
856
857 struct udpcommon *uc=&st->uc;
858 struct commcommon *cc=&uc->cc;
859
860 st->max_interfs=dict_read_number(d,"max-interfaces",False,"polypath",loc,3);
861
862 st->ifname_pats=dict_read_string_array(d,"interfaces",False,"polypath",
863 cc->loc,0);
864 st->permit_loopback=0; /* ifname_wanted reads this */
865 ifname_wanted(st,st->uc.cc.loc," "); /* try to check each pattern */
866
867 st->monitor_command=dict_read_string_array(d,"monitor-command",False,
868 "polypath",cc->loc, default_monitor_command);
869 if (!st->monitor_command[0])
870 cfgfatal(loc,"polypath","no polypath interface monitor-command"
871 " (polypath unsupported on this platform?)\n");
872
873 st->permit_loopback=dict_read_bool(d,"permit-loopback",False,
874 "polypath",cc->loc,False);
875
876 LIST_INIT(&st->interfs);
877 buffer_new(&st->lbuf,ADNS_ADDR2TEXT_BUFLEN+100);
878 BUF_ALLOC(&st->lbuf,"polypath lbuf");
879
880 st->monitor_fd=-1;
881 st->monitor_pid=0;
882
93cdea57
IJ
883 add_hook(PHASE_GETRESOURCES, polypath_phase_startprivsep,st);
884
ce5c098f 885 add_hook(PHASE_SHUTDOWN, polypath_phase_shutdown, st);
32654a31 886 add_hook(PHASE_CHILDPERSIST,polypath_phase_childpersist,st);
ce5c098f
IJ
887
888 return new_closure(&cc->cl);
889}
890
891#endif /* CONFIG_IPV6 */
892
893void polypath_module(dict_t *dict)
894{
895#ifdef CONFIG_IPV6
896 add_closure(dict,"polypath",polypath_apply);
897#endif /* CONFIG_IPV6 */
898}