sockets: Initialize the whole ancillary data buffer not only the actual struct
[strongswan.git] / src / libcharon / plugins / socket_dynamic / socket_dynamic_socket.c
1 /*
2 * Copyright (C) 2006-2013 Tobias Brunner
3 * Copyright (C) 2006 Daniel Roethlisberger
4 * Copyright (C) 2005-2010 Martin Willi
5 * Copyright (C) 2005 Jan Hutter
6 * Hochschule fuer Technik Rapperswil
7 * Copyright (C) 2010 revosec AG
8 *
9 * This program is free software; you can redistribute it and/or modify it
10 * under the terms of the GNU General Public License as published by the
11 * Free Software Foundation; either version 2 of the License, or (at your
12 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
13 *
14 * This program is distributed in the hope that it will be useful, but
15 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
16 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
17 * for more details.
18 */
19
20 /* for struct in6_pktinfo */
21 #define _GNU_SOURCE
22
23 #include "socket_dynamic_socket.h"
24
25 #include <sys/types.h>
26 #include <sys/socket.h>
27 #include <string.h>
28 #include <errno.h>
29 #include <unistd.h>
30 #include <stdlib.h>
31 #include <fcntl.h>
32 #include <sys/ioctl.h>
33 #include <netinet/in_systm.h>
34 #include <netinet/in.h>
35 #include <netinet/ip.h>
36 #include <netinet/udp.h>
37 #include <net/if.h>
38
39 #include <hydra.h>
40 #include <daemon.h>
41 #include <threading/thread.h>
42 #include <threading/rwlock.h>
43 #include <collections/hashtable.h>
44
45 /* Maximum size of a packet */
46 #define MAX_PACKET 10000
47
48 /* these are not defined on some platforms */
49 #ifndef SOL_IP
50 #define SOL_IP IPPROTO_IP
51 #endif
52 #ifndef SOL_IPV6
53 #define SOL_IPV6 IPPROTO_IPV6
54 #endif
55
56 /* IPV6_RECVPKTINFO is defined in RFC 3542 which obsoletes RFC 2292 that
57 * previously defined IPV6_PKTINFO */
58 #ifndef IPV6_RECVPKTINFO
59 #define IPV6_RECVPKTINFO IPV6_PKTINFO
60 #endif
61
62 typedef struct private_socket_dynamic_socket_t private_socket_dynamic_socket_t;
63 typedef struct dynsock_t dynsock_t;
64
65 /**
66 * Private data of an socket_t object
67 */
68 struct private_socket_dynamic_socket_t {
69
70 /**
71 * public functions
72 */
73 socket_dynamic_socket_t public;
74
75 /**
76 * Hashtable of bound sockets
77 */
78 hashtable_t *sockets;
79
80 /**
81 * Lock for sockets hashtable
82 */
83 rwlock_t *lock;
84
85 /**
86 * Notification pipe to signal receiver
87 */
88 int notify[2];
89
90 /**
91 * Maximum packet size to receive
92 */
93 int max_packet;
94 };
95
96 /**
97 * Struct for a dynamically allocated socket
98 */
99 struct dynsock_t {
100
101 /**
102 * File descriptor of socket
103 */
104 int fd;
105
106 /**
107 * Address family
108 */
109 int family;
110
111 /**
112 * Bound source port
113 */
114 u_int16_t port;
115 };
116
117 /**
118 * Hash function for hashtable
119 */
120 static u_int hash(dynsock_t *key)
121 {
122 return (key->family << 16) | key->port;
123 }
124
125 /**
126 * Equals function for hashtable
127 */
128 static bool equals(dynsock_t *a, dynsock_t *b)
129 {
130 return a->family == b->family && a->port == b->port;
131 }
132
133 /**
134 * Create a fd_set from all bound sockets
135 */
136 static int build_fds(private_socket_dynamic_socket_t *this, fd_set *fds)
137 {
138 enumerator_t *enumerator;
139 dynsock_t *key, *value;
140 int maxfd;
141
142 FD_ZERO(fds);
143 FD_SET(this->notify[0], fds);
144 maxfd = this->notify[0];
145
146 this->lock->read_lock(this->lock);
147 enumerator = this->sockets->create_enumerator(this->sockets);
148 while (enumerator->enumerate(enumerator, &key, &value))
149 {
150 FD_SET(value->fd, fds);
151 maxfd = max(maxfd, value->fd);
152 }
153 enumerator->destroy(enumerator);
154 this->lock->unlock(this->lock);
155
156 return maxfd + 1;
157 }
158
159 /**
160 * Find the socket select()ed
161 */
162 static dynsock_t* scan_fds(private_socket_dynamic_socket_t *this, fd_set *fds)
163 {
164 enumerator_t *enumerator;
165 dynsock_t *key, *value, *selected = NULL;
166
167 this->lock->read_lock(this->lock);
168 enumerator = this->sockets->create_enumerator(this->sockets);
169 while (enumerator->enumerate(enumerator, &key, &value))
170 {
171 if (FD_ISSET(value->fd, fds))
172 {
173 selected = value;
174 break;
175 }
176 }
177 enumerator->destroy(enumerator);
178 this->lock->unlock(this->lock);
179
180 return selected;
181 }
182
183 /**
184 * Receive a packet from a given socket fd
185 */
186 static packet_t *receive_packet(private_socket_dynamic_socket_t *this,
187 dynsock_t *skt)
188 {
189 host_t *source = NULL, *dest = NULL;
190 ssize_t len;
191 char buffer[this->max_packet];
192 chunk_t data;
193 packet_t *packet;
194 struct msghdr msg;
195 struct cmsghdr *cmsgptr;
196 struct iovec iov;
197 char ancillary[64];
198 union {
199 struct sockaddr_in in4;
200 struct sockaddr_in6 in6;
201 } src;
202
203 msg.msg_name = &src;
204 msg.msg_namelen = sizeof(src);
205 iov.iov_base = buffer;
206 iov.iov_len = this->max_packet;
207 msg.msg_iov = &iov;
208 msg.msg_iovlen = 1;
209 msg.msg_control = ancillary;
210 msg.msg_controllen = sizeof(ancillary);
211 msg.msg_flags = 0;
212 len = recvmsg(skt->fd, &msg, 0);
213 if (len < 0)
214 {
215 DBG1(DBG_NET, "error reading socket: %s", strerror(errno));
216 return NULL;
217 }
218 if (msg.msg_flags & MSG_TRUNC)
219 {
220 DBG1(DBG_NET, "receive buffer too small, packet discarded");
221 return NULL;
222 }
223 DBG3(DBG_NET, "received packet %b", buffer, (u_int)len);
224
225 /* read ancillary data to get destination address */
226 for (cmsgptr = CMSG_FIRSTHDR(&msg); cmsgptr != NULL;
227 cmsgptr = CMSG_NXTHDR(&msg, cmsgptr))
228 {
229 if (cmsgptr->cmsg_len == 0)
230 {
231 DBG1(DBG_NET, "error reading ancillary data");
232 return NULL;
233 }
234
235 if (cmsgptr->cmsg_level == SOL_IPV6 &&
236 cmsgptr->cmsg_type == IPV6_PKTINFO)
237 {
238 struct in6_pktinfo *pktinfo;
239 struct sockaddr_in6 dst;
240
241 pktinfo = (struct in6_pktinfo*)CMSG_DATA(cmsgptr);
242 memset(&dst, 0, sizeof(dst));
243 memcpy(&dst.sin6_addr, &pktinfo->ipi6_addr, sizeof(dst.sin6_addr));
244 dst.sin6_family = AF_INET6;
245 dst.sin6_port = htons(skt->port);
246 dest = host_create_from_sockaddr((sockaddr_t*)&dst);
247 }
248 if (cmsgptr->cmsg_level == SOL_IP &&
249 cmsgptr->cmsg_type == IP_PKTINFO)
250 {
251 struct in_pktinfo *pktinfo;
252 struct sockaddr_in dst;
253
254 pktinfo = (struct in_pktinfo*)CMSG_DATA(cmsgptr);
255 memset(&dst, 0, sizeof(dst));
256 memcpy(&dst.sin_addr, &pktinfo->ipi_addr, sizeof(dst.sin_addr));
257
258 dst.sin_family = AF_INET;
259 dst.sin_port = htons(skt->port);
260 dest = host_create_from_sockaddr((sockaddr_t*)&dst);
261 }
262 if (dest)
263 {
264 break;
265 }
266 }
267 if (dest == NULL)
268 {
269 DBG1(DBG_NET, "error reading IP header");
270 return NULL;
271 }
272 source = host_create_from_sockaddr((sockaddr_t*)&src);
273 DBG2(DBG_NET, "received packet: from %#H to %#H", source, dest);
274 data = chunk_create(buffer, len);
275
276 packet = packet_create();
277 packet->set_source(packet, source);
278 packet->set_destination(packet, dest);
279 packet->set_data(packet, chunk_clone(data));
280 return packet;
281 }
282
283 METHOD(socket_t, receiver, status_t,
284 private_socket_dynamic_socket_t *this, packet_t **packet)
285 {
286 dynsock_t *selected;
287 packet_t *pkt;
288 bool oldstate;
289 fd_set fds;
290 int maxfd;
291
292 while (TRUE)
293 {
294 maxfd = build_fds(this, &fds);
295
296 DBG2(DBG_NET, "waiting for data on sockets");
297 oldstate = thread_cancelability(TRUE);
298 if (select(maxfd, &fds, NULL, NULL, NULL) <= 0)
299 {
300 thread_cancelability(oldstate);
301 return FAILED;
302 }
303 thread_cancelability(oldstate);
304
305 if (FD_ISSET(this->notify[0], &fds))
306 { /* got notified, read garbage, rebuild fdset */
307 char buf[1];
308
309 ignore_result(read(this->notify[0], buf, sizeof(buf)));
310 DBG2(DBG_NET, "rebuilding fdset due to newly bound ports");
311 continue;
312 }
313 selected = scan_fds(this, &fds);
314 if (selected)
315 {
316 break;
317 }
318 }
319 pkt = receive_packet(this, selected);
320 if (pkt)
321 {
322 *packet = pkt;
323 return SUCCESS;
324 }
325 return FAILED;
326 }
327
328 /**
329 * Get the port allocated dynamically using bind()
330 */
331 static bool get_dynamic_port(int fd, int family, u_int16_t *port)
332 {
333 union {
334 struct sockaddr_storage ss;
335 struct sockaddr s;
336 struct sockaddr_in sin;
337 struct sockaddr_in6 sin6;
338 } addr;
339 socklen_t addrlen;
340
341 addrlen = sizeof(addr);
342 if (getsockname(fd, &addr.s, &addrlen) != 0)
343 {
344 DBG1(DBG_NET, "unable to getsockname: %s", strerror(errno));
345 return FALSE;
346 }
347 switch (family)
348 {
349 case AF_INET:
350 if (addrlen != sizeof(addr.sin) || addr.sin.sin_family != family)
351 {
352 break;
353 }
354 *port = ntohs(addr.sin.sin_port);
355 return TRUE;
356 case AF_INET6:
357 if (addrlen != sizeof(addr.sin6) || addr.sin6.sin6_family != family)
358 {
359 break;
360 }
361 *port = ntohs(addr.sin6.sin6_port);
362 return TRUE;
363 default:
364 return FALSE;
365 }
366 DBG1(DBG_NET, "received invalid getsockname() result");
367 return FALSE;
368 }
369
370 /**
371 * open a socket to send and receive packets
372 */
373 static int open_socket(private_socket_dynamic_socket_t *this,
374 int family, u_int16_t *port)
375 {
376 union {
377 struct sockaddr_storage ss;
378 struct sockaddr s;
379 struct sockaddr_in sin;
380 struct sockaddr_in6 sin6;
381 } addr;
382 int on = TRUE;
383 socklen_t addrlen;
384 u_int sol, pktinfo = 0;
385 int fd;
386
387 memset(&addr, 0, sizeof(addr));
388 /* precalculate constants depending on address family */
389 switch (family)
390 {
391 case AF_INET:
392 addr.sin.sin_family = AF_INET;
393 addr.sin.sin_addr.s_addr = INADDR_ANY;
394 addr.sin.sin_port = htons(*port);
395 addrlen = sizeof(addr.sin);
396 sol = SOL_IP;
397 pktinfo = IP_PKTINFO;
398 break;
399 case AF_INET6:
400 addr.sin6.sin6_family = AF_INET6;
401 memset(&addr.sin6.sin6_addr, 0, sizeof(addr.sin6.sin6_addr));
402 addr.sin6.sin6_port = htons(*port);
403 addrlen = sizeof(addr.sin6);
404 sol = SOL_IPV6;
405 pktinfo = IPV6_RECVPKTINFO;
406 break;
407 default:
408 return 0;
409 }
410
411 fd = socket(family, SOCK_DGRAM, IPPROTO_UDP);
412 if (fd < 0)
413 {
414 DBG1(DBG_NET, "could not open socket: %s", strerror(errno));
415 return 0;
416 }
417 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void*)&on, sizeof(on)) < 0)
418 {
419 DBG1(DBG_NET, "unable to set SO_REUSEADDR on socket: %s", strerror(errno));
420 close(fd);
421 return 0;
422 }
423
424 if (bind(fd, &addr.s, addrlen) < 0)
425 {
426 DBG1(DBG_NET, "unable to bind socket: %s", strerror(errno));
427 close(fd);
428 return 0;
429 }
430 if (*port == 0 && !get_dynamic_port(fd, family, port))
431 {
432 close(fd);
433 return 0;
434 }
435
436 /* get additional packet info on receive */
437 if (setsockopt(fd, sol, pktinfo, &on, sizeof(on)) < 0)
438 {
439 DBG1(DBG_NET, "unable to set IP_PKTINFO on socket: %s", strerror(errno));
440 close(fd);
441 return 0;
442 }
443
444 if (!hydra->kernel_interface->bypass_socket(hydra->kernel_interface,
445 fd, family))
446 {
447 DBG1(DBG_NET, "installing IKE bypass policy failed");
448 }
449
450 /* enable UDP decapsulation on each socket */
451 if (!hydra->kernel_interface->enable_udp_decap(hydra->kernel_interface,
452 fd, family, *port))
453 {
454 DBG1(DBG_NET, "enabling UDP decapsulation for %s on port %d failed",
455 family == AF_INET ? "IPv4" : "IPv6", *port);
456 }
457
458 return fd;
459 }
460
461 /**
462 * Get the first usable socket for an address family
463 */
464 static dynsock_t *get_any_socket(private_socket_dynamic_socket_t *this,
465 int family)
466 {
467 dynsock_t *key, *value, *found = NULL;
468 enumerator_t *enumerator;
469
470 this->lock->read_lock(this->lock);
471 enumerator = this->sockets->create_enumerator(this->sockets);
472 while (enumerator->enumerate(enumerator, &key, &value))
473 {
474 if (value->family == family)
475 {
476 found = value;
477 break;
478 }
479 }
480 enumerator->destroy(enumerator);
481 this->lock->unlock(this->lock);
482
483 return found;
484 }
485
486 /**
487 * Find/Create a socket to send from host
488 */
489 static dynsock_t *find_socket(private_socket_dynamic_socket_t *this,
490 int family, u_int16_t port)
491 {
492 dynsock_t *skt, lookup = {
493 .family = family,
494 .port = port,
495 };
496 char buf[] = {0x01};
497 int fd;
498
499 this->lock->read_lock(this->lock);
500 skt = this->sockets->get(this->sockets, &lookup);
501 this->lock->unlock(this->lock);
502 if (skt)
503 {
504 return skt;
505 }
506 if (!port)
507 {
508 skt = get_any_socket(this, family);
509 if (skt)
510 {
511 return skt;
512 }
513 }
514 fd = open_socket(this, family, &port);
515 if (!fd)
516 {
517 return NULL;
518 }
519 INIT(skt,
520 .family = family,
521 .port = port,
522 .fd = fd,
523 );
524 this->lock->write_lock(this->lock);
525 this->sockets->put(this->sockets, skt, skt);
526 this->lock->unlock(this->lock);
527 /* notify receiver thread to reread socket list */
528 ignore_result(write(this->notify[1], buf, sizeof(buf)));
529
530 return skt;
531 }
532
533 METHOD(socket_t, sender, status_t,
534 private_socket_dynamic_socket_t *this, packet_t *packet)
535 {
536 dynsock_t *skt;
537 host_t *src, *dst;
538 int family;
539 ssize_t len;
540 chunk_t data;
541 struct msghdr msg;
542 struct cmsghdr *cmsg;
543 struct iovec iov;
544
545 src = packet->get_source(packet);
546 dst = packet->get_destination(packet);
547 family = src->get_family(src);
548 skt = find_socket(this, family, src->get_port(src));
549 if (!skt)
550 {
551 return FAILED;
552 }
553
554 data = packet->get_data(packet);
555 DBG2(DBG_NET, "sending packet: from %#H to %#H", src, dst);
556
557 memset(&msg, 0, sizeof(struct msghdr));
558 msg.msg_name = dst->get_sockaddr(dst);;
559 msg.msg_namelen = *dst->get_sockaddr_len(dst);
560 iov.iov_base = data.ptr;
561 iov.iov_len = data.len;
562 msg.msg_iov = &iov;
563 msg.msg_iovlen = 1;
564 msg.msg_flags = 0;
565
566 if (!src->is_anyaddr(src))
567 {
568 if (family == AF_INET)
569 {
570 struct in_addr *addr;
571 struct sockaddr_in *sin;
572 char buf[CMSG_SPACE(sizeof(struct in_pktinfo))];
573 struct in_pktinfo *pktinfo;
574
575 memset(buf, 0, sizeof(buf));
576 msg.msg_control = buf;
577 msg.msg_controllen = sizeof(buf);
578 cmsg = CMSG_FIRSTHDR(&msg);
579 cmsg->cmsg_level = SOL_IP;
580 cmsg->cmsg_type = IP_PKTINFO;
581 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo));
582 pktinfo = (struct in_pktinfo*)CMSG_DATA(cmsg);
583 addr = &pktinfo->ipi_spec_dst;
584 sin = (struct sockaddr_in*)src->get_sockaddr(src);
585 memcpy(addr, &sin->sin_addr, sizeof(struct in_addr));
586 }
587 else
588 {
589 char buf[CMSG_SPACE(sizeof(struct in6_pktinfo))];
590 struct in6_pktinfo *pktinfo;
591 struct sockaddr_in6 *sin;
592
593 memset(buf, 0, sizeof(buf));
594 msg.msg_control = buf;
595 msg.msg_controllen = sizeof(buf);
596 cmsg = CMSG_FIRSTHDR(&msg);
597 cmsg->cmsg_level = SOL_IPV6;
598 cmsg->cmsg_type = IPV6_PKTINFO;
599 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
600 pktinfo = (struct in6_pktinfo*)CMSG_DATA(cmsg);
601 sin = (struct sockaddr_in6*)src->get_sockaddr(src);
602 memcpy(&pktinfo->ipi6_addr, &sin->sin6_addr, sizeof(struct in6_addr));
603 }
604 }
605
606 len = sendmsg(skt->fd, &msg, 0);
607 if (len != data.len)
608 {
609 DBG1(DBG_NET, "error writing to socket: %s", strerror(errno));
610 return FAILED;
611 }
612 return SUCCESS;
613 }
614
615 METHOD(socket_t, get_port, u_int16_t,
616 private_socket_dynamic_socket_t *this, bool nat_t)
617 {
618 /* we return 0 here for users that have no explicit port configured, the
619 * sender will default to the default port in this case */
620 return 0;
621 }
622
623 METHOD(socket_t, supported_families, socket_family_t,
624 private_socket_dynamic_socket_t *this)
625 {
626 /* we could return only the families of the opened sockets, but it could
627 * be that both families are supported even if no socket is yet open */
628 return SOCKET_FAMILY_BOTH;
629 }
630
631 METHOD(socket_t, destroy, void,
632 private_socket_dynamic_socket_t *this)
633 {
634 enumerator_t *enumerator;
635 dynsock_t *key, *value;
636
637 enumerator = this->sockets->create_enumerator(this->sockets);
638 while (enumerator->enumerate(enumerator, &key, &value))
639 {
640 close(value->fd);
641 free(value);
642 }
643 enumerator->destroy(enumerator);
644 this->sockets->destroy(this->sockets);
645 this->lock->destroy(this->lock);
646
647 close(this->notify[0]);
648 close(this->notify[1]);
649 free(this);
650 }
651
652 /*
653 * See header for description
654 */
655 socket_dynamic_socket_t *socket_dynamic_socket_create()
656 {
657 private_socket_dynamic_socket_t *this;
658
659 INIT(this,
660 .public = {
661 .socket = {
662 .send = _sender,
663 .receive = _receiver,
664 .get_port = _get_port,
665 .supported_families = _supported_families,
666 .destroy = _destroy,
667 },
668 },
669 .lock = rwlock_create(RWLOCK_TYPE_DEFAULT),
670 .max_packet = lib->settings->get_int(lib->settings,
671 "%s.max_packet", MAX_PACKET, charon->name),
672 );
673
674 if (pipe(this->notify) != 0)
675 {
676 DBG1(DBG_NET, "creating notify pipe for dynamic socket failed");
677 free(this);
678 return NULL;
679 }
680
681 this->sockets = hashtable_create((void*)hash, (void*)equals, 8);
682
683 return &this->public;
684 }