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