chiark / gitweb /
polypath: Provide privsep mode
[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     "!userv*","!sl*","!tap*","!tun*", "*", 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     badctx->undospace=space;
187     *space++=0;
188     const char *ifaddr=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,x) \
212         if (IN6_IS_ADDR_##X(i6)) DONT("IPv6 address is " #x)
213         DONTKIND(UNSPECIFIED,unspecified);
214         DONTKIND(MULTICAST  ,multicast  );
215         DONTKIND(LINKLOCAL  ,linklocal  );
216         DONTKIND(SITELOCAL  ,sitelocal  );
217         DONTKIND(V4MAPPED   ,v4mapped   );
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 #undef DONTMASK
229         break;
230     }
231     case AF_INET: {
232         const uint32_t i4=htonl(ia.sin.sin_addr.s_addr);
233         if (i4==INADDR_ANY) DONT("IPv4 address is any/unspecified");
234         if (i4==INADDR_BROADCAST) DONT("IPv4 address is all hosts broadcast");
235 #define DONTMASK(b3,b2,b1,b0,prefixlen,m) do{                           \
236             const uint8_t prefixbytes[4] = { (b3),(b2),(b1),(b0) };     \
237             if (matches32(i4,get_uint32(prefixbytes),prefixlen))        \
238                 DONT("IPv4 address is " m);                             \
239         }while(0)
240         DONTMASK(169,254,0,0, 16, "link local");
241         DONTMASK(224,  0,0,0,  4, "multicast");
242         DONTMASK(192,  0,0,0, 24, "in IETF protocol block (RFC6890)");
243         DONTMASK(240,  0,0,0,  4, "in reserved addressing block (RFC1112)");
244         if (!st->permit_loopback)
245             DONTMASK(127,  0,0,0,  8, "loopback");
246 #undef DONTMASK
247         break;
248     }
249     default:
250         abort();
251     }
252
253 #undef DONT
254
255     /* OK, process it */
256     callback(st, bad,badctx, add,ifname,ifaddr,&ia,-1);
257
258  out:;
259 }
260
261 static void dump_pria(struct polypath *st, const char *ifname)
262 {
263 #if 0
264     struct interf *interf;
265     if (orgl)
266         lg_perror(LG,M_DEBUG,0, "polypath record ifaddr `%s'",ifname);
267     LIST_FOREACH(interf, &st->interfs, entry) {
268         lg_perror(LG,M_DEBUG,0, "  polypath interface `%s', nsocks=%d",
269                   interf->name, interf->socks.n_socks);
270         int i;
271         for (i=0; i<interf->socks.n_socks; i++) {
272             struct udpsock *us=&interf->socks.socks[i];
273             lg_perror(LG,M_DEBUG,0, "    polypath sock fd=%d addr=%s",
274                       us->fd, iaddr_to_string(&us->addr));
275         }
276     }
277 #endif
278 }
279
280 static bool_t polypath_make_socket(struct polypath *st,
281                                    bad_fn_type *bad, void *badctx,
282                                    struct udpsock *us, const char *ifname)
283     /* on error exit has called bad; might leave us->fd as -1 */
284 {
285     assert(us->fd==-1);
286
287     bool_t ok=udp_make_socket(&st->uc,us,M_WARNING);
288     if (!ok) BAD("unable to set up socket");
289     int r=setsockopt(us->fd,SOL_SOCKET,SO_BINDTODEVICE,
290                      ifname,strlen(ifname)+1);
291     if (r) BADE("setsockopt(,,SO_BINDTODEVICE,)",errno);
292     return True;
293
294  out:
295     return False;
296 }
297
298 static void polypath_record_ifaddr(struct polypath *st,
299                                    bad_fn_type *bad, void *badctx,
300                                    bool_t add, const char *ifname,
301                                    const char *ifaddr,
302                                    const union iaddr *ia, int fd)
303 {
304     struct udpcommon *uc=&st->uc;
305     struct interf *interf=0;
306     struct udpsock *us=0;
307
308     dump_pria(st,ifname);
309
310     int n_ifs=0;
311     LIST_FOREACH(interf,&st->interfs,entry) {
312         if (!strcmp(interf->name,ifname))
313             goto found_interf;
314         n_ifs++;
315     }
316     /* not found */
317     if (n_ifs==st->max_interfs) BAD("too many interfaces");
318     interf=malloc(sizeof(*interf));
319     if (!interf) BADE("malloc for new interface",errno);
320     interf->name=0;
321     interf->socks.n_socks=0;
322     FILLZERO(interf->experienced_xmit_noaf);
323     LIST_INSERT_HEAD(&st->interfs,interf,entry);
324     udp_socks_register(&st->uc,&interf->socks);
325     interf->name=strdup(ifname);
326     if (!interf->name) BADE("strdup interface name",errno);
327  found_interf:
328
329     if (add) {
330         if (interf->socks.n_socks == UDP_MAX_SOCKETS)
331             BAD("too many addresses on this interface");
332         struct udpsock *us=&interf->socks.socks[interf->socks.n_socks];
333         us->fd=-1;
334         COPY_OBJ(us->addr,*ia);
335         if (fd<0) {
336             bool_t ok=polypath_make_socket(st,bad,badctx, us,ifname);
337             if (!ok) goto out;
338         } else {
339             FILLZERO(us->experienced);
340             us->fd=fd;
341             fd=-1;
342         }
343         interf->socks.n_socks++;
344         us=0; /* do not destroy this socket during `out' */
345         lg_perror(LG,M_INFO,0,"using %s %s",ifname,ifaddr);
346     } else {
347         int i;
348         for (i=0;i<interf->socks.n_socks;i++)
349             if (!memcmp(&interf->socks.socks[i].addr,ia,sizeof(*ia)))
350                 goto address_remove_found;
351         BAD("address to remove not found");
352     address_remove_found:
353         lg_perror(LG,M_INFO,0,"removed %s %s",ifname,ifaddr);
354         udp_destroy_socket(&st->uc,&interf->socks.socks[i]);
355         interf->socks.socks[i]=
356             interf->socks.socks[--interf->socks.n_socks];
357     }
358
359  out:
360     if (us)
361         udp_destroy_socket(uc,us);
362     if (fd>=0)
363         close(fd);
364     if (interf && !interf->socks.n_socks) {
365         udp_socks_deregister(&st->uc,&interf->socks);
366         LIST_REMOVE(interf,entry);
367         free(interf->name);
368         free(interf);
369     }
370
371     dump_pria(st,0);
372 }
373
374 static void subproc_problem(struct polypath *st,
375                             enum async_linebuf_result alr, const char *emsg)
376 {
377     int status;
378     assert(st->monitor_pid);
379
380     pid_t gotpid=waitpid(st->monitor_pid,&status,WNOHANG);
381     if (gotpid==st->monitor_pid) {
382         st->monitor_pid=0;
383         lg_exitstatus(LG,M_FATAL,status,"interface monitor");
384     } else if (gotpid<0)
385         lg_perror(LG,M_ERR,errno,"unable to reap interface monitor");
386     else
387         assert(gotpid==0);
388
389     if (alr==async_linebuf_eof)
390         lg_perror(LG,M_FATAL,0,"unexpected EOF from interface monitor");
391     else
392         lg_perror(LG,M_FATAL,0,"bad output from interface monitor: %s",emsg);
393     assert(!"not reached");
394 }
395
396 /* Used in non-privsep case, and in privsep child */
397 static void afterpoll_monitor(struct polypath *st, struct pollfd *fd,
398                               polypath_ppml_callback_type *callback)
399 {
400     enum async_linebuf_result alr;
401     const char *emsg;
402     
403     while ((alr=async_linebuf_read(fd,&st->lbuf,&emsg)) == async_linebuf_ok)
404         polypath_process_monitor_line(st,st->lbuf.base,callback);
405
406     if (alr==async_linebuf_nothing)
407         return;
408
409     subproc_problem(st,alr,emsg);
410 }
411
412 /* Used in non-privsep case only - glue for secnet main loop */
413 static void polypath_afterpoll_monitor(void *state, struct pollfd *fds,
414                                        int nfds)
415 {
416     struct polypath *st=state;
417     if (nfds<1) return;
418     afterpoll_monitor(st,fds,polypath_record_ifaddr);
419 }
420
421 /* Actual udp packet sending work */
422 static bool_t polypath_sendmsg(void *commst, struct buffer_if *buf,
423                           const struct comm_addr *dest)
424 {
425     struct polypath *st=commst;
426     struct interf *interf;
427     bool_t allreasonable=True;
428     int af=dest->ia.sa.sa_family;
429
430     LIST_FOREACH(interf,&st->interfs,entry) {
431         int i;
432         bool_t attempted=False, reasonable=False;
433         for (i=0; i<interf->socks.n_socks; i++) {
434             struct udpsock *us=&interf->socks.socks[i];
435             if (af != us->addr.sa.sa_family)
436                 continue;
437             attempted=True;
438             int r=sendto(us->fd,buf->start,buf->size,
439                          0,&dest->ia.sa,iaddr_socklen(&dest->ia));
440             udp_sock_experienced(0,&st->uc, interf->name,us,
441                                  1,af, r,errno);
442             if (r>=0) {
443                 reasonable=True;
444                 break;
445             }
446             if (!(errno==EAFNOSUPPORT || errno==ENETUNREACH))
447                 reasonable=True;
448             lg_perror(LG,M_DEBUG,errno,"xmit %"PRIu32" bytes to %s",
449                       buf->size,iaddr_to_string(&dest->ia));
450         }
451         if (!attempted)
452             if (!interf->experienced_xmit_noaf[af]++)
453                 lg_perror(LG, M_WARNING,0,
454                           "%s has no suitable address to transmit %s",
455                           interf->name, af_name(af));
456         allreasonable &= reasonable;
457     }
458     return allreasonable;
459 }
460
461 /* Non-privsep: called in (sole) child.  Privsep: in grandchild. */
462 static void child_monitor(struct polypath *st, int childfd)
463 {
464     dup2(childfd,1);
465     execvp(st->monitor_command[0],(char**)st->monitor_command);
466     fprintf(stderr,"secnet: cannot execute %s: %s\n",
467             st->monitor_command[0], strerror(errno));
468     exit(-1);
469 }
470
471 /* General utility function. */
472 static void start_subproc(struct polypath *st, void (*make_fdpair)(int[2]),
473                           void (*child)(struct polypath *st, int childfd),
474                           const char *desc)
475 {
476     int pfds[2];
477
478     assert(!st->monitor_pid);
479     assert(st->monitor_fd<0);
480
481     make_fdpair(pfds);
482
483     pid_t pid=fork();
484     if (!pid) {
485         afterfork();
486         close(pfds[0]);
487         child(st,pfds[1]);
488         abort();
489     }
490     if (pid<0)
491         fatal_perror("%s: failed to fork for interface monitoring",
492                      st->uc.cc.cl.description);
493
494     close(pfds[1]);
495     st->monitor_pid=pid;
496     st->monitor_fd=pfds[0];
497     setnonblock(st->monitor_fd);
498
499     lg_perror(LG,M_NOTICE,0, "%s: spawning %s [pid %ld]",
500               st->uc.cc.cl.description, desc, (long)st->monitor_pid);
501 }
502
503 /* Non-privsep only: glue for forking the monitor, from the main loop */
504 static void polypath_phase_startmonitor(void *sst, uint32_t newphase)
505 {
506     struct polypath *st=sst;
507     start_subproc(st,pipe_cloexec,child_monitor,
508                   "interface monitor (no privsep)");
509     register_for_poll(st,polypath_beforepoll,
510                       polypath_afterpoll_monitor,"polypath");
511 }
512
513 /*----- Privsep-only: -----*/
514
515 /*
516  * We use two subprocesses, a child and a grandchild.  These are
517  * forked before secnet drops privilege.
518  *
519  * The grandchild is the same interface monitor helper script as used
520  * in the non-privsep case.  But its lines are read by the child
521  * instead of by the main secnet.  The child is responsible for
522  * creating the actual socket (binding it, etc.).  Each socket is
523  * passed to secnet proper via fd passing, along with a data message
524  * describing the interface name and address.  The child does not
525  * retain a list of current interfaces and addresses - it trusts the
526  * interface monitor to get that right.  secnet proper still maintains
527  * that data structure.
528  *
529  * The result is that much of the non-privsep code can be reused, but
530  * just plumbed together differently.
531  *
532  * The child does not retain the socket after passingn it on.
533  * Interface removals are handled similarly but without any fd.
534  *
535  * The result is that the configuration's limits on which interfaces
536  * and ports secnet may use are enforced by the privileged child.
537  */
538
539 struct privsep_mdata {
540     bool_t add;
541     char ifname[100];
542     union iaddr ia;
543 };
544
545 static void papp_bad(struct polypath *st, void *badctx, const char *m, int ev)
546 {
547     const struct privsep_mdata *mdata=(const void*)st->lbuf.start;
548     const char *addr_str=badctx;
549
550     lg_perror(LG,M_WARNING,ev,
551               "error processing polypath address change %s %s [%s]: %s",
552               mdata->add ? "+" : "-",
553               mdata->ifname, addr_str, m);
554 }
555
556 static void polypath_afterpoll_privsep(void *state, struct pollfd *fds,
557                                        int nfds)
558 /* In secnet proper; receives messages from child. */
559 {
560     struct polypath *st=state;
561
562     if (nfds<1) return;
563
564     int revents=fds[0].revents;
565
566     const char *badbit=pollbadbit(revents);
567     if (badbit) subproc_problem(st,async_linebuf_broken,badbit);
568
569     if (!(revents & POLLIN)) return;
570
571     for (;;) {
572         if (st->lbuf.size==sizeof(struct privsep_mdata)) {
573             const struct privsep_mdata *mdata=(const void*)st->lbuf.start;
574             if (mdata->add && st->privsep_incoming_fd<0)
575                 fatal("polypath (privsep): got add message data but no fd");
576             if (!mdata->add && st->privsep_incoming_fd>=0)
577                 fatal("polypath (privsep): got remove message data with fd");
578             if (!memchr(mdata->ifname,0,sizeof(mdata->ifname)))
579                 fatal("polypath (privsep): got message data but no newline");
580             int af=mdata->ia.sa.sa_family;
581             if (!(af==AF_INET6 || af==AF_INET))
582                 fatal("polypath (privsep): got message data but bad AF %d",af);
583             const char *addr_str=iaddr_to_string(&mdata->ia);
584             polypath_record_ifaddr(st,papp_bad,(void*)addr_str,
585                                    mdata->add,mdata->ifname,addr_str,
586                                    &mdata->ia, st->privsep_incoming_fd);
587             st->privsep_incoming_fd=-1;
588             st->lbuf.size=0;
589         }
590         struct msghdr msg;
591         int fd;
592         size_t cmsgdatalen=sizeof(fd);
593         char cmsg_control_buf[CMSG_SPACE(cmsgdatalen)];
594         struct iovec iov;
595
596         FILLZERO(msg);
597         msg.msg_iov=&iov;
598         msg.msg_iovlen=1;
599
600         iov.iov_base=st->lbuf.start+st->lbuf.size;
601         iov.iov_len=sizeof(struct privsep_mdata)-st->lbuf.size;
602
603         if (st->privsep_incoming_fd<0) {
604             msg.msg_control=cmsg_control_buf;
605             msg.msg_controllen=sizeof(cmsg_control_buf);
606         }
607
608         ssize_t got=recvmsg(st->monitor_fd,&msg,0);
609         if (got<0) {
610             if (errno==EINTR) continue;
611             if (iswouldblock(errno)) break;
612             fatal_perror("polypath (privsep): recvmsg failed");
613         }
614         if (got==0)
615             subproc_problem(st,async_linebuf_eof,0);
616
617         st->lbuf.size+=got;
618
619         if (msg.msg_controllen) {
620             size_t cmsgdatalen=sizeof(st->privsep_incoming_fd);
621             struct cmsghdr *h=CMSG_FIRSTHDR(&msg);
622             if (!(st->privsep_incoming_fd==-1 &&
623                   h &&
624                   h->cmsg_level==SOL_SOCKET &&
625                   h->cmsg_type==SCM_RIGHTS &&
626                   h->cmsg_len==CMSG_LEN(cmsgdatalen) &&
627                   !CMSG_NXTHDR(&msg,h)))
628                 subproc_problem(st,async_linebuf_broken,"bad cmsg");
629             memcpy(&st->privsep_incoming_fd,CMSG_DATA(h),cmsgdatalen);
630             assert(st->privsep_incoming_fd>=0);
631         }
632
633     }
634 }
635
636 static void privsep_handle_ifaddr(struct polypath *st,
637                                    bad_fn_type *bad, void *badctx,
638                                    bool_t add, const char *ifname,
639                                    const char *ifaddr,
640                                    const union iaddr *ia, int fd_dummy)
641 /* In child: handles discovered wanted interfaces, making sockets
642    and sending them to secnet proper. */
643 {
644     struct msghdr msg;
645     struct iovec iov;
646     struct udpsock us={ .fd=-1 };
647     size_t cmsgdatalen=sizeof(us.fd);
648     char cmsg_control_buf[CMSG_SPACE(cmsgdatalen)];
649
650     assert(fd_dummy==-1);
651
652     struct privsep_mdata mdata;
653     FILLZERO(mdata);
654     mdata.add=add;
655
656     size_t l=strlen(ifname);
657     if (l>=sizeof(mdata.ifname)) BAD("interface name too long");
658     strcpy(mdata.ifname,ifname);
659
660     COPY_OBJ(mdata.ia,*ia);
661
662     iov.iov_base=&mdata;
663     iov.iov_len =sizeof(mdata);
664
665     FILLZERO(msg);
666     msg.msg_iov=&iov;
667     msg.msg_iovlen=1;
668
669     if (add) {
670         COPY_OBJ(us.addr,*ia);
671         bool_t ok=polypath_make_socket(st,bad,badctx,&us,ifname);
672         if (!ok) goto out;
673
674         msg.msg_control=cmsg_control_buf;
675         msg.msg_controllen=sizeof(cmsg_control_buf);
676
677         struct cmsghdr *h=CMSG_FIRSTHDR(&msg);
678         h->cmsg_level=SOL_SOCKET;
679         h->cmsg_type =SCM_RIGHTS;
680         h->cmsg_len  =CMSG_LEN(cmsgdatalen);
681         memcpy(CMSG_DATA(h),&us.fd,cmsgdatalen);
682     }
683
684     while (iov.iov_len) {
685         ssize_t got=sendmsg(st->privsep_ipcsock_fd,&msg,0);
686         if (got<0) {
687             if (errno!=EINTR) fatal_perror("polypath privsep sendmsg");
688             got=0;
689         } else {
690             assert(got>0);
691             assert((size_t)got<=iov.iov_len);
692         }
693         iov.iov_base=(char*)iov.iov_base+got;
694         iov.iov_len-=got;
695         msg.msg_control=0;
696         msg.msg_controllen=0;
697     }
698
699  out:
700     if (us.fd>=0) close(us.fd);
701 }
702
703 static void child_privsep(struct polypath *st, int ipcsockfd)
704 /* Privsep child main loop. */
705 {
706     struct pollfd fds[2];
707
708     enter_phase(PHASE_CHILDPERSIST);
709
710     st->privsep_ipcsock_fd=ipcsockfd;
711     start_subproc(st,pipe_cloexec,child_monitor,
712                   "interface monitor (grandchild)");
713     for (;;) {
714         int nfds=1;
715         int r=polypath_beforepoll(st,fds,&nfds,0);
716         assert(nfds==1);
717         assert(!r);
718
719         fds[1].fd=st->privsep_ipcsock_fd;
720         fds[1].events=POLLIN;
721
722         r=poll(fds,ARRAY_SIZE(fds),-1);
723
724         if (r<0) {
725             if (errno==EINTR) continue;
726             fatal_perror("polypath privsep poll");
727         }
728         if (fds[1].revents) {
729             if (fds[1].revents & (POLLHUP|POLLIN)) {
730                 polypath_phase_shutdown(st,PHASE_SHUTDOWN);
731                 exit(0);
732             }
733             fatal("polypath privsep poll parent socket revents=%#x",
734                   fds[1].revents);
735         }
736         afterpoll_monitor(st,fds,privsep_handle_ifaddr);
737     }
738 }
739
740 static void privsep_socketpair(int *fd)
741 {
742     int r=socketpair(AF_UNIX,SOCK_STREAM,0,fd);
743     if (r) fatal_perror("socketpair(AF_UNIX,SOCK_STREAM,,)");
744     setcloexec(fd[0]);
745     setcloexec(fd[1]);
746 }
747
748 static void polypath_phase_startprivsep(void *sst, uint32_t newphase)
749 {
750     struct polypath *st=sst;
751
752     if (!will_droppriv()) {
753         add_hook(PHASE_RUN,          polypath_phase_startmonitor,st);
754         return;
755     }
756
757     start_subproc(st,privsep_socketpair,child_privsep,
758                   "socket generator (privsep interface handler)");
759
760     BUF_FREE(&st->lbuf);
761     buffer_destroy(&st->lbuf);
762     buffer_new(&st->lbuf,sizeof(struct privsep_mdata));
763     BUF_ALLOC(&st->lbuf,"polypath mdata buf");
764     st->privsep_incoming_fd=-1;
765
766     register_for_poll(st,polypath_beforepoll,
767                       polypath_afterpoll_privsep,"polypath");
768 }
769
770 static void polypath_phase_shutdown(void *sst, uint32_t newphase)
771 {
772     struct polypath *st=sst;
773     if (st->monitor_pid) {
774         assert(st->monitor_pid>0);
775         kill(st->monitor_pid,SIGTERM);
776     }
777 }
778
779 static void polypath_phase_childpersist(void *sst, uint32_t newphase)
780 {
781     struct polypath *st=sst;
782     struct interf *interf;
783
784     LIST_FOREACH(interf,&st->interfs,entry)
785         udp_socks_childpersist(&st->uc,&interf->socks);
786 }
787
788 #undef BAD
789 #undef BADE
790
791 /*----- generic closure and module setup -----*/
792
793 static list_t *polypath_apply(closure_t *self, struct cloc loc,
794                               dict_t *context, list_t *args)
795 {
796     struct polypath *st;
797
798     COMM_APPLY(st,&st->uc.cc,polypath_,"polypath",loc);
799     COMM_APPLY_STANDARD(st,&st->uc.cc,"polypath",args);
800     UDP_APPLY_STANDARD(st,&st->uc,"polypath");
801
802     struct udpcommon *uc=&st->uc;
803     struct commcommon *cc=&uc->cc;
804
805     uc->authbind=dict_read_string(d,"authbind",False,"udp",cc->loc);
806     st->max_interfs=dict_read_number(d,"max-interfaces",False,"polypath",loc,3);
807
808     st->ifname_pats=dict_read_string_array(d,"interfaces",False,"polypath",
809                                            cc->loc,0);
810     st->permit_loopback=0; /* ifname_wanted reads this */
811     ifname_wanted(st,st->uc.cc.loc,"dummy"); /* walks and checks */
812
813     st->monitor_command=dict_read_string_array(d,"monitor-command",False,
814                                "polypath",cc->loc, default_monitor_command);
815     if (!st->monitor_command[0])
816         cfgfatal(loc,"tun","no polypath interface monitor-command"
817                  " (polypath unsupported on this platform?)\n");
818
819     st->permit_loopback=dict_read_bool(d,"permit-loopback",False,
820                                        "polypath",cc->loc,False);
821
822     LIST_INIT(&st->interfs);
823     buffer_new(&st->lbuf,ADNS_ADDR2TEXT_BUFLEN+100);
824     BUF_ALLOC(&st->lbuf,"polypath lbuf");
825
826     st->monitor_fd=-1;
827     st->monitor_pid=0;
828
829     add_hook(PHASE_GETRESOURCES, polypath_phase_startprivsep,st);
830
831     add_hook(PHASE_SHUTDOWN,    polypath_phase_shutdown,    st);
832     add_hook(PHASE_CHILDPERSIST,polypath_phase_childpersist,st);
833
834     return new_closure(&cc->cl);
835 }
836
837 #endif /* CONFIG_IPV6 */
838
839 void polypath_module(dict_t *dict)
840 {
841 #ifdef CONFIG_IPV6
842     add_closure(dict,"polypath",polypath_apply);
843 #endif /* CONFIG_IPV6 */
844 }