chiark / gitweb /
udp: Break out udp_destroy_socket
[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 /*
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_destroy_socket(struct udpcommon *uc, struct udpsock *us)
187 {
188     if (us->fd>=0) {
189         close(us->fd);
190         us->fd=-1;
191     }
192 }
193
194 bool_t udp_make_socket(struct udpcommon *uc, struct udpsock *us,
195                        int failmsgclass)
196 {
197     const union iaddr *addr=&us->addr;
198     struct commcommon *cc=&uc->cc;
199     us->fd=-1;
200
201 #define FAIL_LG 0, cc->cl.description, &cc->loc, failmsgclass
202 #define FAIL(...) do{                                           \
203         lg_perror(FAIL_LG,errno,__VA_ARGS__);   \
204         goto failed;                                            \
205     }while(0)
206
207     us->fd=socket(addr->sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
208     if (us->fd<0) FAIL("socket");
209     if (fcntl(us->fd, F_SETFL, fcntl(us->fd, F_GETFL)|O_NONBLOCK)==-1)
210         FAIL("fcntl(set O_NONBLOCK)");
211     setcloexec(us->fd);
212 #ifdef CONFIG_IPV6
213     if (addr->sa.sa_family==AF_INET6) {
214         int r;
215         int optval=1;
216         socklen_t optlen=sizeof(optval);
217         r=setsockopt(us->fd,IPPROTO_IPV6,IPV6_V6ONLY,&optval,optlen);
218         if (r) FAIL("setsockopt(,IPV6_V6ONLY,&1,)");
219     }
220 #endif
221
222     if (uc->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             FAIL("fork() for authbind");
231         if (c==0) {
232             char *argv[5], addrstr[33], portstr[5];
233             const char *addrfam;
234             int port;
235             switch (addr->sa.sa_family) {
236             case AF_INET:
237                 sprintf(addrstr,"%08lX",(long)addr->sin.sin_addr.s_addr);
238                 port=addr->sin.sin_port;
239                 addrfam=NULL;
240                 break;
241 #ifdef CONFIG_IPV6
242             case AF_INET6: {
243                 int i;
244                 for (i=0; i<16; i++)
245                     sprintf(addrstr+i*2,"%02X",addr->sin6.sin6_addr.s6_addr[i]);
246                 port=addr->sin6.sin6_port;
247                 addrfam="6";
248                 break;
249             }
250 #endif /*CONFIG_IPV6*/
251             default:
252                 fatal("udp (%s:%d): unsupported address family for authbind",
253                       cc->loc.file,cc->loc.line);
254             }
255             sprintf(portstr,"%04X",port);
256             argv[0]=uc->authbind;
257             argv[1]=addrstr;
258             argv[2]=portstr;
259             argv[3]=(char*)addrfam;
260             argv[4]=NULL;
261             dup2(us->fd,0);
262             execvp(uc->authbind,argv);
263             _exit(255);
264         }
265         while (waitpid(c,&status,0)==-1) {
266             if (errno==EINTR) continue;
267             FAIL("waitpid for authbind");
268         }
269         if (status) {
270             if (WIFEXITED(status) && WEXITSTATUS(status)<127) {
271                 int es=WEXITSTATUS(status);
272                 lg_perror(FAIL_LG,es,
273                           "authbind exited with error exit status %d;"
274                           " indicates error",es);
275             } else {
276                 lg_exitstatus(FAIL_LG,status,"authbind");
277             }
278             goto failed;
279         }
280     } else {
281         if (bind(us->fd, &addr->sa, iaddr_socklen(addr))!=0)
282             FAIL("bind (%s)",iaddr_to_string(addr));
283     }
284     return True;
285
286 failed:
287     udp_destroy_socket(uc,us);
288     return False;
289
290 #undef FAIL
291 }
292
293 void udp_socks_register(struct udpcommon *uc, struct udpsocks *socks)
294 {
295     socks->uc=uc;
296     socks->interest=
297         register_for_poll(socks,udp_socks_beforepoll,udp_socks_afterpoll,"udp");
298 }
299
300 void udp_socks_deregister(struct udpcommon *uc, struct udpsocks *socks)
301 {
302     socks->uc=uc;
303     deregister_for_poll(socks->interest);
304 }
305
306 static void udp_phase_hook(void *sst, uint32_t new_phase)
307 {
308     struct udp *st=sst;
309     struct udpsocks *socks=&st->socks;
310     struct udpcommon *uc=&st->uc;
311     int i;
312     for (i=0; i<socks->n_socks; i++)
313         udp_make_socket(uc,&socks->socks[i],M_FATAL);
314
315     udp_socks_register(uc,socks);
316 }
317
318 static list_t *udp_apply(closure_t *self, struct cloc loc, dict_t *context,
319                          list_t *args)
320 {
321     struct udp *st;
322     list_t *caddrl;
323     list_t *l;
324     uint32_t a;
325     int i;
326
327     COMM_APPLY(st,&st->uc.cc,udp_,"udp",loc);
328     COMM_APPLY_STANDARD(st,&st->uc.cc,"udp",args);
329     UDP_APPLY_STANDARD(st,&st->uc,"udp");
330
331     struct udpcommon *uc=&st->uc;
332     struct udpsocks *socks=&st->socks;
333     struct commcommon *cc=&uc->cc;
334
335     union iaddr defaultaddrs[] = {
336 #ifdef CONFIG_IPV6
337         { .sin6 = { .sin6_family=AF_INET6,
338                     .sin6_port=htons(uc->port),
339                     .sin6_addr=IN6ADDR_ANY_INIT } },
340 #endif
341         { .sin = { .sin_family=AF_INET,
342                    .sin_port=htons(uc->port),
343                    .sin_addr= { .s_addr=INADDR_ANY } } }
344     };
345
346     caddrl=dict_lookup(d,"address");
347     socks->n_socks=caddrl ? list_length(caddrl) : (int)ARRAY_SIZE(defaultaddrs);
348     if (socks->n_socks<=0 || socks->n_socks>UDP_MAX_SOCKETS)
349         cfgfatal(cc->loc,"udp","`address' must be 1..%d addresses",
350                  UDP_MAX_SOCKETS);
351
352     for (i=0; i<socks->n_socks; i++) {
353         struct udpsock *us=&socks->socks[i];
354         if (!list_length(caddrl)) {
355             us->addr=defaultaddrs[i];
356         } else {
357             string_item_to_iaddr(list_elem(caddrl,i),uc->port,&us->addr,"udp");
358         }
359         us->fd=-1;
360     }
361
362     l=dict_lookup(d,"proxy");
363     if (l) {
364         uc->use_proxy=True;
365         uc->proxy.sa.sa_family=AF_INET;
366         item=list_elem(l,0);
367         if (!item || item->type!=t_string) {
368             cfgfatal(cc->loc,"udp","proxy must supply ""addr"",port\n");
369         }
370         a=string_item_to_ipaddr(item,"proxy");
371         uc->proxy.sin.sin_addr.s_addr=htonl(a);
372         item=list_elem(l,1);
373         if (!item || item->type!=t_number) {
374             cfgfatal(cc->loc,"udp","proxy must supply ""addr"",port\n");
375         }
376         uc->proxy.sin.sin_port=htons(item->data.number);
377     }
378
379     update_max_start_pad(&comm_max_start_pad, uc->use_proxy ? 8 : 0);
380
381     add_hook(PHASE_GETRESOURCES,udp_phase_hook,st);
382
383     return new_closure(&cc->cl);
384 }
385
386 void udp_module(dict_t *dict)
387 {
388     add_closure(dict,"udp",udp_apply);
389 }