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