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