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