chiark / gitweb /
polypath: Do not separately log xmit failures
[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     }
508     if (!wanted)
509         return;
510
511     if (!attempted)
512         if (!interf->experienced_xmit_noaf[af]++)
513             lg_perror(LG,M_WARNING,0,
514                       "%s has no suitable address to transmit %s",
515                       interf->name, af_name(af));
516
517     *allreasonable &= reasonable;
518 }
519
520 static bool_t polypath_sendmsg(void *commst, struct buffer_if *buf,
521                           const struct comm_addr *dest,
522                           struct comm_clientinfo *clientinfo)
523 {
524     struct polypath *st=commst;
525     struct interf *interf;
526     bool_t allreasonable=True;
527
528     LIST_FOREACH(interf,&st->interfs_general,entry) {
529         polypath_sendmsg_interf(st,interf,buf,dest,
530                                 0, &allreasonable);
531     }
532     if (clientinfo && clientinfo->dedicated.sa.sa_family != AF_UNSPEC) {
533         LIST_FOREACH(interf,&st->interfs_dedicated,entry) {
534             polypath_sendmsg_interf(st,interf,buf,dest,
535                                     &clientinfo->dedicated, &allreasonable);
536         }
537     }
538     return allreasonable;
539 }
540
541 /* Non-privsep: called in (sole) child.  Privsep: in grandchild. */
542 static void child_monitor(struct polypath *st, int childfd)
543 {
544     dup2(childfd,1);
545     execvp(st->monitor_command[0],(char**)st->monitor_command);
546     fprintf(stderr,"secnet: cannot execute %s: %s\n",
547             st->monitor_command[0], strerror(errno));
548     exit(-1);
549 }
550
551 /* General utility function. */
552 static void start_subproc(struct polypath *st, void (*make_fdpair)(int[2]),
553                           void (*child)(struct polypath *st, int childfd),
554                           const char *desc)
555 {
556     int pfds[2];
557
558     assert(!st->monitor_pid);
559     assert(st->monitor_fd<0);
560
561     make_fdpair(pfds);
562
563     pid_t pid=fork();
564     if (!pid) {
565         afterfork();
566         close(pfds[0]);
567         child(st,pfds[1]);
568         abort();
569     }
570     if (pid<0)
571         fatal_perror("%s: failed to fork for interface monitoring",
572                      st->uc.cc.cl.description);
573
574     close(pfds[1]);
575     st->monitor_pid=pid;
576     st->monitor_fd=pfds[0];
577     setnonblock(st->monitor_fd);
578
579     lg_perror(LG,M_NOTICE,0, "%s: spawning %s [pid %ld]",
580               st->uc.cc.cl.description, desc, (long)st->monitor_pid);
581 }
582
583 /* Non-privsep only: glue for forking the monitor, from the main loop */
584 static void polypath_phase_startmonitor(void *sst, uint32_t newphase)
585 {
586     struct polypath *st=sst;
587     start_subproc(st,pipe_cloexec,child_monitor,
588                   "interface monitor (no privsep)");
589     register_for_poll(st,polypath_beforepoll,
590                       polypath_afterpoll_monitor,"polypath");
591 }
592
593 /*----- Privsep-only: -----*/
594
595 /*
596  * We use two subprocesses, a child and a grandchild.  These are
597  * forked before secnet drops privilege.
598  *
599  * The grandchild is the same interface monitor helper script as used
600  * in the non-privsep case.  But its lines are read by the child
601  * instead of by the main secnet.  The child is responsible for
602  * creating the actual socket (binding it, etc.).  Each socket is
603  * passed to secnet proper via fd passing, along with a data message
604  * describing the interface name and address.  The child does not
605  * retain a list of current interfaces and addresses - it trusts the
606  * interface monitor to get that right.  secnet proper still maintains
607  * that data structure.
608  *
609  * The result is that much of the non-privsep code can be reused, but
610  * just plumbed together differently.
611  *
612  * The child does not retain the socket after passing it on.
613  * Interface removals are handled similarly but without any fd.
614  *
615  * The result is that the configuration's limits on which interfaces
616  * and ports secnet may use are enforced by the privileged child.
617  */
618
619 struct privsep_mdata {
620     bool_t add;
621     char ifname[100];
622     union iaddr ia;
623     char want; /* `+' or `@' */
624 };
625
626 static void papp_bad(struct polypath *st, void *badctx,
627                      int mclass, const char *m, int ev)
628 {
629     const struct privsep_mdata *mdata=(const void*)st->lbuf.start;
630     const char *addr_str=badctx;
631
632     lg_perror(LG,mclass,ev,
633               "error processing polypath address change %s %s [%s]: %s",
634               mdata->add ? "+" : "-",
635               mdata->ifname, addr_str, m);
636 }
637
638 static void polypath_afterpoll_privsep(void *state, struct pollfd *fds,
639                                        int nfds)
640 /* In secnet proper; receives messages from child. */
641 {
642     struct polypath *st=state;
643
644     if (nfds<1) return;
645
646     int revents=fds[0].revents;
647
648     const char *badbit=pollbadbit(revents);
649     if (badbit) subproc_problem(st,async_linebuf_broken,badbit);
650
651     if (!(revents & POLLIN)) return;
652
653     for (;;) {
654         if (st->lbuf.size==sizeof(struct privsep_mdata)) {
655             const struct privsep_mdata *mdata=(const void*)st->lbuf.start;
656             if (mdata->add && st->privsep_incoming_fd<0)
657                 fatal("polypath (privsep): got add message data but no fd");
658             if (!mdata->add && st->privsep_incoming_fd>=0)
659                 fatal("polypath (privsep): got remove message data with fd");
660             if (!memchr(mdata->ifname,0,sizeof(mdata->ifname)))
661                 fatal("polypath (privsep): got ifname with no terminating nul");
662             int af=mdata->ia.sa.sa_family;
663             if (!(af==AF_INET6 || af==AF_INET))
664                 fatal("polypath (privsep): got message data but bad AF %d",af);
665             const char *addr_str=iaddr_to_string(&mdata->ia);
666             polypath_record_ifaddr(st,papp_bad,(void*)addr_str,
667                                    mdata->add,mdata->want,
668                                    mdata->ifname,addr_str,
669                                    &mdata->ia, st->privsep_incoming_fd);
670             st->privsep_incoming_fd=-1;
671             st->lbuf.size=0;
672         }
673         struct msghdr msg;
674         int fd;
675         size_t cmsgdatalen=sizeof(fd);
676         char cmsg_control_buf[CMSG_SPACE(cmsgdatalen)];
677         struct iovec iov;
678
679         FILLZERO(msg);
680         msg.msg_iov=&iov;
681         msg.msg_iovlen=1;
682
683         iov.iov_base=st->lbuf.start+st->lbuf.size;
684         iov.iov_len=sizeof(struct privsep_mdata)-st->lbuf.size;
685
686         if (st->privsep_incoming_fd<0) {
687             msg.msg_control=cmsg_control_buf;
688             msg.msg_controllen=sizeof(cmsg_control_buf);
689         }
690
691         ssize_t got=recvmsg(st->monitor_fd,&msg,0);
692         if (got<0) {
693             if (errno==EINTR) continue;
694             if (iswouldblock(errno)) break;
695             fatal_perror("polypath (privsep): recvmsg failed");
696         }
697         if (got==0)
698             subproc_problem(st,async_linebuf_eof,0);
699
700         st->lbuf.size+=got;
701
702         if (msg.msg_controllen) {
703             size_t cmsgdatalen=sizeof(st->privsep_incoming_fd);
704             struct cmsghdr *h=CMSG_FIRSTHDR(&msg);
705             if (!(st->privsep_incoming_fd==-1 &&
706                   h &&
707                   h->cmsg_level==SOL_SOCKET &&
708                   h->cmsg_type==SCM_RIGHTS &&
709                   h->cmsg_len==CMSG_LEN(cmsgdatalen) &&
710                   !CMSG_NXTHDR(&msg,h)))
711                 subproc_problem(st,async_linebuf_broken,"bad cmsg");
712             memcpy(&st->privsep_incoming_fd,CMSG_DATA(h),cmsgdatalen);
713             assert(st->privsep_incoming_fd>=0);
714         }
715
716     }
717 }
718
719 static void privsep_handle_ifaddr(struct polypath *st,
720                                    bad_fn_type *bad, void *badctx,
721                                    bool_t add, char want,
722                                    const char *ifname,
723                                    const char *ifaddr,
724                                    const union iaddr *ia, int fd_dummy)
725 /* In child: handles discovered wanted interfaces, making sockets
726    and sending them to secnet proper. */
727 {
728     struct msghdr msg;
729     struct iovec iov;
730     struct udpsock us={ .fd=-1 };
731     size_t cmsgdatalen=sizeof(us.fd);
732     char cmsg_control_buf[CMSG_SPACE(cmsgdatalen)];
733
734     assert(fd_dummy==-1);
735
736     struct privsep_mdata mdata;
737     FILLZERO(mdata);
738     mdata.add=add;
739
740     size_t l=strlen(ifname);
741     if (l>=sizeof(mdata.ifname)) BAD("interface name too long");
742     strcpy(mdata.ifname,ifname);
743     mdata.want=want;
744
745     COPY_OBJ(mdata.ia,*ia);
746
747     iov.iov_base=&mdata;
748     iov.iov_len =sizeof(mdata);
749
750     FILLZERO(msg);
751     msg.msg_iov=&iov;
752     msg.msg_iovlen=1;
753
754     if (add) {
755         COPY_OBJ(us.addr,*ia);
756         bool_t ok=polypath_make_socket(st,bad,badctx,&us,ifname);
757         if (!ok) goto out;
758
759         msg.msg_control=cmsg_control_buf;
760         msg.msg_controllen=sizeof(cmsg_control_buf);
761
762         struct cmsghdr *h=CMSG_FIRSTHDR(&msg);
763         h->cmsg_level=SOL_SOCKET;
764         h->cmsg_type =SCM_RIGHTS;
765         h->cmsg_len  =CMSG_LEN(cmsgdatalen);
766         memcpy(CMSG_DATA(h),&us.fd,cmsgdatalen);
767     }
768
769     while (iov.iov_len) {
770         ssize_t got=sendmsg(st->privsep_ipcsock_fd,&msg,0);
771         if (got<0) {
772             if (errno!=EINTR) fatal_perror("polypath privsep sendmsg");
773             got=0;
774         } else {
775             assert(got>0);
776             assert((size_t)got<=iov.iov_len);
777         }
778         iov.iov_base=(char*)iov.iov_base+got;
779         iov.iov_len-=got;
780         msg.msg_control=0;
781         msg.msg_controllen=0;
782     }
783
784  out:
785     if (us.fd>=0) close(us.fd);
786 }
787
788 static void child_privsep(struct polypath *st, int ipcsockfd)
789 /* Privsep child main loop. */
790 {
791     struct pollfd fds[2];
792
793     enter_phase(PHASE_CHILDPERSIST);
794
795     st->privsep_ipcsock_fd=ipcsockfd;
796     start_subproc(st,pipe_cloexec,child_monitor,
797                   "interface monitor (grandchild)");
798     for (;;) {
799         int nfds=1;
800         int r=polypath_beforepoll(st,fds,&nfds,0);
801         assert(nfds==1);
802         assert(!r);
803
804         fds[1].fd=st->privsep_ipcsock_fd;
805         fds[1].events=POLLIN;
806
807         r=poll(fds,ARRAY_SIZE(fds),-1);
808
809         if (r<0) {
810             if (errno==EINTR) continue;
811             fatal_perror("polypath privsep poll");
812         }
813         if (fds[1].revents) {
814             if (fds[1].revents & (POLLHUP|POLLIN)) {
815                 polypath_phase_shutdown(st,PHASE_SHUTDOWN);
816                 exit(0);
817             }
818             fatal("polypath privsep poll parent socket revents=%#x",
819                   fds[1].revents);
820         }
821         if (fds[0].revents & POLLNVAL)
822             fatal("polypath privsep poll child socket POLLNVAL");
823         afterpoll_monitor(st,fds,privsep_handle_ifaddr);
824     }
825 }
826
827 static void privsep_socketpair(int *fd)
828 {
829     int r=socketpair(AF_UNIX,SOCK_STREAM,0,fd);
830     if (r) fatal_perror("socketpair(AF_UNIX,SOCK_STREAM,,)");
831     setcloexec(fd[0]);
832     setcloexec(fd[1]);
833 }
834
835 static void polypath_phase_startprivsep(void *sst, uint32_t newphase)
836 {
837     struct polypath *st=sst;
838
839     if (!will_droppriv()) {
840         add_hook(PHASE_RUN,          polypath_phase_startmonitor,st);
841         return;
842     }
843
844     start_subproc(st,privsep_socketpair,child_privsep,
845                   "socket generator (privsep interface handler)");
846
847     BUF_FREE(&st->lbuf);
848     buffer_destroy(&st->lbuf);
849     buffer_new(&st->lbuf,sizeof(struct privsep_mdata));
850     BUF_ALLOC(&st->lbuf,"polypath mdata buf");
851     st->privsep_incoming_fd=-1;
852
853     register_for_poll(st,polypath_beforepoll,
854                       polypath_afterpoll_privsep,"polypath");
855 }
856
857 static void polypath_phase_shutdown(void *sst, uint32_t newphase)
858 {
859     struct polypath *st=sst;
860     if (st->monitor_pid) {
861         assert(st->monitor_pid>0);
862         kill(st->monitor_pid,SIGTERM);
863     }
864 }
865
866 static void polypath_phase_childpersist(void *sst, uint32_t newphase)
867 {
868     struct polypath *st=sst;
869     struct interf *interf;
870
871     LIST_FOREACH(interf,&st->interfs_general,entry)
872         udp_socks_childpersist(&st->uc,&interf->socks);
873     LIST_FOREACH(interf,&st->interfs_dedicated,entry)
874         udp_socks_childpersist(&st->uc,&interf->socks);
875 }
876
877 #undef BAD
878 #undef BADE
879
880 /*----- generic closure and module setup -----*/
881
882 static list_t *polypath_apply(closure_t *self, struct cloc loc,
883                               dict_t *context, list_t *args)
884 {
885     struct polypath *st;
886
887     COMM_APPLY(st,&st->uc.cc,polypath_,"polypath",loc);
888     COMM_APPLY_STANDARD(st,&st->uc.cc,"polypath",args);
889     UDP_APPLY_STANDARD(st,&st->uc,"polypath");
890
891     st->uc.cc.ops.clientinfo = polypath_clientinfo;
892
893     struct udpcommon *uc=&st->uc;
894     struct commcommon *cc=&uc->cc;
895
896     st->max_interfs=dict_read_number(d,"max-interfaces",False,"polypath",loc,3);
897
898     st->ifname_pats=dict_read_string_array(d,"interfaces",False,"polypath",
899                                            cc->loc,0);
900     st->permit_loopback=0; /* ifname_wanted reads this */
901     ifname_wanted(st,st->uc.cc.loc," "); /* try to check each pattern */
902
903     st->monitor_command=dict_read_string_array(d,"monitor-command",False,
904                                "polypath",cc->loc, default_monitor_command);
905     if (!st->monitor_command[0])
906         cfgfatal(loc,"polypath","no polypath interface monitor-command"
907                  " (polypath unsupported on this platform?)\n");
908
909     st->permit_loopback=dict_read_bool(d,"permit-loopback",False,
910                                        "polypath",cc->loc,False);
911
912     LIST_INIT(&st->interfs_general);
913     LIST_INIT(&st->interfs_dedicated);
914     buffer_new(&st->lbuf,ADNS_ADDR2TEXT_BUFLEN+100);
915     BUF_ALLOC(&st->lbuf,"polypath lbuf");
916
917     st->monitor_fd=-1;
918     st->monitor_pid=0;
919
920     add_hook(PHASE_GETRESOURCES, polypath_phase_startprivsep,st);
921
922     add_hook(PHASE_SHUTDOWN,    polypath_phase_shutdown,    st);
923     add_hook(PHASE_CHILDPERSIST,polypath_phase_childpersist,st);
924
925     return new_closure(&cc->cl);
926 }
927
928 #endif /* CONFIG_IPV6 */
929
930 void polypath_module(dict_t *dict)
931 {
932 #ifdef CONFIG_IPV6
933     add_closure(dict,"polypath",polypath_apply);
934 #endif /* CONFIG_IPV6 */
935 }