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