chiark / gitweb /
test-example: Reorder a config to better test CHILDPERSIST
[secnet.git] / udp.c
1 /* UDP send/receive module for secnet */
2
3 /* This module enables sites to communicate by sending UDP
4  * packets. When an instance of the module is created we can
5  * optionally bind to a particular local IP address (not implemented
6  * yet).
7  *
8  * Packets are offered to registered receivers in turn. Once one
9  * accepts it, it isn't offered to any more. */
10
11 #include "secnet.h"
12 #include <stdio.h>
13 #include <unistd.h>
14 #include <fcntl.h>
15 #include <string.h>
16 #include <errno.h>
17 #include <sys/socket.h>
18 #include <sys/wait.h>
19 #include <netinet/in.h>
20 #include <arpa/inet.h>
21 #include "util.h"
22 #include "magic.h"
23 #include "unaligned.h"
24 #include "ipaddr.h"
25 #include "magic.h"
26 #include "comm-common.h"
27
28 static comm_sendmsg_fn udp_sendmsg;
29
30 struct udp {
31     struct udpcommon uc;
32     struct udpsocks socks;
33 };
34
35 /*
36  * Re comm_addr.ix: This field allows us to note in the comm_addr
37  * which socket an incoming packet was received on.  This is required
38  * for conveniently logging the actual source of a packet.  But the ix
39  * does not formally form part of the address: it is not used when
40  * sending, nor when comparing two comm_addrs.
41  *
42  * The special value -1 means that the comm_addr was constructed by
43  * another module in secnet (eg the resolver), rather than being a
44  * description of the source of an incoming packet.
45  */
46
47 static const char *udp_addr_to_string(void *commst, const struct comm_addr *ca)
48 {
49     struct udp *st=commst;
50     struct udpsocks *socks=&st->socks;
51     static char sbuf[100];
52     int ix=ca->ix>=0 ? ca->ix : 0;
53
54     assert(ix>=0 && ix<socks->n_socks);
55     snprintf(sbuf, sizeof(sbuf), "udp:%s%s-%s",
56              iaddr_to_string(&socks->socks[ix].addr),
57              ca->ix<0 ? "&" : "",
58              iaddr_to_string(&ca->ia));
59     return sbuf;
60 }
61
62 static int udp_socks_beforepoll(void *state, struct pollfd *fds, int *nfds_io,
63                                 int *timeout_io)
64 {
65     struct udpsocks *socks=state;
66     int i;
67     BEFOREPOLL_WANT_FDS(socks->n_socks);
68     for (i=0; i<socks->n_socks; i++) {
69         fds[i].fd=socks->socks[i].fd;
70         fds[i].events=POLLIN;
71     }
72     return 0;
73 }
74
75 const char *af_name(int af)
76 {
77     switch (af) {
78     case AF_INET6: return "IPv6";
79     case AF_INET:  return "IPv4";
80     case 0:        return "(any)";
81     default: abort();
82     }
83 }
84
85 void udp_sock_experienced(struct log_if *lg, struct udpcommon *uc,
86                           const char *socksdesc, struct udpsock *us,
87                           bool_t recvsend, int af,
88                           int r, int errnoval)
89 {
90     bool_t success=r>=0;
91     if (us->experienced[recvsend][af][success]++)
92         return;
93     lg_perror(lg, uc->cc.cl.description, &uc->cc.loc,
94               success ? M_INFO : M_WARNING,
95               success ? 0 : errnoval,
96               "%s %s experiencing some %s %s%s%s",
97               socksdesc,iaddr_to_string(&us->addr),
98               success?"success":"trouble",
99               recvsend?"transmitting":"receiving",
100               af?" ":"", af?af_name(af):"");
101 }
102
103 static void udp_socks_afterpoll(void *state, struct pollfd *fds, int nfds)
104 {
105     struct udpsocks *socks=state;
106     struct udpcommon *uc=socks->uc;
107     union iaddr from;
108     socklen_t fromlen;
109     bool_t done;
110     int rv;
111     int i;
112
113     struct commcommon *cc=&uc->cc;
114
115     for (i=0; i<socks->n_socks; i++) {
116         struct udpsock *us=&socks->socks[i];
117         if (i>=nfds) continue;
118         if (!(fds[i].revents & POLLIN)) continue;
119         assert(fds[i].fd == us->fd);
120         int fd=us->fd;
121         do {
122             fromlen=sizeof(from);
123             BUF_ASSERT_FREE(cc->rbuf);
124             BUF_ALLOC(cc->rbuf,"udp_afterpoll");
125             buffer_init(cc->rbuf,calculate_max_start_pad());
126             rv=recvfrom(fd, cc->rbuf->start,
127                         buf_remaining_space(cc->rbuf),
128                         0, &from.sa, &fromlen);
129             if (rv>0) {
130                 cc->rbuf->size=rv;
131                 if (uc->use_proxy) {
132                     /* Check that the packet came from our poxy server;
133                        we shouldn't be contacted directly by anybody else
134                        (since they can trivially forge source addresses) */
135                     if (!iaddr_equal(&from,&uc->proxy)) {
136                         Message(M_INFO,"udp: received packet that's not "
137                                 "from the proxy\n");
138                         BUF_FREE(cc->rbuf);
139                         continue;
140                     }
141                     /* proxy protocol supports ipv4 transport only */
142                     from.sa.sa_family=AF_INET;
143                     BUF_GET_BYTES(unprepend,cc->rbuf,&from.sin.sin_addr,4);
144                     buf_unprepend(cc->rbuf,2);
145                     BUF_GET_BYTES(unprepend,cc->rbuf,&from.sin.sin_port,2);
146                 }
147                 struct comm_addr ca;
148                 ca.comm=&cc->ops;
149                 ca.ia=from;
150                 ca.ix=i;
151                 done=comm_notify(&cc->notify, cc->rbuf, &ca);
152                 if (!done) {
153                     uint32_t msgtype;
154                     if (cc->rbuf->size>12 /* prevents traffic amplification */
155                         && ((msgtype=get_uint32(cc->rbuf->start+8))
156                             != LABEL_NAK)) {
157                         uint32_t source,dest;
158                         /* Manufacture and send NAK packet */
159                         source=get_uint32(cc->rbuf->start); /* Us */
160                         dest=get_uint32(cc->rbuf->start+4); /* Them */
161                         send_nak(&ca,source,dest,msgtype,cc->rbuf,"unwanted");
162                     }
163                     BUF_FREE(cc->rbuf);
164                 }
165                 BUF_ASSERT_FREE(cc->rbuf);
166             } else { /* rv<=0 */
167                 if (errno!=EINTR && !iswouldblock(errno))
168                     udp_sock_experienced(0,uc, "socket",us, 0,0, rv,errno);
169                 BUF_FREE(cc->rbuf);
170             }
171         } while (rv>=0);
172     }
173 }
174
175 static bool_t udp_sendmsg(void *commst, struct buffer_if *buf,
176                           const struct comm_addr *dest)
177 {
178     struct udp *st=commst;
179     struct udpcommon *uc=&st->uc;
180     struct udpsocks *socks=&st->socks;
181     uint8_t *sa;
182
183     if (uc->use_proxy) {
184         struct udpsock *us=&socks->socks[0];
185         sa=buf_prepend(buf,8);
186         if (dest->ia.sa.sa_family != AF_INET) {
187             Message(M_INFO,
188                "udp: proxy means dropping outgoing non-IPv4 packet to %s\n",
189                     iaddr_to_string(&dest->ia));
190             return False;
191         }
192         memcpy(sa,&dest->ia.sin.sin_addr,4);
193         memset(sa+4,0,4);
194         memcpy(sa+6,&dest->ia.sin.sin_port,2);
195         int r=sendto(us->fd,sa,buf->size+8,0,&uc->proxy.sa,
196                iaddr_socklen(&uc->proxy));
197         udp_sock_experienced(0,uc, "proxy",us, 1,0, r,errno);
198         buf_unprepend(buf,8);
199     } else {
200         int i,r;
201         bool_t allunsupported=True;
202         int af=dest->ia.sa.sa_family;
203         for (i=0; i<socks->n_socks; i++) {
204             struct udpsock *us=&socks->socks[i];
205             if (us->addr.sa.sa_family != af)
206                 /* no point even trying */
207                 continue;
208             r=sendto(us->fd, buf->start, buf->size, 0,
209                      &dest->ia.sa, iaddr_socklen(&dest->ia));
210             udp_sock_experienced(0,uc, "socket",us, 1,af, r,errno);
211             if (r>=0) return True;
212             if (!(errno==EAFNOSUPPORT || errno==ENETUNREACH))
213                 /* who knows what that error means? */
214                 allunsupported=False;
215         }
216         return !allunsupported; /* see doc for comm_sendmsg_fn in secnet.h */
217     }
218
219     return True;
220 }
221
222 void udp_destroy_socket(struct udpcommon *uc, struct udpsock *us)
223 {
224     if (us->fd>=0) {
225         close(us->fd);
226         us->fd=-1;
227     }
228 }
229
230 bool_t udp_make_socket(struct udpcommon *uc, struct udpsock *us,
231                        int failmsgclass)
232 {
233     const union iaddr *addr=&us->addr;
234     struct commcommon *cc=&uc->cc;
235     us->fd=-1;
236
237 #define FAIL_LG 0, cc->cl.description, &cc->loc, failmsgclass
238 #define FAIL(...) do{                                           \
239         lg_perror(FAIL_LG,errno,__VA_ARGS__);   \
240         goto failed;                                            \
241     }while(0)
242
243     FILLZERO(us->experienced);
244     us->fd=socket(addr->sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
245     if (us->fd<0) FAIL("socket");
246     setnonblock(us->fd);
247     setcloexec(us->fd);
248 #ifdef CONFIG_IPV6
249     if (addr->sa.sa_family==AF_INET6) {
250         int r;
251         int optval=1;
252         socklen_t optlen=sizeof(optval);
253         r=setsockopt(us->fd,IPPROTO_IPV6,IPV6_V6ONLY,&optval,optlen);
254         if (r) FAIL("setsockopt(,IPV6_V6ONLY,&1,)");
255     }
256 #endif
257
258     if (uc->authbind) {
259         pid_t c;
260         int status;
261
262         /* XXX this fork() and waitpid() business needs to be hidden
263            in some system-specific library functions. */
264         c=fork();
265         if (c==-1)
266             FAIL("fork() for authbind");
267         if (c==0) {
268             char *argv[5], addrstr[33], portstr[5];
269             const char *addrfam;
270             int port;
271             afterfork();
272             switch (addr->sa.sa_family) {
273             case AF_INET:
274                 sprintf(addrstr,"%08lX",(long)addr->sin.sin_addr.s_addr);
275                 port=addr->sin.sin_port;
276                 addrfam=NULL;
277                 break;
278 #ifdef CONFIG_IPV6
279             case AF_INET6: {
280                 int i;
281                 for (i=0; i<16; i++)
282                     sprintf(addrstr+i*2,"%02X",addr->sin6.sin6_addr.s6_addr[i]);
283                 port=addr->sin6.sin6_port;
284                 addrfam="6";
285                 break;
286             }
287 #endif /*CONFIG_IPV6*/
288             default:
289                 fatal("udp (%s:%d): unsupported address family for authbind",
290                       cc->loc.file,cc->loc.line);
291             }
292             sprintf(portstr,"%04X",port);
293             argv[0]=uc->authbind;
294             argv[1]=addrstr;
295             argv[2]=portstr;
296             argv[3]=(char*)addrfam;
297             argv[4]=NULL;
298             dup2(us->fd,0);
299             execvp(uc->authbind,argv);
300             _exit(255);
301         }
302         while (waitpid(c,&status,0)==-1) {
303             if (errno==EINTR) continue;
304             FAIL("waitpid for authbind");
305         }
306         if (status) {
307             if (WIFEXITED(status) && WEXITSTATUS(status)<127) {
308                 int es=WEXITSTATUS(status);
309                 lg_perror(FAIL_LG,es,
310                           "authbind exited with error exit status %d;"
311                           " indicates error",es);
312             } else {
313                 lg_exitstatus(FAIL_LG,status,"authbind");
314             }
315             goto failed;
316         }
317     } else {
318         if (bind(us->fd, &addr->sa, iaddr_socklen(addr))!=0)
319             FAIL("bind (%s)",iaddr_to_string(addr));
320     }
321     return True;
322
323 failed:
324     udp_destroy_socket(uc,us);
325     return False;
326
327 #undef FAIL
328 }
329
330 void udp_socks_register(struct udpcommon *uc, struct udpsocks *socks)
331 {
332     socks->uc=uc;
333     socks->interest=
334         register_for_poll(socks,udp_socks_beforepoll,udp_socks_afterpoll,"udp");
335 }
336
337 void udp_socks_deregister(struct udpcommon *uc, struct udpsocks *socks)
338 {
339     socks->uc=uc;
340     deregister_for_poll(socks->interest);
341 }
342
343 void udp_socks_childpersist(struct udpcommon *uc, struct udpsocks *socks)
344 {
345     int i;
346     for (i=0; i<socks->n_socks; i++)
347         udp_destroy_socket(uc,&socks->socks[i]);
348 }
349
350 static void udp_childpersist_hook(void *sst, uint32_t new_phase)
351 {
352     struct udp *st=sst;
353     udp_socks_childpersist(&st->uc,&st->socks);
354 }
355
356 static void udp_phase_hook(void *sst, uint32_t new_phase)
357 {
358     struct udp *st=sst;
359     struct udpsocks *socks=&st->socks;
360     struct udpcommon *uc=&st->uc;
361     int i;
362     for (i=0; i<socks->n_socks; i++)
363         udp_make_socket(uc,&socks->socks[i],M_FATAL);
364
365     udp_socks_register(uc,socks);
366
367     add_hook(PHASE_CHILDPERSIST,udp_childpersist_hook,st);
368 }
369
370 static list_t *udp_apply(closure_t *self, struct cloc loc, dict_t *context,
371                          list_t *args)
372 {
373     struct udp *st;
374     list_t *caddrl;
375     list_t *l;
376     uint32_t a;
377     int i;
378
379     COMM_APPLY(st,&st->uc.cc,udp_,"udp",loc);
380     COMM_APPLY_STANDARD(st,&st->uc.cc,"udp",args);
381     UDP_APPLY_STANDARD(st,&st->uc,"udp");
382
383     struct udpcommon *uc=&st->uc;
384     struct udpsocks *socks=&st->socks;
385     struct commcommon *cc=&uc->cc;
386
387     union iaddr defaultaddrs[] = {
388 #ifdef CONFIG_IPV6
389         { .sin6 = { .sin6_family=AF_INET6,
390                     .sin6_port=htons(uc->port),
391                     .sin6_addr=IN6ADDR_ANY_INIT } },
392 #endif
393         { .sin = { .sin_family=AF_INET,
394                    .sin_port=htons(uc->port),
395                    .sin_addr= { .s_addr=INADDR_ANY } } }
396     };
397
398     caddrl=dict_lookup(d,"address");
399     socks->n_socks=caddrl ? list_length(caddrl) : (int)ARRAY_SIZE(defaultaddrs);
400     if (socks->n_socks<=0 || socks->n_socks>UDP_MAX_SOCKETS)
401         cfgfatal(cc->loc,"udp","`address' must be 1..%d addresses",
402                  UDP_MAX_SOCKETS);
403
404     for (i=0; i<socks->n_socks; i++) {
405         struct udpsock *us=&socks->socks[i];
406         if (!list_length(caddrl)) {
407             us->addr=defaultaddrs[i];
408         } else {
409             string_item_to_iaddr(list_elem(caddrl,i),uc->port,&us->addr,"udp");
410         }
411         us->fd=-1;
412     }
413
414     l=dict_lookup(d,"proxy");
415     if (l) {
416         uc->use_proxy=True;
417         uc->proxy.sa.sa_family=AF_INET;
418         item=list_elem(l,0);
419         if (!item || item->type!=t_string) {
420             cfgfatal(cc->loc,"udp","proxy must supply ""addr"",port\n");
421         }
422         a=string_item_to_ipaddr(item,"proxy");
423         uc->proxy.sin.sin_addr.s_addr=htonl(a);
424         item=list_elem(l,1);
425         if (!item || item->type!=t_number) {
426             cfgfatal(cc->loc,"udp","proxy must supply ""addr"",port\n");
427         }
428         uc->proxy.sin.sin_port=htons(item->data.number);
429     }
430
431     update_max_start_pad(&comm_max_start_pad, uc->use_proxy ? 8 : 0);
432
433     add_hook(PHASE_GETRESOURCES,udp_phase_hook,st);
434
435     return new_closure(&cc->cl);
436 }
437
438 void udp_module(dict_t *dict)
439 {
440     add_closure(dict,"udp",udp_apply);
441 }