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