chiark / gitweb /
63851fe07598673d593f21195165cbe6897c82c7
[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 beforepoll_fn udp_beforepoll;
29 static afterpoll_fn udp_afterpoll;
30 static comm_sendmsg_fn udp_sendmsg;
31
32 #define UDP_MAX_SOCKETS 3 /* 2 ought to do really */
33
34 struct udpsock {
35     union iaddr addr;
36     int fd;
37 };
38
39 struct udp {
40     struct commcommon cc;
41     int n_socks;
42     struct udpsock socks[UDP_MAX_SOCKETS];
43     string_t authbind;
44     bool_t use_proxy;
45     union iaddr proxy;
46 };
47
48 /*
49  * Re comm_addr.ix: This field allows us to note in the comm_addr
50  * which socket an incoming packet was received on.  This is required
51  * for conveniently logging the actual source of a packet.  But the ix
52  * does not formally form part of the address: it is not used when
53  * sending, nor when comparing two comm_addrs.
54  *
55  * The special value -1 means that the comm_addr was constructed by
56  * another module in secnet (eg the resolver), rather than being a
57  * description of the source of an incoming packet.
58  */
59
60 static const char *udp_addr_to_string(void *commst, const struct comm_addr *ca)
61 {
62     struct udp *st=commst;
63     struct udp *socks=st; /* for now */
64     static char sbuf[100];
65     int ix=ca->ix>=0 ? ca->ix : 0;
66
67     assert(ix>=0 && ix<socks->n_socks);
68     snprintf(sbuf, sizeof(sbuf), "udp:%s%s-%s",
69              iaddr_to_string(&socks->socks[ix].addr),
70              ca->ix<0 ? "&" : "",
71              iaddr_to_string(&ca->ia));
72     return sbuf;
73 }
74
75 static int udp_beforepoll(void *state, struct pollfd *fds, int *nfds_io,
76                           int *timeout_io)
77 {
78     int i;
79     struct udp *st=state;
80     struct udp *socks=st; /* for now */
81     BEFOREPOLL_WANT_FDS(socks->n_socks);
82     for (i=0; i<socks->n_socks; i++) {
83         fds[i].fd=socks->socks[i].fd;
84         fds[i].events=POLLIN;
85     }
86     return 0;
87 }
88
89 static void udp_afterpoll(void *state, struct pollfd *fds, int nfds)
90 {
91     struct udp *st=state;
92     struct commcommon *cc=&st->cc;
93     struct udp *socks=st; /* for now */
94     struct udp *uc=st; /* for now */
95     union iaddr from;
96     socklen_t fromlen;
97     bool_t done;
98     int rv;
99     int i;
100
101     for (i=0; i<st->n_socks; i++) {
102         if (i>=nfds) continue;
103         if (!(fds[i].revents & POLLIN)) continue;
104         assert(fds[i].fd == socks->socks[i].fd);
105         int fd=socks->socks[i].fd;
106         do {
107             fromlen=sizeof(from);
108             BUF_ASSERT_FREE(cc->rbuf);
109             BUF_ALLOC(cc->rbuf,"udp_afterpoll");
110             buffer_init(cc->rbuf,calculate_max_start_pad());
111             rv=recvfrom(fd, cc->rbuf->start,
112                         buf_remaining_space(cc->rbuf),
113                         0, &from.sa, &fromlen);
114             if (rv>0) {
115                 cc->rbuf->size=rv;
116                 if (uc->use_proxy) {
117                     /* Check that the packet came from our poxy server;
118                        we shouldn't be contacted directly by anybody else
119                        (since they can trivially forge source addresses) */
120                     if (!iaddr_equal(&from,&uc->proxy)) {
121                         Message(M_INFO,"udp: received packet that's not "
122                                 "from the proxy\n");
123                         BUF_FREE(cc->rbuf);
124                         continue;
125                     }
126                     /* proxy protocol supports ipv4 transport only */
127                     from.sa.sa_family=AF_INET;
128                     BUF_GET_BYTES(unprepend,cc->rbuf,&from.sin.sin_addr,4);
129                     buf_unprepend(cc->rbuf,2);
130                     BUF_GET_BYTES(unprepend,cc->rbuf,&from.sin.sin_port,2);
131                 }
132                 struct comm_addr ca;
133                 ca.comm=&cc->ops;
134                 ca.ia=from;
135                 ca.ix=i;
136                 done=comm_notify(&cc->notify, cc->rbuf, &ca);
137                 if (!done) {
138                     uint32_t msgtype;
139                     if (cc->rbuf->size>12 /* prevents traffic amplification */
140                         && ((msgtype=get_uint32(cc->rbuf->start+8))
141                             != LABEL_NAK)) {
142                         uint32_t source,dest;
143                         /* Manufacture and send NAK packet */
144                         source=get_uint32(cc->rbuf->start); /* Us */
145                         dest=get_uint32(cc->rbuf->start+4); /* Them */
146                         send_nak(&ca,source,dest,msgtype,cc->rbuf,"unwanted");
147                     }
148                     BUF_FREE(cc->rbuf);
149                 }
150                 BUF_ASSERT_FREE(cc->rbuf);
151             } else {
152                 BUF_FREE(cc->rbuf);
153             }
154         } while (rv>=0);
155     }
156 }
157
158 static bool_t udp_sendmsg(void *commst, struct buffer_if *buf,
159                           const struct comm_addr *dest)
160 {
161     struct udp *st=commst;
162     struct udp *uc=st; /* for now */
163     struct udp *socks=st; /* for now */
164     uint8_t *sa;
165
166     if (uc->use_proxy) {
167         sa=buf_prepend(buf,8);
168         if (dest->ia.sa.sa_family != AF_INET) {
169             Message(M_INFO,
170                "udp: proxy means dropping outgoing non-IPv4 packet to %s\n",
171                     iaddr_to_string(&dest->ia));
172             return False;
173         }
174         memcpy(sa,&dest->ia.sin.sin_addr,4);
175         memset(sa+4,0,4);
176         memcpy(sa+6,&dest->ia.sin.sin_port,2);
177         sendto(socks->socks[0].fd,sa,buf->size+8,0,&uc->proxy.sa,
178                iaddr_socklen(&uc->proxy));
179         buf_unprepend(buf,8);
180     } else {
181         int i,r;
182         bool_t allunsupported=True;
183         for (i=0; i<socks->n_socks; i++) {
184             if (dest->ia.sa.sa_family != socks->socks[i].addr.sa.sa_family)
185                 /* no point even trying */
186                 continue;
187             r=sendto(socks->socks[i].fd, buf->start, buf->size, 0,
188                      &dest->ia.sa, iaddr_socklen(&dest->ia));
189             if (r>=0) return True;
190             if (!(errno==EAFNOSUPPORT || errno==ENETUNREACH))
191                 /* who knows what that error means? */
192                 allunsupported=False;
193         }
194         return !allunsupported; /* see doc for comm_sendmsg_fn in secnet.h */
195     }
196
197     return True;
198 }
199
200 static void udp_make_socket(struct udp *st, struct udpsock *us)
201 {
202     const union iaddr *addr=&us->addr;
203     struct commcommon *cc=&st->cc; /* for now */
204     struct udp *uc=st; /* for now */
205     us->fd=socket(addr->sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
206     if (us->fd<0) {
207         fatal_perror("udp (%s:%d): socket",cc->loc.file,cc->loc.line);
208     }
209     if (fcntl(us->fd, F_SETFL, fcntl(us->fd, F_GETFL)|O_NONBLOCK)==-1) {
210         fatal_perror("udp (%s:%d): fcntl(set O_NONBLOCK)",
211                      cc->loc.file,cc->loc.line);
212     }
213     setcloexec(us->fd);
214 #ifdef CONFIG_IPV6
215     if (addr->sa.sa_family==AF_INET6) {
216         int r;
217         int optval=1;
218         socklen_t optlen=sizeof(optval);
219         r=setsockopt(us->fd,IPPROTO_IPV6,IPV6_V6ONLY,&optval,optlen);
220         if (r) fatal_perror("udp (%s:%d): setsockopt(,IPV6_V6ONLY,&1,)",
221                             cc->loc.file,cc->loc.line);
222     }
223 #endif
224
225     if (uc->authbind) {
226         pid_t c;
227         int status;
228
229         /* XXX this fork() and waitpid() business needs to be hidden
230            in some system-specific library functions. */
231         c=fork();
232         if (c==-1) {
233             fatal_perror("udp_phase_hook: fork() for authbind");
234         }
235         if (c==0) {
236             char *argv[5], addrstr[33], portstr[5];
237             const char *addrfam;
238             int port;
239             switch (addr->sa.sa_family) {
240             case AF_INET:
241                 sprintf(addrstr,"%08lX",(long)addr->sin.sin_addr.s_addr);
242                 port=addr->sin.sin_port;
243                 addrfam=NULL;
244                 break;
245 #ifdef CONFIG_IPV6
246             case AF_INET6: {
247                 int i;
248                 for (i=0; i<16; i++)
249                     sprintf(addrstr+i*2,"%02X",addr->sin6.sin6_addr.s6_addr[i]);
250                 port=addr->sin6.sin6_port;
251                 addrfam="6";
252                 break;
253             }
254 #endif /*CONFIG_IPV6*/
255             default:
256                 fatal("udp (%s:%d): unsupported address family for authbind",
257                       cc->loc.file,cc->loc.line);
258             }
259             sprintf(portstr,"%04X",port);
260             argv[0]=uc->authbind;
261             argv[1]=addrstr;
262             argv[2]=portstr;
263             argv[3]=(char*)addrfam;
264             argv[4]=NULL;
265             dup2(us->fd,0);
266             execvp(uc->authbind,argv);
267             _exit(255);
268         }
269         while (waitpid(c,&status,0)==-1) {
270             if (errno==EINTR) continue;
271             fatal_perror("udp (%s:%d): authbind",cc->loc.file,cc->loc.line);
272         }
273         if (WIFSIGNALED(status)) {
274             fatal("udp (%s:%d): authbind died on signal %d",cc->loc.file,
275                   cc->loc.line, WTERMSIG(status));
276         }
277         if (WIFEXITED(status) && WEXITSTATUS(status)!=0) {
278             fatal("udp (%s:%d): authbind died with status %d",cc->loc.file,
279                   cc->loc.line, WEXITSTATUS(status));
280         }
281     } else {
282         if (bind(us->fd, &addr->sa, iaddr_socklen(addr))!=0) {
283             fatal_perror("udp (%s:%d): bind",cc->loc.file,cc->loc.line);
284         }
285     }
286 }
287
288 static void udp_phase_hook(void *sst, uint32_t new_phase)
289 {
290     struct udp *st=sst;
291     struct udp *socks=st; /* for now */
292     int i;
293     for (i=0; i<socks->n_socks; i++)
294         udp_make_socket(st,&socks->socks[i]);
295
296     register_for_poll(st,udp_beforepoll,udp_afterpoll,"udp");
297 }
298
299 static list_t *udp_apply(closure_t *self, struct cloc loc, dict_t *context,
300                          list_t *args)
301 {
302     struct udp *st;
303     list_t *caddrl;
304     list_t *l;
305     uint32_t a;
306     int i;
307
308     COMM_APPLY(st,&st->cc,udp_,"udp",loc);
309     struct commcommon *cc=&st->cc; /* for now */
310     struct udp *uc=st; /* for now */
311     struct udp *socks=st; /* for now */
312
313     uc->use_proxy=False;
314
315     COMM_APPLY_STANDARD(st,&st->cc,"udp",args);
316
317     int port=dict_read_number(d,"port",True,"udp",cc->loc,0);
318
319     union iaddr defaultaddrs[] = {
320 #ifdef CONFIG_IPV6
321         { .sin6 = { .sin6_family=AF_INET6,
322                     .sin6_port=htons(port),
323                     .sin6_addr=IN6ADDR_ANY_INIT } },
324 #endif
325         { .sin = { .sin_family=AF_INET,
326                    .sin_port=htons(port),
327                    .sin_addr= { .s_addr=INADDR_ANY } } }
328     };
329
330     caddrl=dict_lookup(d,"address");
331     socks->n_socks=caddrl ? list_length(caddrl) : (int)ARRAY_SIZE(defaultaddrs);
332     if (socks->n_socks<=0 || socks->n_socks>UDP_MAX_SOCKETS)
333         cfgfatal(cc->loc,"udp","`address' must be 1..%d addresses",
334                  UDP_MAX_SOCKETS);
335
336     for (i=0; i<socks->n_socks; i++) {
337         struct udpsock *us=&socks->socks[i];
338         if (!list_length(caddrl)) {
339             us->addr=defaultaddrs[i];
340         } else {
341             string_item_to_iaddr(list_elem(caddrl,i),port,&us->addr,"udp");
342         }
343         us->fd=-1;
344     }
345
346     uc->authbind=dict_read_string(d,"authbind",False,"udp",cc->loc);
347     l=dict_lookup(d,"proxy");
348     if (l) {
349         uc->use_proxy=True;
350         uc->proxy.sa.sa_family=AF_INET;
351         item=list_elem(l,0);
352         if (!item || item->type!=t_string) {
353             cfgfatal(cc->loc,"udp","proxy must supply ""addr"",port\n");
354         }
355         a=string_item_to_ipaddr(item,"proxy");
356         uc->proxy.sin.sin_addr.s_addr=htonl(a);
357         item=list_elem(l,1);
358         if (!item || item->type!=t_number) {
359             cfgfatal(cc->loc,"udp","proxy must supply ""addr"",port\n");
360         }
361         uc->proxy.sin.sin_port=htons(item->data.number);
362     }
363
364     update_max_start_pad(&comm_max_start_pad, uc->use_proxy ? 8 : 0);
365
366     add_hook(PHASE_GETRESOURCES,udp_phase_hook,st);
367
368     return new_closure(&cc->cl);
369 }
370
371 void udp_module(dict_t *dict)
372 {
373     add_closure(dict,"udp",udp_apply);
374 }