comm: Formalise interface to udp sockets
[secnet] / 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 #include "comm-common.h"
27
28 static comm_sendmsg_fn udp_sendmsg;
29
30 struct udp {
31 struct udpcommon uc;
32 struct udpsocks socks;
33 };
34
35 /*
36 * Re comm_addr.ix: This field allows us to note in the comm_addr
37 * which socket an incoming packet was received on. This is required
38 * for conveniently logging the actual source of a packet. But the ix
39 * does not formally form part of the address: it is not used when
40 * sending, nor when comparing two comm_addrs.
41 *
42 * The special value -1 means that the comm_addr was constructed by
43 * another module in secnet (eg the resolver), rather than being a
44 * description of the source of an incoming packet.
45 */
46
47 static const char *udp_addr_to_string(void *commst, const struct comm_addr *ca)
48 {
49 struct udp *st=commst;
50 struct udpsocks *socks=&st->socks;
51 static char sbuf[100];
52 int ix=ca->ix>=0 ? ca->ix : 0;
53
54 assert(ix>=0 && ix<socks->n_socks);
55 snprintf(sbuf, sizeof(sbuf), "udp:%s%s-%s",
56 iaddr_to_string(&socks->socks[ix].addr),
57 ca->ix<0 ? "&" : "",
58 iaddr_to_string(&ca->ia));
59 return sbuf;
60 }
61
62 static int udp_socks_beforepoll(void *state, struct pollfd *fds, int *nfds_io,
63 int *timeout_io)
64 {
65 struct udpsocks *socks=state;
66 int i;
67 BEFOREPOLL_WANT_FDS(socks->n_socks);
68 for (i=0; i<socks->n_socks; i++) {
69 fds[i].fd=socks->socks[i].fd;
70 fds[i].events=POLLIN;
71 }
72 return 0;
73 }
74
75 static void udp_socks_afterpoll(void *state, struct pollfd *fds, int nfds)
76 {
77 struct udpsocks *socks=state;
78 struct udpcommon *uc=socks->uc;
79 union iaddr from;
80 socklen_t fromlen;
81 bool_t done;
82 int rv;
83 int i;
84
85 struct commcommon *cc=&uc->cc;
86
87 for (i=0; i<socks->n_socks; i++) {
88 if (i>=nfds) continue;
89 if (!(fds[i].revents & POLLIN)) continue;
90 assert(fds[i].fd == socks->socks[i].fd);
91 int fd=socks->socks[i].fd;
92 do {
93 fromlen=sizeof(from);
94 BUF_ASSERT_FREE(cc->rbuf);
95 BUF_ALLOC(cc->rbuf,"udp_afterpoll");
96 buffer_init(cc->rbuf,calculate_max_start_pad());
97 rv=recvfrom(fd, cc->rbuf->start,
98 buf_remaining_space(cc->rbuf),
99 0, &from.sa, &fromlen);
100 if (rv>0) {
101 cc->rbuf->size=rv;
102 if (uc->use_proxy) {
103 /* Check that the packet came from our poxy server;
104 we shouldn't be contacted directly by anybody else
105 (since they can trivially forge source addresses) */
106 if (!iaddr_equal(&from,&uc->proxy)) {
107 Message(M_INFO,"udp: received packet that's not "
108 "from the proxy\n");
109 BUF_FREE(cc->rbuf);
110 continue;
111 }
112 /* proxy protocol supports ipv4 transport only */
113 from.sa.sa_family=AF_INET;
114 BUF_GET_BYTES(unprepend,cc->rbuf,&from.sin.sin_addr,4);
115 buf_unprepend(cc->rbuf,2);
116 BUF_GET_BYTES(unprepend,cc->rbuf,&from.sin.sin_port,2);
117 }
118 struct comm_addr ca;
119 ca.comm=&cc->ops;
120 ca.ia=from;
121 ca.ix=i;
122 done=comm_notify(&cc->notify, cc->rbuf, &ca);
123 if (!done) {
124 uint32_t msgtype;
125 if (cc->rbuf->size>12 /* prevents traffic amplification */
126 && ((msgtype=get_uint32(cc->rbuf->start+8))
127 != LABEL_NAK)) {
128 uint32_t source,dest;
129 /* Manufacture and send NAK packet */
130 source=get_uint32(cc->rbuf->start); /* Us */
131 dest=get_uint32(cc->rbuf->start+4); /* Them */
132 send_nak(&ca,source,dest,msgtype,cc->rbuf,"unwanted");
133 }
134 BUF_FREE(cc->rbuf);
135 }
136 BUF_ASSERT_FREE(cc->rbuf);
137 } else {
138 BUF_FREE(cc->rbuf);
139 }
140 } while (rv>=0);
141 }
142 }
143
144 static bool_t udp_sendmsg(void *commst, struct buffer_if *buf,
145 const struct comm_addr *dest)
146 {
147 struct udp *st=commst;
148 struct udpcommon *uc=&st->uc;
149 struct udpsocks *socks=&st->socks;
150 uint8_t *sa;
151
152 if (uc->use_proxy) {
153 sa=buf_prepend(buf,8);
154 if (dest->ia.sa.sa_family != AF_INET) {
155 Message(M_INFO,
156 "udp: proxy means dropping outgoing non-IPv4 packet to %s\n",
157 iaddr_to_string(&dest->ia));
158 return False;
159 }
160 memcpy(sa,&dest->ia.sin.sin_addr,4);
161 memset(sa+4,0,4);
162 memcpy(sa+6,&dest->ia.sin.sin_port,2);
163 sendto(socks->socks[0].fd,sa,buf->size+8,0,&uc->proxy.sa,
164 iaddr_socklen(&uc->proxy));
165 buf_unprepend(buf,8);
166 } else {
167 int i,r;
168 bool_t allunsupported=True;
169 for (i=0; i<socks->n_socks; i++) {
170 if (dest->ia.sa.sa_family != socks->socks[i].addr.sa.sa_family)
171 /* no point even trying */
172 continue;
173 r=sendto(socks->socks[i].fd, buf->start, buf->size, 0,
174 &dest->ia.sa, iaddr_socklen(&dest->ia));
175 if (r>=0) return True;
176 if (!(errno==EAFNOSUPPORT || errno==ENETUNREACH))
177 /* who knows what that error means? */
178 allunsupported=False;
179 }
180 return !allunsupported; /* see doc for comm_sendmsg_fn in secnet.h */
181 }
182
183 return True;
184 }
185
186 void udp_make_socket(struct udpcommon *uc, struct udpsock *us)
187 {
188 const union iaddr *addr=&us->addr;
189 struct commcommon *cc=&uc->cc;
190
191 us->fd=socket(addr->sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
192 if (us->fd<0) {
193 fatal_perror("udp (%s:%d): socket",cc->loc.file,cc->loc.line);
194 }
195 if (fcntl(us->fd, F_SETFL, fcntl(us->fd, F_GETFL)|O_NONBLOCK)==-1) {
196 fatal_perror("udp (%s:%d): fcntl(set O_NONBLOCK)",
197 cc->loc.file,cc->loc.line);
198 }
199 setcloexec(us->fd);
200 #ifdef CONFIG_IPV6
201 if (addr->sa.sa_family==AF_INET6) {
202 int r;
203 int optval=1;
204 socklen_t optlen=sizeof(optval);
205 r=setsockopt(us->fd,IPPROTO_IPV6,IPV6_V6ONLY,&optval,optlen);
206 if (r) fatal_perror("udp (%s:%d): setsockopt(,IPV6_V6ONLY,&1,)",
207 cc->loc.file,cc->loc.line);
208 }
209 #endif
210
211 if (uc->authbind) {
212 pid_t c;
213 int status;
214
215 /* XXX this fork() and waitpid() business needs to be hidden
216 in some system-specific library functions. */
217 c=fork();
218 if (c==-1) {
219 fatal_perror("udp_phase_hook: fork() for authbind");
220 }
221 if (c==0) {
222 char *argv[5], addrstr[33], portstr[5];
223 const char *addrfam;
224 int port;
225 switch (addr->sa.sa_family) {
226 case AF_INET:
227 sprintf(addrstr,"%08lX",(long)addr->sin.sin_addr.s_addr);
228 port=addr->sin.sin_port;
229 addrfam=NULL;
230 break;
231 #ifdef CONFIG_IPV6
232 case AF_INET6: {
233 int i;
234 for (i=0; i<16; i++)
235 sprintf(addrstr+i*2,"%02X",addr->sin6.sin6_addr.s6_addr[i]);
236 port=addr->sin6.sin6_port;
237 addrfam="6";
238 break;
239 }
240 #endif /*CONFIG_IPV6*/
241 default:
242 fatal("udp (%s:%d): unsupported address family for authbind",
243 cc->loc.file,cc->loc.line);
244 }
245 sprintf(portstr,"%04X",port);
246 argv[0]=uc->authbind;
247 argv[1]=addrstr;
248 argv[2]=portstr;
249 argv[3]=(char*)addrfam;
250 argv[4]=NULL;
251 dup2(us->fd,0);
252 execvp(uc->authbind,argv);
253 _exit(255);
254 }
255 while (waitpid(c,&status,0)==-1) {
256 if (errno==EINTR) continue;
257 fatal_perror("udp (%s:%d): authbind",cc->loc.file,cc->loc.line);
258 }
259 if (WIFSIGNALED(status)) {
260 fatal("udp (%s:%d): authbind died on signal %d",cc->loc.file,
261 cc->loc.line, WTERMSIG(status));
262 }
263 if (WIFEXITED(status) && WEXITSTATUS(status)!=0) {
264 fatal("udp (%s:%d): authbind died with status %d",cc->loc.file,
265 cc->loc.line, WEXITSTATUS(status));
266 }
267 } else {
268 if (bind(us->fd, &addr->sa, iaddr_socklen(addr))!=0) {
269 fatal_perror("udp (%s:%d): bind",cc->loc.file,cc->loc.line);
270 }
271 }
272 }
273
274 void udp_socks_register(struct udpcommon *uc, struct udpsocks *socks)
275 {
276 socks->uc=uc;
277 register_for_poll(socks,udp_socks_beforepoll,udp_socks_afterpoll,"udp");
278 }
279
280 static void udp_phase_hook(void *sst, uint32_t new_phase)
281 {
282 struct udp *st=sst;
283 struct udpsocks *socks=&st->socks;
284 struct udpcommon *uc=&st->uc;
285 int i;
286 for (i=0; i<socks->n_socks; i++)
287 udp_make_socket(uc,&socks->socks[i]);
288
289 udp_socks_register(uc,socks);
290 }
291
292 static list_t *udp_apply(closure_t *self, struct cloc loc, dict_t *context,
293 list_t *args)
294 {
295 struct udp *st;
296 list_t *caddrl;
297 list_t *l;
298 uint32_t a;
299 int i;
300
301 COMM_APPLY(st,&st->uc.cc,udp_,"udp",loc);
302 COMM_APPLY_STANDARD(st,&st->uc.cc,"udp",args);
303 UDP_APPLY_STANDARD(st,&st->uc,"udp");
304
305 struct udpcommon *uc=&st->uc;
306 struct udpsocks *socks=&st->socks;
307 struct commcommon *cc=&uc->cc;
308
309 union iaddr defaultaddrs[] = {
310 #ifdef CONFIG_IPV6
311 { .sin6 = { .sin6_family=AF_INET6,
312 .sin6_port=htons(uc->port),
313 .sin6_addr=IN6ADDR_ANY_INIT } },
314 #endif
315 { .sin = { .sin_family=AF_INET,
316 .sin_port=htons(uc->port),
317 .sin_addr= { .s_addr=INADDR_ANY } } }
318 };
319
320 caddrl=dict_lookup(d,"address");
321 socks->n_socks=caddrl ? list_length(caddrl) : (int)ARRAY_SIZE(defaultaddrs);
322 if (socks->n_socks<=0 || socks->n_socks>UDP_MAX_SOCKETS)
323 cfgfatal(cc->loc,"udp","`address' must be 1..%d addresses",
324 UDP_MAX_SOCKETS);
325
326 for (i=0; i<socks->n_socks; i++) {
327 struct udpsock *us=&socks->socks[i];
328 if (!list_length(caddrl)) {
329 us->addr=defaultaddrs[i];
330 } else {
331 string_item_to_iaddr(list_elem(caddrl,i),uc->port,&us->addr,"udp");
332 }
333 us->fd=-1;
334 }
335
336 l=dict_lookup(d,"proxy");
337 if (l) {
338 uc->use_proxy=True;
339 uc->proxy.sa.sa_family=AF_INET;
340 item=list_elem(l,0);
341 if (!item || item->type!=t_string) {
342 cfgfatal(cc->loc,"udp","proxy must supply ""addr"",port\n");
343 }
344 a=string_item_to_ipaddr(item,"proxy");
345 uc->proxy.sin.sin_addr.s_addr=htonl(a);
346 item=list_elem(l,1);
347 if (!item || item->type!=t_number) {
348 cfgfatal(cc->loc,"udp","proxy must supply ""addr"",port\n");
349 }
350 uc->proxy.sin.sin_port=htons(item->data.number);
351 }
352
353 update_max_start_pad(&comm_max_start_pad, uc->use_proxy ? 8 : 0);
354
355 add_hook(PHASE_GETRESOURCES,udp_phase_hook,st);
356
357 return new_closure(&cc->cl);
358 }
359
360 void udp_module(dict_t *dict)
361 {
362 add_closure(dict,"udp",udp_apply);
363 }