chiark / gitweb /
a1d3b74f5b1b6d7d1963f9e38c8048622be7f844
[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 udp {
38     closure_t cl;
39     struct comm_if ops;
40     struct cloc loc;
41     uint32_t addr;
42     uint16_t port;
43     int fd;
44     string_t authbind;
45     struct buffer_if *rbuf;
46     struct notify_list *notify;
47     bool_t use_proxy;
48     struct sockaddr_in proxy;
49 };
50
51 static const char *saddr_to_string(const struct sockaddr_in *sin) {
52     static char bufs[2][100];
53     static int b;
54
55     b ^= 1;
56     snprintf(bufs[b], sizeof(bufs[b]), "[%s]:%d",
57              inet_ntoa(sin->sin_addr),
58              ntohs(sin->sin_port));
59     return bufs[b];
60 }
61
62 static const char *addr_to_string(void *commst, const struct comm_addr *ca) {
63     struct udp *st=commst;
64     static char sbuf[100];
65
66     struct sockaddr_in la;
67     la.sin_addr.s_addr=htonl(st->addr);
68     la.sin_port=htons(st->port);
69
70     snprintf(sbuf, sizeof(sbuf), "udp:%s-%s",
71              saddr_to_string(&la), saddr_to_string(&ca->priv.sin));
72     return sbuf;
73 }
74
75 static bool_t addr_construct(void *commst, struct comm_addr *ca,
76                              const struct sockaddr_in *sin) {
77     struct udp *st=commst;
78     FILLZERO(*ca);
79     ca->comm=&st->ops;
80     ca->priv.sin=*sin;
81     return True;
82 }
83
84 static int udp_beforepoll(void *state, struct pollfd *fds, int *nfds_io,
85                           int *timeout_io)
86 {
87     struct udp *st=state;
88     if (*nfds_io<1) {
89         *nfds_io=1;
90         return ERANGE;
91     }
92     *nfds_io=1;
93     fds->fd=st->fd;
94     fds->events=POLLIN;
95     return 0;
96 }
97
98 static void udp_afterpoll(void *state, struct pollfd *fds, int nfds)
99 {
100     struct udp *st=state;
101     struct sockaddr_in from;
102     socklen_t fromlen;
103     struct notify_list *n;
104     bool_t done;
105     int rv;
106
107     if (nfds && (fds->revents & POLLIN)) {
108         do {
109             FILLZERO(from);
110             fromlen=sizeof(from);
111             BUF_ASSERT_FREE(st->rbuf);
112             BUF_ALLOC(st->rbuf,"udp_afterpoll");
113             rv=recvfrom(st->fd, st->rbuf->start, st->rbuf->len, 0,
114                         (struct sockaddr *)&from, &fromlen);
115             if (rv>0) {
116                 st->rbuf->size=rv;
117                 if (st->use_proxy) {
118                     /* Check that the packet came from our poxy server;
119                        we shouldn't be contacted directly by anybody else
120                        (since they can trivially forge source addresses) */
121                     if (memcmp(&from.sin_addr,&st->proxy.sin_addr,4)!=0 ||
122                         memcmp(&from.sin_port,&st->proxy.sin_port,2)!=0) {
123                         Message(M_INFO,"udp: received packet that's not "
124                                 "from the proxy\n");
125                         BUF_FREE(st->rbuf);
126                         continue;
127                     }
128                     memcpy(&from.sin_addr,buf_unprepend(st->rbuf,4),4);
129                     buf_unprepend(st->rbuf,2);
130                     memcpy(&from.sin_port,buf_unprepend(st->rbuf,2),2);
131                 }
132                 done=False;
133                 for (n=st->notify; n; n=n->next) {
134                     struct comm_addr ca;
135                     FILLZERO(ca);
136                     ca.comm=&st->ops;
137                     ca.priv.sin=from;
138                     if (n->fn(n->state, st->rbuf, &ca)) {
139                         done=True;
140                         break;
141                     }
142                 }
143                 if (!done) {
144                     uint32_t source,dest;
145                     /* Manufacture and send NAK packet */
146                     source=get_uint32(st->rbuf->start); /* Us */
147                     dest=get_uint32(st->rbuf->start+4); /* Them */
148                     Message(M_INFO,"udp (port %d): sending NAK\n",st->port);
149                     buffer_init(st->rbuf,0);
150                     buf_append_uint32(st->rbuf,dest);
151                     buf_append_uint32(st->rbuf,source);
152                     buf_append_uint32(st->rbuf,0); /* NAK is msg type 0 */
153                     sendto(st->fd, st->rbuf->start, st->rbuf->size, 0,
154                            (struct sockaddr *)&from, sizeof(from));
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->start-8;
206         memcpy(sa,&dest->priv.sin.sin_addr,4);
207         memset(sa+4,0,4);
208         memcpy(sa+6,&dest->priv.sin.sin_port,2);
209         sendto(st->fd,sa,buf->size+8,0,(struct sockaddr *)&st->proxy,
210                sizeof(st->proxy));
211     } else {
212         sendto(st->fd, buf->start, buf->size, 0,
213                (struct sockaddr *)&dest->priv.sin, sizeof(dest->priv.sin));
214     }
215
216     return True;
217 }
218
219 static void udp_phase_hook(void *sst, uint32_t new_phase)
220 {
221     struct udp *st=sst;
222     struct sockaddr_in addr;
223
224     st->fd=socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
225     if (st->fd<0) {
226         fatal_perror("udp (%s:%d): socket",st->loc.file,st->loc.line);
227     }
228     if (fcntl(st->fd, F_SETFL, fcntl(st->fd, F_GETFL)|O_NONBLOCK)==-1) {
229         fatal_perror("udp (%s:%d): fcntl(set O_NONBLOCK)",
230                      st->loc.file,st->loc.line);
231     }
232     if (fcntl(st->fd, F_SETFD, FD_CLOEXEC)==-1) {
233         fatal_perror("udp (%s:%d): fcntl(set FD_CLOEXEC)",
234                      st->loc.file,st->loc.line);
235     }
236
237     FILLZERO(addr);
238     addr.sin_family=AF_INET;
239     addr.sin_addr.s_addr=htonl(st->addr);
240     addr.sin_port=htons(st->port);
241     if (st->authbind) {
242         pid_t c;
243         int status;
244
245         /* XXX this fork() and waitpid() business needs to be hidden
246            in some system-specific library functions. */
247         c=fork();
248         if (c==-1) {
249             fatal_perror("udp_phase_hook: fork() for authbind");
250         }
251         if (c==0) {
252             char *argv[4], addrstr[9], portstr[5];
253             sprintf(addrstr,"%08lX",(long)st->addr);
254             sprintf(portstr,"%04X",st->port);
255             argv[0]=st->authbind;
256             argv[1]=addrstr;
257             argv[2]=portstr;
258             argv[3]=NULL;
259             dup2(st->fd,0);
260             execvp(st->authbind,argv);
261             _exit(255);
262         }
263         while (waitpid(c,&status,0)==-1) {
264             if (errno==EINTR) continue;
265             fatal_perror("udp (%s:%d): authbind",st->loc.file,st->loc.line);
266         }
267         if (WIFSIGNALED(status)) {
268             fatal("udp (%s:%d): authbind died on signal %d",st->loc.file,
269                   st->loc.line, WTERMSIG(status));
270         }
271         if (WIFEXITED(status) && WEXITSTATUS(status)!=0) {
272             fatal("udp (%s:%d): authbind died with status %d",st->loc.file,
273                   st->loc.line, WEXITSTATUS(status));
274         }
275     } else {
276         if (bind(st->fd, (struct sockaddr *)&addr, sizeof(addr))!=0) {
277             fatal_perror("udp (%s:%d): bind",st->loc.file,st->loc.line);
278         }
279     }
280
281     register_for_poll(st,udp_beforepoll,udp_afterpoll,1,"udp");
282 }
283
284 static list_t *udp_apply(closure_t *self, struct cloc loc, dict_t *context,
285                          list_t *args)
286 {
287     struct udp *st;
288     item_t *i,*j;
289     dict_t *d;
290     list_t *l;
291     uint32_t a;
292
293     st=safe_malloc(sizeof(*st),"udp_apply(st)");
294     st->loc=loc;
295     st->cl.description="udp";
296     st->cl.type=CL_COMM;
297     st->cl.apply=NULL;
298     st->cl.interface=&st->ops;
299     st->ops.st=st;
300     st->ops.min_start_pad=0;
301     st->ops.min_end_pad=0;
302     st->ops.request_notify=request_notify;
303     st->ops.release_notify=release_notify;
304     st->ops.sendmsg=udp_sendmsg;
305     st->ops.addr_construct=addr_construct;
306     st->ops.addr_to_string=addr_to_string;
307     st->port=0;
308     st->use_proxy=False;
309
310     i=list_elem(args,0);
311     if (!i || i->type!=t_dict) {
312         cfgfatal(st->loc,"udp","first argument must be a dictionary\n");
313     }
314     d=i->data.dict;
315
316     j=dict_find_item(d,"address",False,"udp",st->loc);
317     st->addr=j?string_item_to_ipaddr(j, "udp"):INADDR_ANY;
318     st->port=dict_read_number(d,"port",True,"udp",st->loc,0);
319     st->rbuf=find_cl_if(d,"buffer",CL_BUFFER,True,"udp",st->loc);
320     st->authbind=dict_read_string(d,"authbind",False,"udp",st->loc);
321     l=dict_lookup(d,"proxy");
322     if (l) {
323         st->use_proxy=True;
324         FILLZERO(st->proxy);
325         st->proxy.sin_family=AF_INET;
326         i=list_elem(l,0);
327         if (!i || i->type!=t_string) {
328             cfgfatal(st->loc,"udp","proxy must supply ""addr"",port\n");
329         }
330         a=string_item_to_ipaddr(i,"proxy");
331         st->proxy.sin_addr.s_addr=htonl(a);
332         i=list_elem(l,1);
333         if (!i || i->type!=t_number) {
334             cfgfatal(st->loc,"udp","proxy must supply ""addr"",port\n");
335         }
336         st->proxy.sin_port=htons(i->data.number);
337         st->ops.min_start_pad=8;
338     }
339
340     add_hook(PHASE_GETRESOURCES,udp_phase_hook,st);
341
342     return new_closure(&st->cl);
343 }
344
345 void udp_module(dict_t *dict)
346 {
347     add_closure(dict,"udp",udp_apply);
348 }