chiark / gitweb /
90f8e9a36602b7cc6ff3fb72e7d7852e4e6f14ed
[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 notify_list {
34     comm_notify_fn *fn;
35     void *state;
36     struct notify_list *next;
37 };
38
39 struct udp {
40     closure_t cl;
41     struct comm_if ops;
42     struct cloc loc;
43     union iaddr addr;
44     int fd;
45     string_t authbind;
46     struct buffer_if *rbuf;
47     struct notify_list *notify;
48     bool_t use_proxy;
49     union iaddr proxy;
50 };
51
52 static const char *addr_to_string(void *commst, const struct comm_addr *ca) {
53     struct udp *st=commst;
54     static char sbuf[100];
55
56     snprintf(sbuf, sizeof(sbuf), "udp:%s-%s",
57             iaddr_to_string(&st->addr), iaddr_to_string(&ca->ia));
58     return sbuf;
59 }
60
61 static int udp_beforepoll(void *state, struct pollfd *fds, int *nfds_io,
62                           int *timeout_io)
63 {
64     struct udp *st=state;
65     if (*nfds_io<1) {
66         *nfds_io=1;
67         return ERANGE;
68     }
69     *nfds_io=1;
70     fds->fd=st->fd;
71     fds->events=POLLIN;
72     return 0;
73 }
74
75 static void udp_afterpoll(void *state, struct pollfd *fds, int nfds)
76 {
77     struct udp *st=state;
78     union iaddr from;
79     socklen_t fromlen;
80     struct notify_list *n;
81     bool_t done;
82     int rv;
83
84     if (nfds && (fds->revents & POLLIN)) {
85         do {
86             FILLZERO(from);
87             fromlen=sizeof(from);
88             BUF_ASSERT_FREE(st->rbuf);
89             BUF_ALLOC(st->rbuf,"udp_afterpoll");
90             buffer_init(st->rbuf,calculate_max_start_pad());
91             rv=recvfrom(st->fd, st->rbuf->start,
92                         buf_remaining_space(st->rbuf),
93                         0, (struct sockaddr *)&from, &fromlen);
94             if (rv>0) {
95                 st->rbuf->size=rv;
96                 if (st->use_proxy) {
97                     /* Check that the packet came from our poxy server;
98                        we shouldn't be contacted directly by anybody else
99                        (since they can trivially forge source addresses) */
100                     if (!iaddr_equal(&from,&st->proxy)) {
101                         Message(M_INFO,"udp: received packet that's not "
102                                 "from the proxy\n");
103                         BUF_FREE(st->rbuf);
104                         continue;
105                     }
106                     /* proxy protocol supports ipv4 transport only */
107                     FILLZERO(from);
108                     from.sa.sa_family=AF_INET;
109                     memcpy(&from.sin.sin_addr,buf_unprepend(st->rbuf,4),4);
110                     buf_unprepend(st->rbuf,2);
111                     memcpy(&from.sin.sin_port,buf_unprepend(st->rbuf,2),2);
112                 }
113                 struct comm_addr ca;
114                 FILLZERO(ca);
115                 ca.comm=&st->ops;
116                 ca.ia=from;
117                 done=False;
118                 for (n=st->notify; n; n=n->next) {
119                     if (n->fn(n->state, st->rbuf, &ca)) {
120                         done=True;
121                         break;
122                     }
123                 }
124                 if (!done) {
125                     uint32_t msgtype;
126                     if (st->rbuf->size>12 /* prevents traffic amplification */
127                         && ((msgtype=get_uint32(st->rbuf->start+8))
128                             != LABEL_NAK)) {
129                         uint32_t source,dest;
130                         /* Manufacture and send NAK packet */
131                         source=get_uint32(st->rbuf->start); /* Us */
132                         dest=get_uint32(st->rbuf->start+4); /* Them */
133                         send_nak(&ca,source,dest,msgtype,st->rbuf,"unwanted");
134                     }
135                     BUF_FREE(st->rbuf);
136                 }
137                 BUF_ASSERT_FREE(st->rbuf);
138             } else {
139                 BUF_FREE(st->rbuf);
140             }
141         } while (rv>=0);
142     }
143 }
144
145 static void request_notify(void *commst, void *nst, comm_notify_fn *fn)
146 {
147     struct udp *st=commst;
148     struct notify_list *n;
149     
150     n=safe_malloc(sizeof(*n),"request_notify");
151     n->fn=fn;
152     n->state=nst;
153     n->next=st->notify;
154     st->notify=n;
155 }
156
157 static void release_notify(void *commst, void *nst, comm_notify_fn *fn)
158 {
159     struct udp *st=commst;
160     struct notify_list *n, **p, *t;
161
162     /* XXX untested */
163     p=&st->notify;
164     for (n=st->notify; n; )
165     {
166         if (n->state==nst && n->fn==fn) {
167             t=n;
168             *p=n->next;
169             n=n->next;
170             free(t);
171         } else {
172             p=&n->next;
173             n=n->next;
174         }
175     }
176 }
177
178 static bool_t udp_sendmsg(void *commst, struct buffer_if *buf,
179                           const struct comm_addr *dest)
180 {
181     struct udp *st=commst;
182     uint8_t *sa;
183
184     if (st->use_proxy) {
185         sa=buf_prepend(buf,8);
186         if (dest->ia.sa.sa_family != AF_INET) {
187             Message(M_INFO,
188                "udp: proxy means dropping outgoing non-IPv4 packet to %s\n",
189                     iaddr_to_string(&dest->ia));
190             return False;
191         }
192         memcpy(sa,&dest->ia.sin.sin_addr,4);
193         memset(sa+4,0,4);
194         memcpy(sa+6,&dest->ia.sin.sin_port,2);
195         sendto(st->fd,sa,buf->size+8,0,(struct sockaddr *)&st->proxy,
196                sizeof(st->proxy));
197         buf_unprepend(buf,8);
198     } else {
199         sendto(st->fd, buf->start, buf->size, 0,
200                &dest->ia.sa, iaddr_socklen(&dest->ia));
201     }
202
203     return True;
204 }
205
206 static void udp_phase_hook(void *sst, uint32_t new_phase)
207 {
208     struct udp *st=sst;
209     union iaddr addr;
210
211     st->fd=socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
212     if (st->fd<0) {
213         fatal_perror("udp (%s:%d): socket",st->loc.file,st->loc.line);
214     }
215     if (fcntl(st->fd, F_SETFL, fcntl(st->fd, F_GETFL)|O_NONBLOCK)==-1) {
216         fatal_perror("udp (%s:%d): fcntl(set O_NONBLOCK)",
217                      st->loc.file,st->loc.line);
218     }
219     setcloexec(st->fd);
220
221     addr=st->addr;
222     if (st->authbind) {
223         pid_t c;
224         int status;
225
226         /* XXX this fork() and waitpid() business needs to be hidden
227            in some system-specific library functions. */
228         c=fork();
229         if (c==-1) {
230             fatal_perror("udp_phase_hook: fork() for authbind");
231         }
232         if (c==0) {
233             char *argv[4], addrstr[9], portstr[5];
234             switch (addr.sa.sa_family) {
235             case AF_INET:
236                 sprintf(addrstr,"%08lX",(long)addr.sin.sin_addr.s_addr);
237                 sprintf(portstr,"%04X",addr.sin.sin_port);
238                 break;
239             default:
240                 fatal("udp (%s:%d): unsupported address family for authbind",
241                       st->loc.file,st->loc.line);
242             }
243             argv[0]=st->authbind;
244             argv[1]=addrstr;
245             argv[2]=portstr;
246             argv[3]=NULL;
247             dup2(st->fd,0);
248             execvp(st->authbind,argv);
249             _exit(255);
250         }
251         while (waitpid(c,&status,0)==-1) {
252             if (errno==EINTR) continue;
253             fatal_perror("udp (%s:%d): authbind",st->loc.file,st->loc.line);
254         }
255         if (WIFSIGNALED(status)) {
256             fatal("udp (%s:%d): authbind died on signal %d",st->loc.file,
257                   st->loc.line, WTERMSIG(status));
258         }
259         if (WIFEXITED(status) && WEXITSTATUS(status)!=0) {
260             fatal("udp (%s:%d): authbind died with status %d",st->loc.file,
261                   st->loc.line, WEXITSTATUS(status));
262         }
263     } else {
264         if (bind(st->fd, (struct sockaddr *)&addr, sizeof(addr))!=0) {
265             fatal_perror("udp (%s:%d): bind",st->loc.file,st->loc.line);
266         }
267     }
268
269     register_for_poll(st,udp_beforepoll,udp_afterpoll,1,"udp");
270 }
271
272 static list_t *udp_apply(closure_t *self, struct cloc loc, dict_t *context,
273                          list_t *args)
274 {
275     struct udp *st;
276     item_t *i,*j;
277     dict_t *d;
278     list_t *l;
279     uint32_t a;
280
281     st=safe_malloc(sizeof(*st),"udp_apply(st)");
282     st->loc=loc;
283     st->cl.description="udp";
284     st->cl.type=CL_COMM;
285     st->cl.apply=NULL;
286     st->cl.interface=&st->ops;
287     st->ops.st=st;
288     st->ops.request_notify=request_notify;
289     st->ops.release_notify=release_notify;
290     st->ops.sendmsg=udp_sendmsg;
291     st->ops.addr_to_string=addr_to_string;
292     FILLZERO(st->addr);
293     st->use_proxy=False;
294
295     i=list_elem(args,0);
296     if (!i || i->type!=t_dict) {
297         cfgfatal(st->loc,"udp","first argument must be a dictionary\n");
298     }
299     d=i->data.dict;
300
301     st->addr.sa.sa_family=AF_INET;
302     j=dict_find_item(d,"address",False,"udp",st->loc);
303     st->addr.sin.sin_addr.s_addr=j?string_item_to_ipaddr(j, "udp"):INADDR_ANY;
304     st->addr.sin.sin_port=dict_read_number(d,"port",True,"udp",st->loc,0);
305     st->rbuf=find_cl_if(d,"buffer",CL_BUFFER,True,"udp",st->loc);
306     st->authbind=dict_read_string(d,"authbind",False,"udp",st->loc);
307     l=dict_lookup(d,"proxy");
308     if (l) {
309         st->use_proxy=True;
310         FILLZERO(st->proxy);
311         st->proxy.sa.sa_family=AF_INET;
312         i=list_elem(l,0);
313         if (!i || i->type!=t_string) {
314             cfgfatal(st->loc,"udp","proxy must supply ""addr"",port\n");
315         }
316         a=string_item_to_ipaddr(i,"proxy");
317         st->proxy.sin.sin_addr.s_addr=htonl(a);
318         i=list_elem(l,1);
319         if (!i || i->type!=t_number) {
320             cfgfatal(st->loc,"udp","proxy must supply ""addr"",port\n");
321         }
322         st->proxy.sin.sin_port=htons(i->data.number);
323     }
324
325     update_max_start_pad(&comm_max_start_pad, st->use_proxy ? 8 : 0);
326
327     add_hook(PHASE_GETRESOURCES,udp_phase_hook,st);
328
329     return new_closure(&st->cl);
330 }
331
332 void udp_module(dict_t *dict)
333 {
334     add_closure(dict,"udp",udp_apply);
335 }