b82a69e1be109aac93827e1688bf6fd4ce6c9474
[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 METHOD(socket_t, sender, status_t,
531 private_socket_dynamic_socket_t *this, packet_t *packet)
532 {
533 dynsock_t *skt;
534 host_t *src, *dst;
535 int family;
536 ssize_t len;
537 chunk_t data;
538 struct msghdr msg;
539 struct cmsghdr *cmsg;
540 struct iovec iov;
541
542 src = packet->get_source(packet);
543 dst = packet->get_destination(packet);
544 family = src->get_family(src);
545 skt = find_socket(this, family, src->get_port(src));
546 if (!skt)
547 {
548 return FAILED;
549 }
550
551 data = packet->get_data(packet);
552 DBG2(DBG_NET, "sending packet: from %#H to %#H", src, dst);
553
554 memset(&msg, 0, sizeof(struct msghdr));
555 msg.msg_name = dst->get_sockaddr(dst);;
556 msg.msg_namelen = *dst->get_sockaddr_len(dst);
557 iov.iov_base = data.ptr;
558 iov.iov_len = data.len;
559 msg.msg_iov = &iov;
560 msg.msg_iovlen = 1;
561 msg.msg_flags = 0;
562
563 if (!src->is_anyaddr(src))
564 {
565 if (family == AF_INET)
566 {
567 struct in_addr *addr;
568 struct sockaddr_in *sin;
569 char buf[CMSG_SPACE(sizeof(struct in_pktinfo))];
570 struct in_pktinfo *pktinfo;
571
572 memset(buf, 0, sizeof(buf));
573 msg.msg_control = buf;
574 msg.msg_controllen = sizeof(buf);
575 cmsg = CMSG_FIRSTHDR(&msg);
576 cmsg->cmsg_level = SOL_IP;
577 cmsg->cmsg_type = IP_PKTINFO;
578 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo));
579 pktinfo = (struct in_pktinfo*)CMSG_DATA(cmsg);
580 addr = &pktinfo->ipi_spec_dst;
581 sin = (struct sockaddr_in*)src->get_sockaddr(src);
582 memcpy(addr, &sin->sin_addr, sizeof(struct in_addr));
583 }
584 else
585 {
586 char buf[CMSG_SPACE(sizeof(struct in6_pktinfo))];
587 struct in6_pktinfo *pktinfo;
588 struct sockaddr_in6 *sin;
589
590 memset(buf, 0, sizeof(buf));
591 msg.msg_control = buf;
592 msg.msg_controllen = sizeof(buf);
593 cmsg = CMSG_FIRSTHDR(&msg);
594 cmsg->cmsg_level = SOL_IPV6;
595 cmsg->cmsg_type = IPV6_PKTINFO;
596 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
597 pktinfo = (struct in6_pktinfo*)CMSG_DATA(cmsg);
598 sin = (struct sockaddr_in6*)src->get_sockaddr(src);
599 memcpy(&pktinfo->ipi6_addr, &sin->sin6_addr, sizeof(struct in6_addr));
600 }
601 }
602
603 len = sendmsg(skt->fd, &msg, 0);
604 if (len != data.len)
605 {
606 DBG1(DBG_NET, "error writing to socket: %s", strerror(errno));
607 return FAILED;
608 }
609 return SUCCESS;
610 }
611
612 METHOD(socket_t, get_port, u_int16_t,
613 private_socket_dynamic_socket_t *this, bool nat_t)
614 {
615 /* we return 0 here for users that have no explicit port configured, the
616 * sender will default to the default port in this case */
617 return 0;
618 }
619
620 METHOD(socket_t, supported_families, socket_family_t,
621 private_socket_dynamic_socket_t *this)
622 {
623 /* we could return only the families of the opened sockets, but it could
624 * be that both families are supported even if no socket is yet open */
625 return SOCKET_FAMILY_BOTH;
626 }
627
628 METHOD(socket_t, destroy, void,
629 private_socket_dynamic_socket_t *this)
630 {
631 enumerator_t *enumerator;
632 dynsock_t *key, *value;
633
634 enumerator = this->sockets->create_enumerator(this->sockets);
635 while (enumerator->enumerate(enumerator, &key, &value))
636 {
637 close(value->fd);
638 free(value);
639 }
640 enumerator->destroy(enumerator);
641 this->sockets->destroy(this->sockets);
642 this->lock->destroy(this->lock);
643
644 close(this->notify[0]);
645 close(this->notify[1]);
646 free(this);
647 }
648
649 /*
650 * See header for description
651 */
652 socket_dynamic_socket_t *socket_dynamic_socket_create()
653 {
654 private_socket_dynamic_socket_t *this;
655
656 INIT(this,
657 .public = {
658 .socket = {
659 .send = _sender,
660 .receive = _receiver,
661 .get_port = _get_port,
662 .supported_families = _supported_families,
663 .destroy = _destroy,
664 },
665 },
666 .lock = rwlock_create(RWLOCK_TYPE_DEFAULT),
667 .max_packet = lib->settings->get_int(lib->settings,
668 "%s.max_packet", PACKET_MAX_DEFAULT, lib->ns),
669 );
670
671 if (pipe(this->notify) != 0)
672 {
673 DBG1(DBG_NET, "creating notify pipe for dynamic socket failed");
674 free(this);
675 return NULL;
676 }
677
678 this->sockets = hashtable_create((void*)hash, (void*)equals, 8);
679
680 return &this->public;
681 }