chiark / gitweb /
WIP dns transport packets etc.
[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 "unaligned.h"
23 #include "ipaddr.h"
24
25 static beforepoll_fn udp_beforepoll;
26 static afterpoll_fn udp_afterpoll;
27 static comm_request_notify_fn request_notify;
28 static comm_release_notify_fn release_notify;
29 static comm_sendmsg_fn udp_sendmsg;
30
31 struct notify_list {
32     comm_notify_fn *fn;
33     void *state;
34     struct notify_list *next;
35 };
36
37 struct peer_config {
38     string_t address; /* DNS name for bootstrapping, optional */
39     int remoteport; /* Port for bootstrapping, optional */
40 };
41
42 struct udp {
43     closure_t cl;
44     struct comm_if ops;
45     struct cloc loc;
46     uint32_t addr;
47     uint16_t port;
48     int fd;
49     string_t authbind;
50     struct buffer_if *rbuf;
51     struct notify_list *notify;
52     struct resolver_if *resolver;
53     bool_t use_proxy;
54     struct sockaddr_in proxy;
55 };
56
57 static const char *saddr_to_string(const struct sockaddr_in *sin) {
58     static char bufs[2][100];
59     static int b;
60
61     b ^= 1;
62     snprintf(bufs[b], sizeof(bufs[b]), "[%s]:%d",
63              inet_ntoa(sin->sin_addr),
64              ntohs(sin->sin_port));
65     return bufs[b];
66 }
67
68 static const char *addr_to_string(void *commst, const struct comm_addr *ca) {
69     struct udp *st=commst;
70     static char sbuf[100];
71
72     struct sockaddr_in la;
73     la.sin_addr.s_addr=htonl(st->addr);
74     la.sin_port=htons(st->port);
75
76     snprintf(sbuf, sizeof(sbuf), "udp:%s-%s",
77              saddr_to_string(&la), saddr_to_string(&ca->priv.sin));
78     return sbuf;
79 }
80
81 struct peer_addr_cst {
82     struct udp *udp;
83     struct peer_config *cfg;
84     comm_peer_addr_answer_fn *cb;
85     void *cst;
86 };
87
88 static void *peer_addr_config(void *commst, dict_t *dict, struct cloc loc,
89                               cstring_t desc)
90 {
91     struct peer_config *cfg;
92     cfg=safe_malloc(sizeof(*cfg),"peer addr config");
93     cfg->address=dict_read_string(dict, "address",False,desc,loc);
94     if (cfg->address)
95         cfg->remoteport=dict_read_number(dict,"port",True,desc,loc,0);
96     else cfg->remoteport=0;
97     if (cfg->address)
98         return cfg;
99     free(cfg);
100     return NULL;
101 }
102
103 static void peer_resolve_callback(void *sst, struct in_addr *address)
104 {
105     struct peer_addr_cst *pacst=sst;
106     struct udp *st=pacst->udp;
107     struct peer_config *cfg=pacst->cfg;
108     struct comm_addr ca;
109     if (address) {
110         FILLZERO(ca);
111         ca.comm=&st->ops;
112         ca.priv.sin.sin_family=AF_INET;
113         ca.priv.sin.sin_port=htons(cfg->remoteport);
114         ca.priv.sin.sin_addr=*address;
115         pacst->cb(pacst->cst,&ca);
116     } else {
117         pacst->cb(pacst->cst,0);
118     }
119     free(pacst);
120 }
121
122 static bool_t peer_addr_request(void *commst, void *from_peer_config,
123                                 comm_peer_addr_answer_fn *cb, void *cst)
124 {
125     struct udp *st=commst;
126     struct peer_config *cfg=from_peer_config;
127     struct peer_addr_cst *pacst;
128     pacst=safe_malloc(sizeof(*pacst),"udp peer addr request cst");
129     pacst->udp=st;
130     pacst->cfg=cfg;
131     pacst->cb=cb;
132     pacst->cst=cst;
133     bool_t ok=st->resolver->request(st->resolver->st,cfg->address,
134                                     peer_resolve_callback,pacst);
135     if (!ok)
136         free(pacst);
137     return ok;
138 }
139
140 static int udp_beforepoll(void *state, struct pollfd *fds, int *nfds_io,
141                           int *timeout_io)
142 {
143     struct udp *st=state;
144     if (*nfds_io<1) {
145         *nfds_io=1;
146         return ERANGE;
147     }
148     *nfds_io=1;
149     fds->fd=st->fd;
150     fds->events=POLLIN;
151     return 0;
152 }
153
154 static void udp_afterpoll(void *state, struct pollfd *fds, int nfds)
155 {
156     struct udp *st=state;
157     struct sockaddr_in from;
158     socklen_t fromlen;
159     struct notify_list *n;
160     bool_t done;
161     int rv;
162
163     if (nfds && (fds->revents & POLLIN)) {
164         do {
165             FILLZERO(from);
166             fromlen=sizeof(from);
167             BUF_ASSERT_FREE(st->rbuf);
168             BUF_ALLOC(st->rbuf,"udp_afterpoll");
169             rv=recvfrom(st->fd, st->rbuf->start, st->rbuf->len, 0,
170                         (struct sockaddr *)&from, &fromlen);
171             if (rv>0) {
172                 st->rbuf->size=rv;
173                 if (st->use_proxy) {
174                     /* Check that the packet came from our poxy server;
175                        we shouldn't be contacted directly by anybody else
176                        (since they can trivially forge source addresses) */
177                     if (memcmp(&from.sin_addr,&st->proxy.sin_addr,4)!=0 ||
178                         memcmp(&from.sin_port,&st->proxy.sin_port,2)!=0) {
179                         Message(M_INFO,"udp: received packet that's not "
180                                 "from the proxy\n");
181                         BUF_FREE(st->rbuf);
182                         continue;
183                     }
184                     memcpy(&from.sin_addr,buf_unprepend(st->rbuf,4),4);
185                     buf_unprepend(st->rbuf,2);
186                     memcpy(&from.sin_port,buf_unprepend(st->rbuf,2),2);
187                 }
188                 done=False;
189                 for (n=st->notify; n; n=n->next) {
190                     struct comm_addr ca;
191                     FILLZERO(ca);
192                     ca.comm=&st->ops;
193                     ca.priv.sin=from;
194                     if (n->fn(n->state, st->rbuf, &ca)) {
195                         done=True;
196                         break;
197                     }
198                 }
199                 if (!done) {
200                     uint32_t source,dest;
201                     /* Manufacture and send NAK packet */
202                     source=get_uint32(st->rbuf->start); /* Us */
203                     dest=get_uint32(st->rbuf->start+4); /* Them */
204                     Message(M_INFO,"udp (port %d): sending NAK\n",st->port);
205                     buffer_init(st->rbuf,0);
206                     buf_append_uint32(st->rbuf,dest);
207                     buf_append_uint32(st->rbuf,source);
208                     buf_append_uint32(st->rbuf,0); /* NAK is msg type 0 */
209                     sendto(st->fd, st->rbuf->start, st->rbuf->size, 0,
210                            (struct sockaddr *)&from, sizeof(from));
211                     BUF_FREE(st->rbuf);
212                 }
213                 BUF_ASSERT_FREE(st->rbuf);
214             } else {
215                 BUF_FREE(st->rbuf);
216             }
217         } while (rv>=0);
218     }
219 }
220
221 static void request_notify(void *commst, void *nst, comm_notify_fn *fn)
222 {
223     struct udp *st=commst;
224     struct notify_list *n;
225     
226     n=safe_malloc(sizeof(*n),"request_notify");
227     n->fn=fn;
228     n->state=nst;
229     n->next=st->notify;
230     st->notify=n;
231 }
232
233 static void release_notify(void *commst, void *nst, comm_notify_fn *fn)
234 {
235     struct udp *st=commst;
236     struct notify_list *n, **p, *t;
237
238     /* XXX untested */
239     p=&st->notify;
240     for (n=st->notify; n; )
241     {
242         if (n->state==nst && n->fn==fn) {
243             t=n;
244             *p=n->next;
245             n=n->next;
246             free(t);
247         } else {
248             p=&n->next;
249             n=n->next;
250         }
251     }
252 }
253
254 static bool_t udp_sendmsg(void *commst, struct buffer_if *buf,
255                           const struct comm_addr *dest)
256 {
257     struct udp *st=commst;
258     uint8_t *sa;
259
260     if (st->use_proxy) {
261         sa=buf->start-8;
262         memcpy(sa,&dest->priv.sin.sin_addr,4);
263         memset(sa+4,0,4);
264         memcpy(sa+6,&dest->priv.sin.sin_port,2);
265         sendto(st->fd,sa,buf->size+8,0,(struct sockaddr *)&st->proxy,
266                sizeof(st->proxy));
267     } else {
268         sendto(st->fd, buf->start, buf->size, 0,
269                (struct sockaddr *)&dest->priv.sin, sizeof(dest->priv.sin));
270     }
271
272     return True;
273 }
274
275 static void udp_phase_hook(void *sst, uint32_t new_phase)
276 {
277     struct udp *st=sst;
278     struct sockaddr_in addr;
279
280     st->fd=socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
281     if (st->fd<0) {
282         fatal_perror("udp (%s:%d): socket",st->loc.file,st->loc.line);
283     }
284     if (fcntl(st->fd, F_SETFL, fcntl(st->fd, F_GETFL)|O_NONBLOCK)==-1) {
285         fatal_perror("udp (%s:%d): fcntl(set O_NONBLOCK)",
286                      st->loc.file,st->loc.line);
287     }
288     if (fcntl(st->fd, F_SETFD, FD_CLOEXEC)==-1) {
289         fatal_perror("udp (%s:%d): fcntl(set FD_CLOEXEC)",
290                      st->loc.file,st->loc.line);
291     }
292
293     FILLZERO(addr);
294     addr.sin_family=AF_INET;
295     addr.sin_addr.s_addr=htonl(st->addr);
296     addr.sin_port=htons(st->port);
297     if (st->authbind) {
298         pid_t c;
299         int status;
300
301         /* XXX this fork() and waitpid() business needs to be hidden
302            in some system-specific library functions. */
303         c=fork();
304         if (c==-1) {
305             fatal_perror("udp_phase_hook: fork() for authbind");
306         }
307         if (c==0) {
308             char *argv[4], addrstr[9], portstr[5];
309             sprintf(addrstr,"%08lX",(long)st->addr);
310             sprintf(portstr,"%04X",st->port);
311             argv[0]=st->authbind;
312             argv[1]=addrstr;
313             argv[2]=portstr;
314             argv[3]=NULL;
315             dup2(st->fd,0);
316             execvp(st->authbind,argv);
317             _exit(255);
318         }
319         while (waitpid(c,&status,0)==-1) {
320             if (errno==EINTR) continue;
321             fatal_perror("udp (%s:%d): authbind",st->loc.file,st->loc.line);
322         }
323         if (WIFSIGNALED(status)) {
324             fatal("udp (%s:%d): authbind died on signal %d",st->loc.file,
325                   st->loc.line, WTERMSIG(status));
326         }
327         if (WIFEXITED(status) && WEXITSTATUS(status)!=0) {
328             fatal("udp (%s:%d): authbind died with status %d",st->loc.file,
329                   st->loc.line, WEXITSTATUS(status));
330         }
331     } else {
332         if (bind(st->fd, (struct sockaddr *)&addr, sizeof(addr))!=0) {
333             fatal_perror("udp (%s:%d): bind",st->loc.file,st->loc.line);
334         }
335     }
336
337     register_for_poll(st,udp_beforepoll,udp_afterpoll,1,"udp");
338 }
339
340 static list_t *udp_apply(closure_t *self, struct cloc loc, dict_t *context,
341                          list_t *args)
342 {
343     struct udp *st;
344     item_t *i,*j;
345     dict_t *d;
346     list_t *l;
347     uint32_t a;
348
349     st=safe_malloc(sizeof(*st),"udp_apply(st)");
350     st->loc=loc;
351     st->cl.description="udp";
352     st->cl.type=CL_COMM;
353     st->cl.apply=NULL;
354     st->cl.interface=&st->ops;
355     st->ops.st=st;
356     st->ops.min_start_pad=0;
357     st->ops.min_end_pad=0;
358     st->ops.request_notify=request_notify;
359     st->ops.release_notify=release_notify;
360     st->ops.sendmsg=udp_sendmsg;
361     st->ops.peer_addr_config=peer_addr_config;
362     st->ops.peer_addr_request=peer_addr_request;
363     st->ops.addr_to_string=addr_to_string;
364     st->port=0;
365     st->use_proxy=False;
366
367     i=list_elem(args,0);
368     if (!i || i->type!=t_dict) {
369         cfgfatal(st->loc,"udp","first argument must be a dictionary\n");
370     }
371     d=i->data.dict;
372
373     j=dict_find_item(d,"address",False,"udp",st->loc);
374     st->addr=j?string_item_to_ipaddr(j, "udp"):INADDR_ANY;
375     st->port=dict_read_number(d,"port",True,"udp",st->loc,0);
376     st->rbuf=find_cl_if(d,"buffer",CL_BUFFER,True,"udp",st->loc);
377     st->authbind=dict_read_string(d,"authbind",False,"udp",st->loc);
378     l=dict_lookup(d,"proxy");
379     if (l) {
380         st->use_proxy=True;
381         FILLZERO(st->proxy);
382         st->proxy.sin_family=AF_INET;
383         i=list_elem(l,0);
384         if (!i || i->type!=t_string) {
385             cfgfatal(st->loc,"udp","proxy must supply ""addr"",port\n");
386         }
387         a=string_item_to_ipaddr(i,"proxy");
388         st->proxy.sin_addr.s_addr=htonl(a);
389         i=list_elem(l,1);
390         if (!i || i->type!=t_number) {
391             cfgfatal(st->loc,"udp","proxy must supply ""addr"",port\n");
392         }
393         st->proxy.sin_port=htons(i->data.number);
394         st->ops.min_start_pad=8;
395     }
396     st->resolver=find_cl_if(d,"resolver",CL_RESOLVER,True,"comm",loc);
397
398     add_hook(PHASE_GETRESOURCES,udp_phase_hook,st);
399
400     return new_closure(&st->cl);
401 }
402
403 void udp_module(dict_t *dict)
404 {
405     add_closure(dict,"udp",udp_apply);
406 }