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