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