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