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