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