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