chiark / gitweb /
polypath: Break up child process handling
[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 };
35
36 #define LG 0, st->uc.cc.cl.description, &st->uc.cc.loc
37
38 static const char *const default_loopback_ifname_pats[] = {
39     "!lo", 0
40 };
41 static const char *const default_ifname_pats[] = {
42     "!tun*","!tap*","!sl*","!userv*", "*", 0
43 };
44
45 static const char *const default_monitor_command[] = {
46 #if __linux__
47     DATAROOTDIR "/secnet/" "polypath-interface-monitor-linux", 0
48 #else
49     0
50 #endif
51 };
52
53 static const char *polypath_addr_to_string(void *commst,
54                                            const struct comm_addr *ca)
55 {
56     static char sbuf[100];
57
58     snprintf(sbuf, sizeof(sbuf), "polypath:%s",
59              iaddr_to_string(&ca->ia));
60     return sbuf;
61 }
62
63 static bool_t ifname_search_pats(struct polypath *st, struct cloc loc,
64                                  const char *ifname, bool_t *want_io,
65                                  const char *const *pats) {
66     /* Returns True iff we found a list entry, in which case *want_io
67      * is set to the sense of that entry.  Otherwise *want_io is set
68      * to the sense of the last entry, or unchanged if there were no pats. */
69     if (!pats)
70         return False;
71     const char *const *pati;
72     for (pati=pats; *pati; pati++) {
73         const char *pat=*pati;
74         if (*pat=='!') { *want_io=False; pat++; }
75         else if (*pat=='+') { *want_io=True; pat++; }
76         else if (*pat=='*' || isalnum((unsigned char)*pat)) { *want_io=True; }
77         else cfgfatal(loc,"polypath","invalid interface name pattern `%s'",pat);
78         int match=fnmatch(pat,ifname,0);
79         if (match==0) return True;
80         if (match!=FNM_NOMATCH)
81             cfgfatal(loc,"polypath","fnmatch failed! (pattern `%s')",pat);
82     }
83     return False;
84 }
85
86 static bool_t ifname_wanted(struct polypath *st, struct cloc loc,
87                             const char *ifname) {
88     bool_t want=False; /* pretend an empty cfg ends with !<doesn'tmatch> */
89     if (ifname_search_pats(st,loc,ifname,&want, st->ifname_pats))
90         return want;
91     if (want) /* last pattern was positive, do not search default */
92         return False;
93     if (!st->permit_loopback &&
94         ifname_search_pats(st,loc,ifname,&want, default_loopback_ifname_pats))
95         return want;
96     if (ifname_search_pats(st,loc,ifname,&want, default_ifname_pats))
97         return want;
98     abort();
99 }
100
101 static int polypath_beforepoll(void *state, struct pollfd *fds, int *nfds_io,
102                                int *timeout_io)
103 {
104     struct polypath *st=state;
105     BEFOREPOLL_WANT_FDS(1);
106     fds[0].fd=st->monitor_fd;
107     fds[0].events=POLLIN;
108     return 0;
109 }
110
111 static inline bool_t matches32(uint32_t word, uint32_t prefix, int prefixlen)
112 {
113     assert(prefixlen>0);
114     assert(prefixlen<=32);
115     uint32_t mask = ~(((uint32_t)1 << (32-prefixlen)) - 1);
116     assert(!(prefix & ~mask));
117     return (word & mask) == prefix;
118 }
119
120 /* These macros expect
121  *    bad_fn_type *const bad;
122  *    void *badctx;
123  * and
124  *   out:
125  */
126 #define BAD(m)     do{ bad(st,badctx,m,0);  goto out; }while(0)
127 #define BADE(m,ev) do{ bad(st,badctx,m,ev); goto out; }while(0)
128 typedef void bad_fn_type(struct polypath *st, void *badctx,
129                          const char* m, int ev);
130
131 typedef void polypath_ppml_callback_type(struct polypath *st,
132           bad_fn_type *bad, void *badctx,
133           bool_t add, const char *ifname, const char *ifaddr,
134           const union iaddr *ia, int fd /* -1 if none yet */);
135
136 struct ppml_bad_ctx {
137     const char *orgl;
138     char *undospace;
139 };
140
141 static void ppml_bad(struct polypath *st, void *badctx, const char *m, int ev)
142 {
143     struct ppml_bad_ctx *bc=badctx;
144     if (bc->undospace)
145         *(bc->undospace)=' ';
146     lg_perror(LG,M_WARNING,ev,
147               "error processing polypath state change: %s"
148               " (while processing `%s')",
149               m,bc->orgl);
150 }
151
152 static void polypath_process_monitor_line(struct polypath *st, char *orgl,
153                                       polypath_ppml_callback_type *callback)
154     /* always calls callback with fd==-1 */
155 {
156     struct udpcommon *uc=&st->uc;
157     char *l=orgl;
158     bad_fn_type (*const bad)=ppml_bad;
159     struct ppml_bad_ctx badctx[1]={{
160             .orgl=orgl,
161             .undospace=0
162         }};
163
164     bool_t add;
165     int c=*l++;
166     if (c=='+') add=True;
167     else if (c=='-') add=False;
168     else BAD("bad +/-");
169
170     int proto;
171     c=*l++;
172     if (c=='4') proto=AF_INET;
173     else if (c=='6') proto=AF_INET6;
174     else BAD("bad proto");
175
176     char *space=strchr(l,' ');
177     if (!space) BAD("no first space");
178     const char *ifname=space+1;
179
180     space=strchr(ifname,' ');
181     if (!space) BAD("no second space");
182     const char *ifaddr=space+1;
183     *space=0;
184     badctx->undospace=space;
185
186     union iaddr ia;
187     FILLZERO(ia);
188     socklen_t salen=sizeof(ia);
189     int r=adns_text2addr(ifaddr,uc->port, adns_qf_addrlit_ipv4_quadonly,
190                          &ia.sa, &salen);
191     assert(r!=ENOSPC);
192     if (r) BADE("adns_text2addr",r);
193     if (ia.sa.sa_family!=proto) BAD("address family mismatch");
194
195 #define DONT(m) do{                                                     \
196         if (add)                                                        \
197             lg_perror(LG,M_INFO,0,"ignoring %s [%s]: %s",ifname,ifaddr,m); \
198         goto out;                                                       \
199     }while(0)
200
201     if (!ifname_wanted(st,st->uc.cc.loc,ifname))
202         DONT("unwanted interface name");
203
204     switch (ia.sa.sa_family) {
205     case AF_INET6: {
206         const struct in6_addr *i6=&ia.sin6.sin6_addr;
207 #define DONTKIND(X,m) \
208         if (IN6_IS_ADDR_##X(i6)) DONT("IPv6 address is " m)
209         DONTKIND(UNSPECIFIED, "unspecified");
210         DONTKIND(MULTICAST  , "multicast"  );
211         DONTKIND(LINKLOCAL  , "link local" );
212         DONTKIND(SITELOCAL  , "site local" );
213         DONTKIND(V4MAPPED   , "v4-mapped"  );
214         if (!st->permit_loopback)
215             DONTKIND(LOOPBACK   , "loopback"   );
216 #undef DONTKIND
217 #define DONTMASK(w7x,w6x,prefixlen,m)                                   \
218         if (matches32(get_uint32(i6->s6_addr),                          \
219                       ((uint32_t)0x##w7x << 16) | (uint32_t)0x##w6x,    \
220                       prefixlen))                                       \
221             DONT("IPv6 address is " m)
222         DONTMASK( 100,   0,  8, "Discard-Only (RFC6666)");
223         DONTMASK(2001,   0, 23, "in IETF protocol block (RFC2928)");
224 #undef DONTMASK
225         break;
226     }
227     case AF_INET: {
228         const uint32_t i4=htonl(ia.sin.sin_addr.s_addr);
229         if (i4==INADDR_ANY) DONT("IPv4 address is any/unspecified");
230         if (i4==INADDR_BROADCAST) DONT("IPv4 address is all hosts broadcast");
231 #define DONTMASK(b3,b2,b1,b0,prefixlen,m) do{                           \
232             const uint8_t prefixbytes[4] = { (b3),(b2),(b1),(b0) };     \
233             if (matches32(i4,get_uint32(prefixbytes),prefixlen))        \
234                 DONT("IPv4 address is " m);                             \
235         }while(0)
236         DONTMASK(169,254,0,0, 16, "link local");
237         DONTMASK(224,  0,0,0,  4, "multicast");
238         DONTMASK(192,  0,0,0, 24, "in IETF protocol block (RFC6890)");
239         DONTMASK(240,  0,0,0,  4, "in reserved addressing block (RFC1112)");
240         if (!st->permit_loopback)
241             DONTMASK(127,  0,0,0,  8, "loopback");
242 #undef DONTMASK
243         break;
244     }
245     default:
246         abort();
247     }
248
249 #undef DONT
250
251     /* OK, process it */
252     callback(st, bad,badctx, add,ifname,ifaddr,&ia,-1);
253
254  out:;
255 }
256
257 static void dump_pria(struct polypath *st, const char *ifname)
258 {
259 #ifdef POLYPATH_DEBUG
260     struct interf *interf;
261     if (ifname)
262         lg_perror(LG,M_DEBUG,0, "polypath record ifaddr `%s'",ifname);
263     LIST_FOREACH(interf, &st->interfs, entry) {
264         lg_perror(LG,M_DEBUG,0, "  polypath interface `%s', nsocks=%d",
265                   interf->name, interf->socks.n_socks);
266         int i;
267         for (i=0; i<interf->socks.n_socks; i++) {
268             struct udpsock *us=&interf->socks.socks[i];
269             lg_perror(LG,M_DEBUG,0, "    polypath sock fd=%d addr=%s",
270                       us->fd, iaddr_to_string(&us->addr));
271         }
272     }
273 #endif
274 }
275
276 static bool_t polypath_make_socket(struct polypath *st,
277                                    bad_fn_type *bad, void *badctx,
278                                    struct udpsock *us, const char *ifname)
279     /* on error exit has called bad; might leave us->fd as -1 */
280 {
281     assert(us->fd==-1);
282
283     bool_t ok=udp_make_socket(&st->uc,us,M_WARNING);
284     if (!ok) BAD("unable to set up socket");
285     int r=setsockopt(us->fd,SOL_SOCKET,SO_BINDTODEVICE,
286                      ifname,strlen(ifname)+1);
287     if (r) BADE("setsockopt(,,SO_BINDTODEVICE,)",errno);
288     return True;
289
290  out:
291     return False;
292 }
293
294 static void polypath_record_ifaddr(struct polypath *st,
295                                    bad_fn_type *bad, void *badctx,
296                                    bool_t add, const char *ifname,
297                                    const char *ifaddr,
298                                    const union iaddr *ia, int fd)
299 {
300     struct udpcommon *uc=&st->uc;
301     struct interf *interf=0;
302     struct udpsock *us=0;
303
304     dump_pria(st,ifname);
305
306     int n_ifs=0;
307     LIST_FOREACH(interf,&st->interfs,entry) {
308         if (!strcmp(interf->name,ifname))
309             goto found_interf;
310         n_ifs++;
311     }
312     /* not found */
313     if (n_ifs==st->max_interfs) BAD("too many interfaces");
314     interf=malloc(sizeof(*interf));
315     if (!interf) BADE("malloc for new interface",errno);
316     interf->name=0;
317     interf->socks.n_socks=0;
318     FILLZERO(interf->experienced_xmit_noaf);
319     LIST_INSERT_HEAD(&st->interfs,interf,entry);
320     udp_socks_register(&st->uc,&interf->socks);
321     interf->name=strdup(ifname);
322     if (!interf->name) BADE("strdup interface name",errno);
323  found_interf:
324
325     if (add) {
326         if (interf->socks.n_socks == UDP_MAX_SOCKETS)
327             BAD("too many addresses on this interface");
328         struct udpsock *us=&interf->socks.socks[interf->socks.n_socks];
329         us->fd=-1;
330         COPY_OBJ(us->addr,*ia);
331         if (fd<0) {
332             bool_t ok=polypath_make_socket(st,bad,badctx, us,ifname);
333             if (!ok) goto out;
334         } else {
335             FILLZERO(us->experienced);
336             us->fd=fd;
337             fd=-1;
338         }
339         interf->socks.n_socks++;
340         us=0; /* do not destroy this socket during `out' */
341         lg_perror(LG,M_INFO,0,"using %s %s",ifname,ifaddr);
342     } else {
343         int i;
344         for (i=0; i<interf->socks.n_socks; i++)
345             if (!memcmp(&interf->socks.socks[i].addr,ia,sizeof(*ia)))
346                 goto address_remove_found;
347         BAD("address to remove not found");
348     address_remove_found:
349         lg_perror(LG,M_INFO,0,"removed %s %s",ifname,ifaddr);
350         udp_destroy_socket(&st->uc,&interf->socks.socks[i]);
351         interf->socks.socks[i]=
352             interf->socks.socks[--interf->socks.n_socks];
353     }
354
355  out:
356     if (us)
357         udp_destroy_socket(uc,us);
358     if (fd>=0)
359         close(fd);
360     if (interf && !interf->socks.n_socks) {
361         udp_socks_deregister(&st->uc,&interf->socks);
362         LIST_REMOVE(interf,entry);
363         free(interf->name);
364         free(interf);
365     }
366
367     dump_pria(st,0);
368 }
369
370 static void subproc_problem(struct polypath *st,
371                             enum async_linebuf_result alr, const char *emsg)
372 {
373     int status;
374     assert(st->monitor_pid);
375
376     pid_t gotpid=waitpid(st->monitor_pid,&status,WNOHANG);
377     if (gotpid==st->monitor_pid) {
378         st->monitor_pid=0;
379         lg_exitstatus(LG,M_FATAL,status,"interface monitor");
380     } else if (gotpid<0)
381         lg_perror(LG,M_ERR,errno,"unable to reap interface monitor");
382     else
383         assert(gotpid==0);
384
385     if (alr==async_linebuf_eof)
386         lg_perror(LG,M_FATAL,0,"unexpected EOF from interface monitor");
387     else
388         lg_perror(LG,M_FATAL,0,"bad output from interface monitor: %s",emsg);
389     assert(!"not reached");
390 }
391
392 static void afterpoll_monitor(struct polypath *st, struct pollfd *fd,
393                               polypath_ppml_callback_type *callback)
394 {
395     enum async_linebuf_result alr;
396     const char *emsg;
397     
398     while ((alr=async_linebuf_read(fd,&st->lbuf,&emsg)) == async_linebuf_ok)
399         polypath_process_monitor_line(st,st->lbuf.base,callback);
400
401     if (alr==async_linebuf_nothing)
402         return;
403
404     subproc_problem(st,alr,emsg);
405 }
406
407 static void polypath_afterpoll_monitor(void *state, struct pollfd *fds,
408                                        int nfds)
409 {
410     struct polypath *st=state;
411     if (nfds<1) return;
412     afterpoll_monitor(st,fds,polypath_record_ifaddr);
413 }
414
415 /* Actual udp packet sending work */
416 static bool_t polypath_sendmsg(void *commst, struct buffer_if *buf,
417                           const struct comm_addr *dest)
418 {
419     struct polypath *st=commst;
420     struct interf *interf;
421     bool_t allreasonable=True;
422     int af=dest->ia.sa.sa_family;
423
424     LIST_FOREACH(interf,&st->interfs,entry) {
425         int i;
426         bool_t attempted=False, reasonable=False;
427         for (i=0; i<interf->socks.n_socks; i++) {
428             struct udpsock *us=&interf->socks.socks[i];
429             if (af != us->addr.sa.sa_family)
430                 continue;
431             attempted=True;
432             int r=sendto(us->fd,buf->start,buf->size,
433                          0,&dest->ia.sa,iaddr_socklen(&dest->ia));
434             udp_sock_experienced(0,&st->uc, interf->name,us,
435                                  1,af, r,errno);
436             if (r>=0) {
437                 reasonable=True;
438                 break;
439             }
440             if (!(errno==EAFNOSUPPORT || errno==ENETUNREACH))
441                 reasonable=True;
442             lg_perror(LG,M_DEBUG,errno,"%s [%s] xmit %"PRIu32" bytes to %s",
443                       interf->name,iaddr_to_string(&us->addr),
444                       buf->size,iaddr_to_string(&dest->ia));
445         }
446         if (!attempted)
447             if (!interf->experienced_xmit_noaf[af]++)
448                 lg_perror(LG,M_WARNING,0,
449                           "%s has no suitable address to transmit %s",
450                           interf->name, af_name(af));
451         allreasonable *= reasonable;
452     }
453     return allreasonable;
454 }
455
456 static void child_monitor(struct polypath *st, int childfd)
457 {
458     dup2(childfd,1);
459     execvp(st->monitor_command[0],(char**)st->monitor_command);
460     fprintf(stderr,"secnet: cannot execute %s: %s\n",
461             st->monitor_command[0], strerror(errno));
462     exit(-1);
463 }
464
465 static void start_subproc(struct polypath *st, void (*make_fdpair)(int[2]),
466                           void (*child)(struct polypath *st, int childfd))
467 {
468     int pfds[2];
469
470     assert(!st->monitor_pid);
471     assert(st->monitor_fd<0);
472
473     make_fdpair(pfds);
474
475     pid_t pid=fork();
476     if (!pid) {
477         afterfork();
478         child(st,pfds[1]);
479         abort();
480     }
481     if (pid<0)
482         fatal_perror("%s: failed to fork for interface monitoring",
483                      st->uc.cc.cl.description);
484
485     close(pfds[1]);
486     st->monitor_pid=pid;
487     st->monitor_fd=pfds[0];
488     setnonblock(st->monitor_fd);
489 }
490
491 static void polypath_phase_startmonitor(void *sst, uint32_t newphase)
492 {
493     struct polypath *st=sst;
494     start_subproc(st,pipe_cloexec,child_monitor);
495     register_for_poll(st,polypath_beforepoll,
496                       polypath_afterpoll_monitor,"polypath");
497 }
498
499 static void polypath_phase_shutdown(void *sst, uint32_t newphase)
500 {
501     struct polypath *st=sst;
502     if (st->monitor_pid) {
503         assert(st->monitor_pid>0);
504         kill(st->monitor_pid,SIGTERM);
505     }
506 }
507
508 #undef BAD
509 #undef BADE
510
511 static list_t *polypath_apply(closure_t *self, struct cloc loc,
512                               dict_t *context, list_t *args)
513 {
514     struct polypath *st;
515
516     COMM_APPLY(st,&st->uc.cc,polypath_,"polypath",loc);
517     COMM_APPLY_STANDARD(st,&st->uc.cc,"polypath",args);
518     UDP_APPLY_STANDARD(st,&st->uc,"polypath");
519
520     struct udpcommon *uc=&st->uc;
521     struct commcommon *cc=&uc->cc;
522
523     st->max_interfs=dict_read_number(d,"max-interfaces",False,"polypath",loc,3);
524
525     st->ifname_pats=dict_read_string_array(d,"interfaces",False,"polypath",
526                                            cc->loc,0);
527     st->permit_loopback=0; /* ifname_wanted reads this */
528     ifname_wanted(st,st->uc.cc.loc," "); /* try to check each pattern */
529
530     st->monitor_command=dict_read_string_array(d,"monitor-command",False,
531                                "polypath",cc->loc, default_monitor_command);
532     if (!st->monitor_command[0])
533         cfgfatal(loc,"polypath","no polypath interface monitor-command"
534                  " (polypath unsupported on this platform?)\n");
535
536     st->permit_loopback=dict_read_bool(d,"permit-loopback",False,
537                                        "polypath",cc->loc,False);
538
539     LIST_INIT(&st->interfs);
540     buffer_new(&st->lbuf,ADNS_ADDR2TEXT_BUFLEN+100);
541     BUF_ALLOC(&st->lbuf,"polypath lbuf");
542
543     st->monitor_fd=-1;
544     st->monitor_pid=0;
545
546     add_hook(PHASE_RUN,         polypath_phase_startmonitor,st);
547     add_hook(PHASE_SHUTDOWN,    polypath_phase_shutdown,    st);
548
549     return new_closure(&cc->cl);
550 }
551
552 #endif /* CONFIG_IPV6 */
553
554 void polypath_module(dict_t *dict)
555 {
556 #ifdef CONFIG_IPV6
557     add_closure(dict,"polypath",polypath_apply);
558 #endif /* CONFIG_IPV6 */
559 }