chiark / gitweb /
a2bb90785bbbfcacf5721d8bb35f0cbed319f948
[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 && socks->n_socks>1 ? "&" : "",
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                           struct udpsocks *socks, 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               socks->desc,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,False)) {
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                     udp_sock_experienced(0,uc,socks,us,0,
154                                          from.sa.sa_family,0,0);
155                 } else {
156                     uint32_t msgtype;
157                     if (cc->rbuf->size>12 /* prevents traffic amplification */
158                         && ((msgtype=get_uint32(cc->rbuf->start+8))
159                             != LABEL_NAK)) {
160                         uint32_t source,dest;
161                         /* Manufacture and send NAK packet */
162                         source=get_uint32(cc->rbuf->start); /* Us */
163                         dest=get_uint32(cc->rbuf->start+4); /* Them */
164                         send_nak(&ca,source,dest,msgtype,cc->rbuf,"unwanted");
165                     }
166                     BUF_FREE(cc->rbuf);
167                 }
168                 BUF_ASSERT_FREE(cc->rbuf);
169             } else { /* rv<=0 */
170                 if (errno!=EINTR && !iswouldblock(errno))
171                     udp_sock_experienced(0,uc,socks,us, 0,0, rv,errno);
172                 BUF_FREE(cc->rbuf);
173             }
174         } while (rv>=0);
175     }
176 }
177
178 static bool_t udp_sendmsg(void *commst, struct buffer_if *buf,
179                           const struct comm_addr *dest)
180 {
181     struct udp *st=commst;
182     struct udpcommon *uc=&st->uc;
183     struct udpsocks *socks=&st->socks;
184     uint8_t *sa;
185
186     if (uc->use_proxy) {
187         struct udpsock *us=&socks->socks[0];
188         sa=buf_prepend(buf,8);
189         if (dest->ia.sa.sa_family != AF_INET) {
190             Message(M_INFO,
191                "udp: proxy means dropping outgoing non-IPv4 packet to %s\n",
192                     iaddr_to_string(&dest->ia));
193             return False;
194         }
195         memcpy(sa,&dest->ia.sin.sin_addr,4);
196         memset(sa+4,0,4);
197         memcpy(sa+6,&dest->ia.sin.sin_port,2);
198         int r=sendto(us->fd,sa,buf->size+8,0,&uc->proxy.sa,
199                iaddr_socklen(&uc->proxy));
200         udp_sock_experienced(0,uc,socks,us, 1,0, r,errno);
201         buf_unprepend(buf,8);
202     } else {
203         int i,r;
204         bool_t allunsupported=True;
205         int af=dest->ia.sa.sa_family;
206         for (i=0; i<socks->n_socks; i++) {
207             struct udpsock *us=&socks->socks[i];
208             if (us->addr.sa.sa_family != af)
209                 /* no point even trying */
210                 continue;
211             r=sendto(us->fd, buf->start, buf->size, 0,
212                      &dest->ia.sa, iaddr_socklen(&dest->ia));
213             udp_sock_experienced(0,uc,socks,us, 1,af, r,errno);
214             if (r>=0) return True;
215             if (!(errno==EAFNOSUPPORT || errno==ENETUNREACH))
216                 /* who knows what that error means? */
217                 allunsupported=False;
218         }
219         return !allunsupported; /* see doc for comm_sendmsg_fn in secnet.h */
220     }
221
222     return True;
223 }
224
225 void udp_destroy_socket(struct udpcommon *uc, struct udpsock *us)
226 {
227     if (us->fd>=0) {
228         close(us->fd);
229         us->fd=-1;
230     }
231 }
232
233 #define FAIL_LG 0, cc->cl.description, &cc->loc, failmsgclass
234 #define FAIL(...) do{                                           \
235         lg_perror(FAIL_LG,errno,__VA_ARGS__);   \
236         goto failed;                                            \
237     }while(0)
238
239 static bool_t record_socket_gotaddr(struct udpcommon *uc, struct udpsock *us,
240                                     int failmsgclass)
241 {
242     struct commcommon *cc=&uc->cc;
243     socklen_t salen=sizeof(us->addr);
244     int r=getsockname(us->fd,&us->addr.sa,&salen);
245     if (r) FAIL("getsockname()");
246     if (salen>sizeof(us->addr)) { errno=0; FAIL("getsockname() length"); }
247     return True;
248
249  failed:
250     return False;
251 }
252
253 bool_t udp_import_socket(struct udpcommon *uc, struct udpsock *us,
254                          int failmsgclass, int fd)
255 {
256     FILLZERO(us->experienced);
257     us->fd=fd;
258     return record_socket_gotaddr(uc,us,failmsgclass);
259 }
260
261 bool_t udp_make_socket(struct udpcommon *uc, struct udpsock *us,
262                        int failmsgclass)
263 {
264     const union iaddr *addr=&us->addr;
265     struct commcommon *cc=&uc->cc;
266     us->fd=-1;
267
268     FILLZERO(us->experienced);
269     us->fd=socket(addr->sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
270     if (us->fd<0) FAIL("socket");
271     setnonblock(us->fd);
272     setcloexec(us->fd);
273 #ifdef CONFIG_IPV6
274     if (addr->sa.sa_family==AF_INET6) {
275         int r;
276         int optval=1;
277         socklen_t optlen=sizeof(optval);
278         r=setsockopt(us->fd,IPPROTO_IPV6,IPV6_V6ONLY,&optval,optlen);
279         if (r) FAIL("setsockopt(,IPV6_V6ONLY,&1,)");
280     }
281 #endif
282
283     if (uc->authbind) {
284         pid_t c;
285         int status;
286         char desc[200];
287         snprintf(desc,sizeof(desc),"authbind for %s: %s",
288                  iaddr_to_string(addr), uc->authbind);
289
290         /* XXX this fork() and waitpid() business needs to be hidden
291            in some system-specific library functions. */
292         c=fork();
293         if (c==-1)
294             FAIL("fork() for authbind");
295         if (c==0) {
296             char *argv[5], addrstr[33], portstr[5];
297             const char *addrfam;
298             int port;
299             afterfork();
300             switch (addr->sa.sa_family) {
301             case AF_INET:
302                 sprintf(addrstr,"%08lX",(long)addr->sin.sin_addr.s_addr);
303                 port=addr->sin.sin_port;
304                 addrfam=NULL;
305                 break;
306 #ifdef CONFIG_IPV6
307             case AF_INET6: {
308                 int i;
309                 for (i=0; i<16; i++)
310                     sprintf(addrstr+i*2,"%02X",addr->sin6.sin6_addr.s6_addr[i]);
311                 port=addr->sin6.sin6_port;
312                 addrfam="6";
313                 break;
314             }
315 #endif /*CONFIG_IPV6*/
316             default:
317                 fatal("udp (%s:%d): unsupported address family for authbind",
318                       cc->loc.file,cc->loc.line);
319             }
320             sprintf(portstr,"%04X",port);
321             argv[0]=uc->authbind;
322             argv[1]=addrstr;
323             argv[2]=portstr;
324             argv[3]=(char*)addrfam;
325             argv[4]=NULL;
326             dup2(us->fd,0);
327             execvp(uc->authbind,argv);
328             _exit(255);
329         }
330         while (waitpid(c,&status,0)==-1) {
331             if (errno==EINTR) continue;
332             FAIL("waitpid for authbind");
333         }
334         if (status) {
335             if (WIFEXITED(status) && WEXITSTATUS(status)<127) {
336                 int es=WEXITSTATUS(status);
337                 lg_perror(FAIL_LG,es,
338                           "%s exited with error exit status %d;"
339                           " indicates error",desc,es);
340             } else {
341                 lg_exitstatus(FAIL_LG,status,desc);
342             }
343             goto failed;
344         }
345     } else {
346         if (bind(us->fd, &addr->sa, iaddr_socklen(addr))!=0)
347             FAIL("bind (%s)",iaddr_to_string(addr));
348     }
349
350     bool_t ok=record_socket_gotaddr(uc,us,failmsgclass);
351     if (!ok) goto failed;
352
353     return True;
354
355 failed:
356     udp_destroy_socket(uc,us);
357     return False;
358 }
359
360 #undef FAIL
361
362 void udp_socks_register(struct udpcommon *uc, struct udpsocks *socks,
363                         const char *desc)
364 {
365     socks->uc=uc;
366     socks->desc=desc;
367     socks->interest=
368         register_for_poll(socks,udp_socks_beforepoll,udp_socks_afterpoll,"udp");
369 }
370
371 void udp_socks_deregister(struct udpcommon *uc, struct udpsocks *socks)
372 {
373     socks->uc=uc;
374     deregister_for_poll(socks->interest);
375 }
376
377 void udp_socks_childpersist(struct udpcommon *uc, struct udpsocks *socks)
378 {
379     int i;
380     for (i=0; i<socks->n_socks; i++)
381         udp_destroy_socket(uc,&socks->socks[i]);
382 }
383
384 static void udp_childpersist_hook(void *sst, uint32_t new_phase)
385 {
386     struct udp *st=sst;
387     udp_socks_childpersist(&st->uc,&st->socks);
388 }
389
390 static void udp_phase_hook(void *sst, uint32_t new_phase)
391 {
392     struct udp *st=sst;
393     struct udpsocks *socks=&st->socks;
394     struct udpcommon *uc=&st->uc;
395     int i;
396     for (i=0; i<socks->n_socks; i++)
397         udp_make_socket(uc,&socks->socks[i],M_FATAL);
398
399     udp_socks_register(uc,socks, uc->use_proxy ? "proxy" : "socket");
400
401     add_hook(PHASE_CHILDPERSIST,udp_childpersist_hook,st);
402 }
403
404 static list_t *udp_apply(closure_t *self, struct cloc loc, dict_t *context,
405                          list_t *args)
406 {
407     struct udp *st;
408     list_t *caddrl;
409     list_t *l;
410     uint32_t a;
411     int i;
412
413     COMM_APPLY(st,&st->uc.cc,udp_,"udp",loc);
414     COMM_APPLY_STANDARD(st,&st->uc.cc,"udp",args);
415     UDP_APPLY_STANDARD(st,&st->uc,"udp");
416
417     struct udpcommon *uc=&st->uc;
418     struct udpsocks *socks=&st->socks;
419     struct commcommon *cc=&uc->cc;
420
421     union iaddr defaultaddrs[] = {
422 #ifdef CONFIG_IPV6
423         { .sin6 = { .sin6_family=AF_INET6,
424                     .sin6_port=htons(uc->port),
425                     .sin6_addr=IN6ADDR_ANY_INIT } },
426 #endif
427         { .sin = { .sin_family=AF_INET,
428                    .sin_port=htons(uc->port),
429                    .sin_addr= { .s_addr=INADDR_ANY } } }
430     };
431
432     caddrl=dict_lookup(d,"address");
433     socks->n_socks=caddrl ? list_length(caddrl) : (int)ARRAY_SIZE(defaultaddrs);
434     if (socks->n_socks<=0 || socks->n_socks>UDP_MAX_SOCKETS)
435         cfgfatal(cc->loc,"udp","`address' must be 1..%d addresses",
436                  UDP_MAX_SOCKETS);
437
438     for (i=0; i<socks->n_socks; i++) {
439         struct udpsock *us=&socks->socks[i];
440         if (!list_length(caddrl)) {
441             us->addr=defaultaddrs[i];
442         } else {
443             string_item_to_iaddr(list_elem(caddrl,i),uc->port,&us->addr,"udp");
444         }
445         us->fd=-1;
446     }
447
448     l=dict_lookup(d,"proxy");
449     if (l) {
450         uc->use_proxy=True;
451         uc->proxy.sa.sa_family=AF_INET;
452         item=list_elem(l,0);
453         if (!item || item->type!=t_string) {
454             cfgfatal(cc->loc,"udp","proxy must supply ""addr"",port\n");
455         }
456         a=string_item_to_ipaddr(item,"proxy");
457         uc->proxy.sin.sin_addr.s_addr=htonl(a);
458         item=list_elem(l,1);
459         if (!item || item->type!=t_number) {
460             cfgfatal(cc->loc,"udp","proxy must supply ""addr"",port\n");
461         }
462         uc->proxy.sin.sin_port=htons(item->data.number);
463     }
464
465     update_max_start_pad(&comm_max_start_pad, uc->use_proxy ? 8 : 0);
466
467     add_hook(PHASE_GETRESOURCES,udp_phase_hook,st);
468
469     return new_closure(&cc->cl);
470 }
471
472 void udp_module(dict_t *dict)
473 {
474     add_closure(dict,"udp",udp_apply);
475 }