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