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