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