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