chiark / gitweb /
c83e618fb6ca91876dcb1307c2bac516ba35a06a
[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 #include "magic.h"
25
26 static beforepoll_fn udp_beforepoll;
27 static afterpoll_fn udp_afterpoll;
28 static comm_request_notify_fn request_notify;
29 static comm_release_notify_fn release_notify;
30 static comm_sendmsg_fn udp_sendmsg;
31
32 struct notify_list {
33     comm_notify_fn *fn;
34     void *state;
35     struct notify_list *next;
36 };
37
38 struct udp {
39     closure_t cl;
40     struct comm_if ops;
41     struct cloc loc;
42     uint32_t addr;
43     uint16_t port;
44     int fd;
45     string_t authbind;
46     struct buffer_if *rbuf;
47     struct notify_list *notify;
48     bool_t use_proxy;
49     struct sockaddr_in proxy;
50 };
51
52 static const char *saddr_to_string(const struct sockaddr_in *sin) {
53     static char bufs[2][100];
54     static int b;
55
56     b ^= 1;
57     snprintf(bufs[b], sizeof(bufs[b]), "[%s]:%d",
58              inet_ntoa(sin->sin_addr),
59              ntohs(sin->sin_port));
60     return bufs[b];
61 }
62
63 static const char *addr_to_string(void *commst, const struct comm_addr *ca) {
64     struct udp *st=commst;
65     static char sbuf[100];
66
67     struct sockaddr_in la;
68     la.sin_addr.s_addr=htonl(st->addr);
69     la.sin_port=htons(st->port);
70
71     snprintf(sbuf, sizeof(sbuf), "udp:%s-%s",
72              saddr_to_string(&la), saddr_to_string(&ca->sin));
73     return sbuf;
74 }
75
76 static int udp_beforepoll(void *state, struct pollfd *fds, int *nfds_io,
77                           int *timeout_io)
78 {
79     struct udp *st=state;
80     if (*nfds_io<1) {
81         *nfds_io=1;
82         return ERANGE;
83     }
84     *nfds_io=1;
85     fds->fd=st->fd;
86     fds->events=POLLIN;
87     return 0;
88 }
89
90 static void udp_afterpoll(void *state, struct pollfd *fds, int nfds)
91 {
92     struct udp *st=state;
93     struct sockaddr_in from;
94     socklen_t fromlen;
95     struct notify_list *n;
96     bool_t done;
97     int rv;
98
99     if (nfds && (fds->revents & POLLIN)) {
100         do {
101             FILLZERO(from);
102             fromlen=sizeof(from);
103             BUF_ASSERT_FREE(st->rbuf);
104             BUF_ALLOC(st->rbuf,"udp_afterpoll");
105             rv=recvfrom(st->fd, st->rbuf->start, st->rbuf->len, 0,
106                         (struct sockaddr *)&from, &fromlen);
107             if (rv>0) {
108                 st->rbuf->size=rv;
109                 if (st->use_proxy) {
110                     /* Check that the packet came from our poxy server;
111                        we shouldn't be contacted directly by anybody else
112                        (since they can trivially forge source addresses) */
113                     if (memcmp(&from.sin_addr,&st->proxy.sin_addr,4)!=0 ||
114                         memcmp(&from.sin_port,&st->proxy.sin_port,2)!=0) {
115                         Message(M_INFO,"udp: received packet that's not "
116                                 "from the proxy\n");
117                         BUF_FREE(st->rbuf);
118                         continue;
119                     }
120                     memcpy(&from.sin_addr,buf_unprepend(st->rbuf,4),4);
121                     buf_unprepend(st->rbuf,2);
122                     memcpy(&from.sin_port,buf_unprepend(st->rbuf,2),2);
123                 }
124                 done=False;
125                 for (n=st->notify; n; n=n->next) {
126                     struct comm_addr ca;
127                     FILLZERO(ca);
128                     ca.comm=&st->ops;
129                     ca.sin=from;
130                     if (n->fn(n->state, st->rbuf, &ca)) {
131                         done=True;
132                         break;
133                     }
134                 }
135                 if (!done) {
136                     uint32_t msgtype;
137                     if (st->rbuf->size>12 /* prevents traffic amplification */
138                         && ((msgtype=get_uint32(st->rbuf->start+8))
139                             != LABEL_NAK)) {
140                         uint32_t source,dest;
141                         /* Manufacture and send NAK packet */
142                         source=get_uint32(st->rbuf->start); /* Us */
143                         dest=get_uint32(st->rbuf->start+4); /* Them */
144                         Message(M_INFO,"udp (port %d, peer %s):"
145                                 " %08"PRIx32"<-%08"PRIx32": %08"PRIx32":"
146                                 " unwanted/incorrect, sending NAK\n",
147                                 st->port, saddr_to_string(&from),
148                                 dest, source, msgtype);
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,LABEL_NAK);
153                         sendto(st->fd, st->rbuf->start, st->rbuf->size, 0,
154                                (struct sockaddr *)&from, sizeof(from));
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 notify_list *n;
170     
171     n=safe_malloc(sizeof(*n),"request_notify");
172     n->fn=fn;
173     n->state=nst;
174     n->next=st->notify;
175     st->notify=n;
176 }
177
178 static void release_notify(void *commst, void *nst, comm_notify_fn *fn)
179 {
180     struct udp *st=commst;
181     struct notify_list *n, **p, *t;
182
183     /* XXX untested */
184     p=&st->notify;
185     for (n=st->notify; n; )
186     {
187         if (n->state==nst && n->fn==fn) {
188             t=n;
189             *p=n->next;
190             n=n->next;
191             free(t);
192         } else {
193             p=&n->next;
194             n=n->next;
195         }
196     }
197 }
198
199 static bool_t udp_sendmsg(void *commst, struct buffer_if *buf,
200                           const struct comm_addr *dest)
201 {
202     struct udp *st=commst;
203     uint8_t *sa;
204
205     if (st->use_proxy) {
206         sa=buf->start-8;
207         memcpy(sa,&dest->sin.sin_addr,4);
208         memset(sa+4,0,4);
209         memcpy(sa+6,&dest->sin.sin_port,2);
210         sendto(st->fd,sa,buf->size+8,0,(struct sockaddr *)&st->proxy,
211                sizeof(st->proxy));
212     } else {
213         sendto(st->fd, buf->start, buf->size, 0,
214                (struct sockaddr *)&dest->sin, sizeof(dest->sin));
215     }
216
217     return True;
218 }
219
220 static void udp_phase_hook(void *sst, uint32_t new_phase)
221 {
222     struct udp *st=sst;
223     struct sockaddr_in addr;
224
225     st->fd=socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
226     if (st->fd<0) {
227         fatal_perror("udp (%s:%d): socket",st->loc.file,st->loc.line);
228     }
229     if (fcntl(st->fd, F_SETFL, fcntl(st->fd, F_GETFL)|O_NONBLOCK)==-1) {
230         fatal_perror("udp (%s:%d): fcntl(set O_NONBLOCK)",
231                      st->loc.file,st->loc.line);
232     }
233     if (fcntl(st->fd, F_SETFD, FD_CLOEXEC)==-1) {
234         fatal_perror("udp (%s:%d): fcntl(set FD_CLOEXEC)",
235                      st->loc.file,st->loc.line);
236     }
237
238     FILLZERO(addr);
239     addr.sin_family=AF_INET;
240     addr.sin_addr.s_addr=htonl(st->addr);
241     addr.sin_port=htons(st->port);
242     if (st->authbind) {
243         pid_t c;
244         int status;
245
246         /* XXX this fork() and waitpid() business needs to be hidden
247            in some system-specific library functions. */
248         c=fork();
249         if (c==-1) {
250             fatal_perror("udp_phase_hook: fork() for authbind");
251         }
252         if (c==0) {
253             char *argv[4], addrstr[9], portstr[5];
254             sprintf(addrstr,"%08lX",(long)addr.sin_addr.s_addr);
255             sprintf(portstr,"%04X",addr.sin_port);
256             argv[0]=st->authbind;
257             argv[1]=addrstr;
258             argv[2]=portstr;
259             argv[3]=NULL;
260             dup2(st->fd,0);
261             execvp(st->authbind,argv);
262             _exit(255);
263         }
264         while (waitpid(c,&status,0)==-1) {
265             if (errno==EINTR) continue;
266             fatal_perror("udp (%s:%d): authbind",st->loc.file,st->loc.line);
267         }
268         if (WIFSIGNALED(status)) {
269             fatal("udp (%s:%d): authbind died on signal %d",st->loc.file,
270                   st->loc.line, WTERMSIG(status));
271         }
272         if (WIFEXITED(status) && WEXITSTATUS(status)!=0) {
273             fatal("udp (%s:%d): authbind died with status %d",st->loc.file,
274                   st->loc.line, WEXITSTATUS(status));
275         }
276     } else {
277         if (bind(st->fd, (struct sockaddr *)&addr, sizeof(addr))!=0) {
278             fatal_perror("udp (%s:%d): bind",st->loc.file,st->loc.line);
279         }
280     }
281
282     register_for_poll(st,udp_beforepoll,udp_afterpoll,1,"udp");
283 }
284
285 static list_t *udp_apply(closure_t *self, struct cloc loc, dict_t *context,
286                          list_t *args)
287 {
288     struct udp *st;
289     item_t *i,*j;
290     dict_t *d;
291     list_t *l;
292     uint32_t a;
293
294     st=safe_malloc(sizeof(*st),"udp_apply(st)");
295     st->loc=loc;
296     st->cl.description="udp";
297     st->cl.type=CL_COMM;
298     st->cl.apply=NULL;
299     st->cl.interface=&st->ops;
300     st->ops.st=st;
301     st->ops.min_start_pad=0;
302     st->ops.min_end_pad=0;
303     st->ops.request_notify=request_notify;
304     st->ops.release_notify=release_notify;
305     st->ops.sendmsg=udp_sendmsg;
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 }