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