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