diff options
author | Rene Mayrhofer <rene@mayrhofer.eu.org> | 2007-04-12 20:30:08 +0000 |
---|---|---|
committer | Rene Mayrhofer <rene@mayrhofer.eu.org> | 2007-04-12 20:30:08 +0000 |
commit | b0d8ed94fe9e74afb49fdf5f11e4add29879c65c (patch) | |
tree | b20167235628771046e940a82a906a6d0991ee4a /src/charon/threads | |
parent | ea939d07c84d2a8e51215458063fc05e9c399290 (diff) | |
download | vyos-strongswan-b0d8ed94fe9e74afb49fdf5f11e4add29879c65c.tar.gz vyos-strongswan-b0d8ed94fe9e74afb49fdf5f11e4add29879c65c.zip |
[svn-upgrade] Integrating new upstream version, strongswan (4.1.1)
Diffstat (limited to 'src/charon/threads')
-rw-r--r-- | src/charon/threads/kernel_interface.c | 1964 | ||||
-rw-r--r-- | src/charon/threads/kernel_interface.h | 331 | ||||
-rw-r--r-- | src/charon/threads/receiver.c | 372 | ||||
-rw-r--r-- | src/charon/threads/receiver.h | 81 | ||||
-rw-r--r-- | src/charon/threads/scheduler.c | 102 | ||||
-rw-r--r-- | src/charon/threads/scheduler.h | 68 | ||||
-rw-r--r-- | src/charon/threads/sender.c | 149 | ||||
-rw-r--r-- | src/charon/threads/sender.h | 74 | ||||
-rwxr-xr-x | src/charon/threads/stroke_interface.c | 1456 | ||||
-rw-r--r-- | src/charon/threads/stroke_interface.h | 61 | ||||
-rw-r--r-- | src/charon/threads/thread_pool.c | 181 | ||||
-rw-r--r-- | src/charon/threads/thread_pool.h | 87 |
12 files changed, 4926 insertions, 0 deletions
diff --git a/src/charon/threads/kernel_interface.c b/src/charon/threads/kernel_interface.c new file mode 100644 index 000000000..4a70d2ecf --- /dev/null +++ b/src/charon/threads/kernel_interface.c @@ -0,0 +1,1964 @@ +/** + * @file kernel_interface.c + * + * @brief Implementation of kernel_interface_t. + * + */ + +/* + * Copyright (C) 2005-2007 Martin Willi + * Copyright (C) 2006-2007 Tobias Brunner + * Copyright (C) 2006-2007 Fabian Hartmann, Noah Heusser + * Copyright (C) 2006 Daniel Roethlisberger + * Copyright (C) 2005 Jan Hutter + * Hochschule fuer Technik Rapperswil + * Copyright (C) 2003 Herbert Xu. + * + * Based on xfrm code from pluto. + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * for more details. + */ + +#include <sys/types.h> +#include <sys/socket.h> +#include <linux/netlink.h> +#include <linux/rtnetlink.h> +#include <linux/xfrm.h> +#include <linux/udp.h> +#include <pthread.h> +#include <unistd.h> +#include <fcntl.h> +#include <errno.h> +#include <string.h> +#include <net/if.h> +#include <sys/ioctl.h> + +#include "kernel_interface.h" + +#include <daemon.h> +#include <utils/linked_list.h> +#include <queues/jobs/delete_child_sa_job.h> +#include <queues/jobs/rekey_child_sa_job.h> +#include <queues/jobs/acquire_job.h> + +/** kernel level protocol identifiers */ +#define KERNEL_ESP 50 +#define KERNEL_AH 51 + +/** default priority of installed policies */ +#define PRIO_LOW 3000 +#define PRIO_HIGH 2000 + +#define BUFFER_SIZE 1024 + +/** + * returns a pointer to the first rtattr following the nlmsghdr *nlh and the + * 'usual' netlink data x like 'struct xfrm_usersa_info' + */ +#define XFRM_RTA(nlh, x) ((struct rtattr*)(NLMSG_DATA(nlh) + NLMSG_ALIGN(sizeof(x)))) +/** + * returns a pointer to the next rtattr following rta. + * !!! do not use this to parse messages. use RTA_NEXT and RTA_OK instead !!! + */ +#define XFRM_RTA_NEXT(rta) ((struct rtattr*)(((char*)(rta)) + RTA_ALIGN((rta)->rta_len))) +/** + * returns the total size of attached rta data + * (after 'usual' netlink data x like 'struct xfrm_usersa_info') + */ +#define XFRM_PAYLOAD(nlh, x) NLMSG_PAYLOAD(nlh, sizeof(x)) + +typedef struct kernel_algorithm_t kernel_algorithm_t; + +/** + * Mapping from the algorithms defined in IKEv2 to + * kernel level algorithm names and their key length + */ +struct kernel_algorithm_t { + /** + * Identifier specified in IKEv2 + */ + int ikev2_id; + + /** + * Name of the algorithm, as used as kernel identifier + */ + char *name; + + /** + * Key length in bits, if fixed size + */ + u_int key_size; +}; +#define END_OF_LIST -1 + +/** + * Algorithms for encryption + */ +kernel_algorithm_t encryption_algs[] = { +/* {ENCR_DES_IV64, "***", 0}, */ + {ENCR_DES, "des", 64}, + {ENCR_3DES, "des3_ede", 192}, +/* {ENCR_RC5, "***", 0}, */ +/* {ENCR_IDEA, "***", 0}, */ + {ENCR_CAST, "cast128", 0}, + {ENCR_BLOWFISH, "blowfish", 0}, +/* {ENCR_3IDEA, "***", 0}, */ +/* {ENCR_DES_IV32, "***", 0}, */ + {ENCR_NULL, "cipher_null", 0}, + {ENCR_AES_CBC, "aes", 0}, +/* {ENCR_AES_CTR, "***", 0}, */ + {END_OF_LIST, NULL, 0}, +}; + +/** + * Algorithms for integrity protection + */ +kernel_algorithm_t integrity_algs[] = { + {AUTH_HMAC_MD5_96, "md5", 128}, + {AUTH_HMAC_SHA1_96, "sha1", 160}, + {AUTH_HMAC_SHA2_256_128, "sha256", 256}, + {AUTH_HMAC_SHA2_384_192, "sha384", 384}, + {AUTH_HMAC_SHA2_512_256, "sha512", 512}, +/* {AUTH_DES_MAC, "***", 0}, */ +/* {AUTH_KPDK_MD5, "***", 0}, */ +/* {AUTH_AES_XCBC_96, "***", 0}, */ + {END_OF_LIST, NULL, 0}, +}; + +/** + * Look up a kernel algorithm name and its key size + */ +char* lookup_algorithm(kernel_algorithm_t *kernel_algo, + algorithm_t *ikev2_algo, u_int *key_size) +{ + while (kernel_algo->ikev2_id != END_OF_LIST) + { + if (ikev2_algo->algorithm == kernel_algo->ikev2_id) + { + /* match, evaluate key length */ + if (ikev2_algo->key_size) + { /* variable length */ + *key_size = ikev2_algo->key_size; + } + else + { /* fixed length */ + *key_size = kernel_algo->key_size; + } + return kernel_algo->name; + } + kernel_algo++; + } + return NULL; +} + +typedef struct route_entry_t route_entry_t; + +/** + * installed routing entry + */ +struct route_entry_t { + + /** Index of the interface the route is bound to */ + int if_index; + + /** Source ip of the route */ + host_t *src_ip; + + /** Destination net */ + chunk_t dst_net; + + /** Destination net prefixlen */ + u_int8_t prefixlen; +}; + +/** + * destroy an route_entry_t object + */ +static void route_entry_destroy(route_entry_t *this) +{ + this->src_ip->destroy(this->src_ip); + chunk_free(&this->dst_net); + free(this); +} + +typedef struct policy_entry_t policy_entry_t; + +/** + * installed kernel policy. + */ +struct policy_entry_t { + + /** direction of this policy: in, out, forward */ + u_int8_t direction; + + /** reqid of the policy */ + u_int32_t reqid; + + /** parameters of installed policy */ + struct xfrm_selector sel; + + /** associated route installed for this policy */ + route_entry_t *route; + + /** by how many CHILD_SA's this policy is used */ + u_int refcount; +}; + +typedef struct vip_entry_t vip_entry_t; + +/** + * Installed virtual ip + */ +struct vip_entry_t { + /** Index of the interface the ip is bound to */ + u_int8_t if_index; + + /** The ip address */ + host_t *ip; + + /** Number of times this IP is used */ + u_int refcount; +}; + +/** + * destroy a vip_entry_t object + */ +static void vip_entry_destroy(vip_entry_t *this) +{ + this->ip->destroy(this->ip); + free(this); +} + +typedef struct address_entry_t address_entry_t; + +/** + * an address found on the system, containg address and interface info + */ +struct address_entry_t { + + /** address of this entry */ + host_t *host; + + /** interface index */ + int ifindex; + + /** name of the index */ + char ifname[IFNAMSIZ]; +}; + +/** + * destroy an address entry + */ +static void address_entry_destroy(address_entry_t *this) +{ + this->host->destroy(this->host); + free(this); +} + +typedef struct private_kernel_interface_t private_kernel_interface_t; + +/** + * Private variables and functions of kernel_interface class. + */ +struct private_kernel_interface_t { + /** + * Public part of the kernel_interface_t object. + */ + kernel_interface_t public; + + /** + * List of installed policies (kernel_entry_t) + */ + linked_list_t *policies; + + /** + * Mutex locks access to policies + */ + pthread_mutex_t policies_mutex; + + /** + * List of installed virtual IPs. (vip_entry_t) + */ + linked_list_t *vips; + + /** + * Mutex to lock access to vips. + */ + pthread_mutex_t vips_mutex; + + /** + * netlink xfrm socket to receive acquire and expire events + */ + int socket_xfrm_events; + + /** + * Netlink xfrm socket (IPsec) + */ + int socket_xfrm; + + /** + * Netlink rt socket (routing) + */ + int socket_rt; + + /** + * Thread receiving events from kernel + */ + pthread_t event_thread; +}; + +/** + * convert a host_t to a struct xfrm_address + */ +static void host2xfrm(host_t *host, xfrm_address_t *xfrm) +{ + chunk_t chunk = host->get_address(host); + memcpy(xfrm, chunk.ptr, min(chunk.len, sizeof(xfrm_address_t))); +} + +/** + * convert a traffic selector address range to subnet and its mask. + */ +static void ts2subnet(traffic_selector_t* ts, + xfrm_address_t *net, u_int8_t *mask) +{ + /* there is no way to do this cleanly, as the address range may + * be anything else but a subnet. We use from_addr as subnet + * and try to calculate a usable subnet mask. + */ + int byte, bit; + bool found = FALSE; + chunk_t from, to; + size_t size = (ts->get_type(ts) == TS_IPV4_ADDR_RANGE) ? 4 : 16; + + from = ts->get_from_address(ts); + to = ts->get_to_address(ts); + + *mask = (size * 8); + /* go trough all bits of the addresses, beginning in the front. + * as long as they are equal, the subnet gets larger + */ + for (byte = 0; byte < size; byte++) + { + for (bit = 7; bit >= 0; bit--) + { + if ((1<<bit & from.ptr[byte]) != (1<<bit & to.ptr[byte])) + { + *mask = ((7 - bit) + (byte * 8)); + found = TRUE; + break; + } + } + if (found) + { + break; + } + } + memcpy(net, from.ptr, from.len); + chunk_free(&from); + chunk_free(&to); +} + +/** + * convert a traffic selector port range to port/portmask + */ +static void ts2ports(traffic_selector_t* ts, + u_int16_t *port, u_int16_t *mask) +{ + /* linux does not seem to accept complex portmasks. Only + * any or a specific port is allowed. We set to any, if we have + * a port range, or to a specific, if we have one port only. + */ + u_int16_t from, to; + + from = ts->get_from_port(ts); + to = ts->get_to_port(ts); + + if (from == to) + { + *port = htons(from); + *mask = ~0; + } + else + { + *port = 0; + *mask = 0; + } +} + +/** + * convert a pair of traffic_selectors to a xfrm_selector + */ +static struct xfrm_selector ts2selector(traffic_selector_t *src, + traffic_selector_t *dst) +{ + struct xfrm_selector sel; + + memset(&sel, 0, sizeof(sel)); + sel.family = src->get_type(src) == TS_IPV4_ADDR_RANGE ? AF_INET : AF_INET6; + /* src or dest proto may be "any" (0), use more restrictive one */ + sel.proto = max(src->get_protocol(src), dst->get_protocol(dst)); + ts2subnet(dst, &sel.daddr, &sel.prefixlen_d); + ts2subnet(src, &sel.saddr, &sel.prefixlen_s); + ts2ports(dst, &sel.dport, &sel.dport_mask); + ts2ports(src, &sel.sport, &sel.sport_mask); + sel.ifindex = 0; + sel.user = 0; + + return sel; +} + +/** + * Creates an rtattr and adds it to the netlink message + */ +static void add_attribute(struct nlmsghdr *hdr, int rta_type, chunk_t data, + size_t buflen) +{ + struct rtattr *rta; + + if (NLMSG_ALIGN(hdr->nlmsg_len) + RTA_ALIGN(data.len) > buflen) + { + DBG1(DBG_KNL, "unable to add attribute, buffer too small"); + return; + } + + rta = (struct rtattr*)(((char*)hdr) + NLMSG_ALIGN(hdr->nlmsg_len)); + rta->rta_type = rta_type; + rta->rta_len = RTA_LENGTH(data.len); + memcpy(RTA_DATA(rta), data.ptr, data.len); + hdr->nlmsg_len = NLMSG_ALIGN(hdr->nlmsg_len) + rta->rta_len; +} + +/** + * Receives events from kernel + */ +static void receive_events(private_kernel_interface_t *this) +{ + while(TRUE) + { + unsigned char response[512]; + struct nlmsghdr *hdr; + struct sockaddr_nl addr; + socklen_t addr_len = sizeof(addr); + int len; + + hdr = (struct nlmsghdr*)response; + len = recvfrom(this->socket_xfrm_events, response, sizeof(response), + 0, (struct sockaddr*)&addr, &addr_len); + if (len < 0) + { + if (errno == EINTR) + { + /* interrupted, try again */ + continue; + } + charon->kill(charon, "unable to receive netlink events"); + } + + if (!NLMSG_OK(hdr, len)) + { + /* bad netlink message */ + continue; + } + + if (addr.nl_pid != 0) + { + /* not from kernel. not interested, try another one */ + continue; + } + + /* we handle ACQUIRE and EXPIRE messages directly */ + if (hdr->nlmsg_type == XFRM_MSG_ACQUIRE) + { + u_int32_t reqid = 0; + job_t *job; + struct rtattr *rtattr = XFRM_RTA(hdr, struct xfrm_user_acquire); + size_t rtsize = XFRM_PAYLOAD(hdr, struct xfrm_user_tmpl); + if (RTA_OK(rtattr, rtsize)) + { + if (rtattr->rta_type == XFRMA_TMPL) + { + struct xfrm_user_tmpl* tmpl = (struct xfrm_user_tmpl*)RTA_DATA(rtattr); + reqid = tmpl->reqid; + } + } + if (reqid == 0) + { + DBG1(DBG_KNL, "received a XFRM_MSG_ACQUIRE, but no reqid found"); + } + else + { + DBG2(DBG_KNL, "received a XFRM_MSG_ACQUIRE"); + DBG1(DBG_KNL, "creating acquire job for CHILD_SA with reqid %d", + reqid); + job = (job_t*)acquire_job_create(reqid); + charon->job_queue->add(charon->job_queue, job); + } + } + else if (hdr->nlmsg_type == XFRM_MSG_EXPIRE) + { + job_t *job; + protocol_id_t protocol; + u_int32_t spi, reqid; + struct xfrm_user_expire *expire; + + expire = (struct xfrm_user_expire*)NLMSG_DATA(hdr); + protocol = expire->state.id.proto == KERNEL_ESP ? + PROTO_ESP : PROTO_AH; + spi = expire->state.id.spi; + reqid = expire->state.reqid; + + DBG2(DBG_KNL, "received a XFRM_MSG_EXPIRE"); + DBG1(DBG_KNL, "creating %s job for %N CHILD_SA 0x%x (reqid %d)", + expire->hard ? "delete" : "rekey", protocol_id_names, + protocol, ntohl(spi), reqid); + if (expire->hard) + { + job = (job_t*)delete_child_sa_job_create(reqid, protocol, spi); + } + else + { + job = (job_t*)rekey_child_sa_job_create(reqid, protocol, spi); + } + charon->job_queue->add(charon->job_queue, job); + } + } +} + +/** + * send a netlink message and wait for a reply + */ +static status_t netlink_send(int socket, struct nlmsghdr *in, + struct nlmsghdr **out, size_t *out_len) +{ + int len, addr_len; + struct sockaddr_nl addr; + chunk_t result = chunk_empty, tmp; + struct nlmsghdr *msg, peek; + + static int seq = 200; + static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; + + + pthread_mutex_lock(&mutex); + + in->nlmsg_seq = ++seq; + in->nlmsg_pid = getpid(); + + memset(&addr, 0, sizeof(addr)); + addr.nl_family = AF_NETLINK; + addr.nl_pid = 0; + addr.nl_groups = 0; + + while (TRUE) + { + len = sendto(socket, in, in->nlmsg_len, 0, + (struct sockaddr*)&addr, sizeof(addr)); + + if (len != in->nlmsg_len) + { + if (errno == EINTR) + { + /* interrupted, try again */ + continue; + } + pthread_mutex_unlock(&mutex); + DBG1(DBG_KNL, "error sending to netlink socket: %m"); + return FAILED; + } + break; + } + + while (TRUE) + { + char buf[1024]; + tmp.len = sizeof(buf); + tmp.ptr = buf; + msg = (struct nlmsghdr*)tmp.ptr; + + memset(&addr, 0, sizeof(addr)); + addr.nl_family = AF_NETLINK; + addr.nl_pid = getpid(); + addr.nl_groups = 0; + addr_len = sizeof(addr); + + len = recvfrom(socket, tmp.ptr, tmp.len, 0, + (struct sockaddr*)&addr, &addr_len); + + if (len < 0) + { + if (errno == EINTR) + { + DBG1(DBG_IKE, "got interrupted"); + /* interrupted, try again */ + continue; + } + DBG1(DBG_IKE, "error reading from netlink socket: %m"); + pthread_mutex_unlock(&mutex); + return FAILED; + } + if (!NLMSG_OK(msg, len)) + { + DBG1(DBG_IKE, "received corrupted netlink message"); + pthread_mutex_unlock(&mutex); + return FAILED; + } + if (msg->nlmsg_seq != seq) + { + DBG1(DBG_IKE, "received invalid netlink sequence number"); + if (msg->nlmsg_seq < seq) + { + continue; + } + pthread_mutex_unlock(&mutex); + return FAILED; + } + + tmp.len = len; + result = chunk_cata("cc", result, tmp); + + /* NLM_F_MULTI flag does not seem to be set correctly, we use sequence + * numbers to detect multi header messages */ + len = recvfrom(socket, &peek, sizeof(peek), MSG_PEEK | MSG_DONTWAIT, + (struct sockaddr*)&addr, &addr_len); + + if (len == sizeof(peek) && peek.nlmsg_seq == seq) + { + /* seems to be multipart */ + continue; + } + break; + } + + *out_len = result.len; + *out = (struct nlmsghdr*)clalloc(result.ptr, result.len); + + pthread_mutex_unlock(&mutex); + + return SUCCESS; +} + +/** + * send a netlink message and wait for its acknowlegde + */ +static status_t netlink_send_ack(int socket, struct nlmsghdr *in) +{ + struct nlmsghdr *out, *hdr; + size_t len; + + if (netlink_send(socket, in, &out, &len) != SUCCESS) + { + return FAILED; + } + hdr = out; + while (NLMSG_OK(hdr, len)) + { + switch (hdr->nlmsg_type) + { + case NLMSG_ERROR: + { + struct nlmsgerr* err = (struct nlmsgerr*)NLMSG_DATA(hdr); + + if (err->error) + { + DBG1(DBG_KNL, "received netlink error: %s (%d)", + strerror(-err->error), -err->error); + free(out); + return FAILED; + } + free(out); + return SUCCESS; + } + default: + hdr = NLMSG_NEXT(hdr, len); + continue; + case NLMSG_DONE: + break; + } + break; + } + DBG1(DBG_KNL, "netlink request not acknowlegded"); + free(out); + return FAILED; +} + +/** + * Create a list of local addresses. + */ +static linked_list_t *create_address_list(private_kernel_interface_t *this) +{ + char request[BUFFER_SIZE]; + struct nlmsghdr *out, *hdr; + struct rtgenmsg *msg; + size_t len; + linked_list_t *list; + + DBG2(DBG_IKE, "getting local address list"); + + list = linked_list_create(); + + memset(&request, 0, sizeof(request)); + + hdr = (struct nlmsghdr*)&request; + hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtgenmsg)); + hdr->nlmsg_type = RTM_GETADDR; + hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_MATCH | NLM_F_ROOT; + msg = (struct rtgenmsg*)NLMSG_DATA(hdr); + msg->rtgen_family = AF_UNSPEC; + + if (netlink_send(this->socket_rt, hdr, &out, &len) == SUCCESS) + { + hdr = out; + while (NLMSG_OK(hdr, len)) + { + switch (hdr->nlmsg_type) + { + case RTM_NEWADDR: + { + struct ifaddrmsg* msg = (struct ifaddrmsg*)(NLMSG_DATA(hdr)); + struct rtattr *rta = IFA_RTA(msg); + size_t rtasize = IFA_PAYLOAD (hdr); + host_t *host = NULL; + char *name = NULL; + chunk_t local = chunk_empty, address = chunk_empty; + + while(RTA_OK(rta, rtasize)) + { + switch (rta->rta_type) + { + case IFA_LOCAL: + local.ptr = RTA_DATA(rta); + local.len = RTA_PAYLOAD(rta); + break; + case IFA_ADDRESS: + address.ptr = RTA_DATA(rta); + address.len = RTA_PAYLOAD(rta); + break; + case IFA_LABEL: + name = RTA_DATA(rta); + break; + } + rta = RTA_NEXT(rta, rtasize); + } + + /* For PPP interfaces, we need the IFA_LOCAL address, + * IFA_ADDRESS is the peers address. But IFA_LOCAL is + * not included in all cases, so fallback to IFA_ADDRESS. */ + if (local.ptr) + { + host = host_create_from_chunk(msg->ifa_family, local, 0); + } + else if (address.ptr) + { + host = host_create_from_chunk(msg->ifa_family, address, 0); + } + + if (host) + { + address_entry_t *entry; + + entry = malloc_thing(address_entry_t); + entry->host = host; + entry->ifindex = msg->ifa_index; + if (name) + { + memcpy(entry->ifname, name, IFNAMSIZ); + } + else + { + strcpy(entry->ifname, "(unknown)"); + } + list->insert_last(list, entry); + } + hdr = NLMSG_NEXT(hdr, len); + continue; + } + default: + hdr = NLMSG_NEXT(hdr, len); + continue; + case NLMSG_DONE: + break; + } + break; + } + free(out); + } + else + { + DBG1(DBG_IKE, "unable to get local address list"); + } + + return list; +} + +/** + * Implements kernel_interface_t.create_address_list. + */ +static linked_list_t *create_address_list_public(private_kernel_interface_t *this) +{ + linked_list_t *result, *list; + address_entry_t *entry; + + result = linked_list_create(); + list = create_address_list(this); + while (list->remove_last(list, (void**)&entry) == SUCCESS) + { + result->insert_last(result, entry->host); + free(entry); + } + list->destroy(list); + + return result; +} + +/** + * implementation of kernel_interface_t.get_interface_name + */ +static char *get_interface_name(private_kernel_interface_t *this, host_t* ip) +{ + linked_list_t *list; + address_entry_t *entry; + char *name = NULL; + + DBG2(DBG_IKE, "getting interface name for %H", ip); + + list = create_address_list(this); + while (!name && list->remove_last(list, (void**)&entry) == SUCCESS) + { + if (ip->ip_equals(ip, entry->host)) + { + name = strdup(entry->ifname); + } + address_entry_destroy(entry); + } + list->destroy_function(list, (void*)address_entry_destroy); + + if (name) + { + DBG2(DBG_IKE, "%H is on interface %s", ip, name); + } + else + { + DBG2(DBG_IKE, "%H is not a local address", ip); + } + return name; +} + +/** + * Tries to find an ip address of a local interface that is included in the + * supplied traffic selector. + */ +static status_t get_address_by_ts(private_kernel_interface_t *this, + traffic_selector_t *ts, host_t **ip) +{ + address_entry_t *entry; + host_t *host; + int family; + linked_list_t *list; + bool found = FALSE; + + DBG2(DBG_IKE, "getting a local address in traffic selector %R", ts); + + /* if we have a family which includes localhost, we do not + * search for an IP, we use the default */ + family = ts->get_type(ts) == TS_IPV4_ADDR_RANGE ? AF_INET : AF_INET6; + + if (family == AF_INET) + { + host = host_create_from_string("127.0.0.1", 0); + } + else + { + host = host_create_from_string("::1", 0); + } + + if (ts->includes(ts, host)) + { + *ip = host_create_any(family); + host->destroy(host); + DBG2(DBG_IKE, "using host %H", *ip); + return SUCCESS; + } + host->destroy(host); + + list = create_address_list(this); + while (!found && list->remove_last(list, (void**)&entry) == SUCCESS) + { + if (ts->includes(ts, entry->host)) + { + found = TRUE; + *ip = entry->host->clone(entry->host); + } + address_entry_destroy(entry); + } + list->destroy_function(list, (void*)address_entry_destroy); + + if (!found) + { + DBG1(DBG_IKE, "no local address found in traffic selector %R", ts); + return FAILED; + } + DBG2(DBG_IKE, "using host %H", *ip); + return SUCCESS; +} + +/** + * get the interface of a local address + */ +static int get_interface_index(private_kernel_interface_t *this, host_t* ip) +{ + linked_list_t *list; + address_entry_t *entry; + int ifindex = 0; + + DBG2(DBG_IKE, "getting iface for %H", ip); + + list = create_address_list(this); + while (!ifindex && list->remove_last(list, (void**)&entry) == SUCCESS) + { + if (ip->ip_equals(ip, entry->host)) + { + ifindex = entry->ifindex; + } + address_entry_destroy(entry); + } + list->destroy_function(list, (void*)address_entry_destroy); + + if (ifindex == 0) + { + DBG1(DBG_IKE, "unable to get interface for %H", ip); + } + return ifindex; +} + +/** + * Manages the creation and deletion of ip addresses on an interface. + * By setting the appropriate nlmsg_type, the ip will be set or unset. + */ +static status_t manage_ipaddr(private_kernel_interface_t *this, int nlmsg_type, + int flags, int if_index, host_t *ip) +{ + unsigned char request[BUFFER_SIZE]; + struct nlmsghdr *hdr; + struct ifaddrmsg *msg; + chunk_t chunk; + + memset(&request, 0, sizeof(request)); + + chunk = ip->get_address(ip); + + hdr = (struct nlmsghdr*)request; + hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | flags; + hdr->nlmsg_type = nlmsg_type; + hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct ifaddrmsg)); + + msg = (struct ifaddrmsg*)NLMSG_DATA(hdr); + msg->ifa_family = ip->get_family(ip); + msg->ifa_flags = 0; + msg->ifa_prefixlen = 8 * chunk.len; + msg->ifa_scope = RT_SCOPE_UNIVERSE; + msg->ifa_index = if_index; + + add_attribute(hdr, IFA_LOCAL, chunk, sizeof(request)); + + return netlink_send_ack(this->socket_rt, hdr); +} + +/** + * Manages source routes in the routing table. + * By setting the appropriate nlmsg_type, the route added or r. + */ +static status_t manage_srcroute(private_kernel_interface_t *this, int nlmsg_type, + int flags, route_entry_t *route) +{ + unsigned char request[BUFFER_SIZE]; + struct nlmsghdr *hdr; + struct rtmsg *msg; + chunk_t chunk; + + /* if route is 0.0.0.0/0, we can't install it, as it would + * overwrite the default route. Instead, we add two routes: + * 0.0.0.0/1 and 128.0.0.0/1 + * TODO: use metrics instead */ + if (route->prefixlen == 0) + { + route_entry_t half; + status_t status; + + half.dst_net = chunk_alloca(route->dst_net.len); + memset(half.dst_net.ptr, 0, half.dst_net.len); + half.src_ip = route->src_ip; + half.if_index = route->if_index; + half.prefixlen = 1; + + status = manage_srcroute(this, nlmsg_type, flags, &half); + half.dst_net.ptr[0] |= 0x80; + status = manage_srcroute(this, nlmsg_type, flags, &half); + return status; + } + + memset(&request, 0, sizeof(request)); + + hdr = (struct nlmsghdr*)request; + hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | flags; + hdr->nlmsg_type = nlmsg_type; + hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg)); + + msg = (struct rtmsg*)NLMSG_DATA(hdr); + msg->rtm_family = route->src_ip->get_family(route->src_ip); + msg->rtm_dst_len = route->prefixlen; + msg->rtm_table = RT_TABLE_MAIN; + msg->rtm_protocol = RTPROT_STATIC; + msg->rtm_type = RTN_UNICAST; + msg->rtm_scope = RT_SCOPE_UNIVERSE; + + add_attribute(hdr, RTA_DST, route->dst_net, sizeof(request)); + chunk = route->src_ip->get_address(route->src_ip); + add_attribute(hdr, RTA_PREFSRC, chunk, sizeof(request)); + chunk.ptr = (char*)&route->if_index; + chunk.len = sizeof(route->if_index); + add_attribute(hdr, RTA_OIF, chunk, sizeof(request)); + + return netlink_send_ack(this->socket_rt, hdr); +} + + +/** + * Implementation of kernel_interface_t.add_ip. + */ +static status_t add_ip(private_kernel_interface_t *this, + host_t *virtual_ip, host_t *iface_ip) +{ + int targetif; + vip_entry_t *listed; + iterator_t *iterator; + + DBG2(DBG_KNL, "adding virtual IP %H", virtual_ip); + + targetif = get_interface_index(this, iface_ip); + if (targetif == 0) + { + DBG1(DBG_KNL, "unable to add virtual IP %H, no iface found for %H", + virtual_ip, iface_ip); + return FAILED; + } + + /* beware of deadlocks (e.g. send/receive packets while holding the lock) */ + iterator = this->vips->create_iterator_locked(this->vips, &(this->vips_mutex)); + while (iterator->iterate(iterator, (void**)&listed)) + { + if (listed->if_index == targetif && + virtual_ip->ip_equals(virtual_ip, listed->ip)) + { + listed->refcount++; + iterator->destroy(iterator); + DBG2(DBG_KNL, "virtual IP %H already added to iface %d reusing it", + virtual_ip, targetif); + return SUCCESS; + } + } + iterator->destroy(iterator); + + if (manage_ipaddr(this, RTM_NEWADDR, NLM_F_CREATE | NLM_F_EXCL, + targetif, virtual_ip) == SUCCESS) + { + listed = malloc_thing(vip_entry_t); + listed->ip = virtual_ip->clone(virtual_ip); + listed->if_index = targetif; + listed->refcount = 1; + this->vips->insert_last(this->vips, listed); + DBG2(DBG_KNL, "virtual IP %H added to iface %d", + virtual_ip, targetif); + return SUCCESS; + } + + DBG2(DBG_KNL, "unable to add virtual IP %H to iface %d", + virtual_ip, targetif); + return FAILED; +} + +/** + * Implementation of kernel_interface_t.del_ip. + */ +static status_t del_ip(private_kernel_interface_t *this, + host_t *virtual_ip, host_t *iface_ip) +{ + int targetif; + vip_entry_t *listed; + iterator_t *iterator; + + DBG2(DBG_KNL, "deleting virtual IP %H", virtual_ip); + + targetif = get_interface_index(this, iface_ip); + if (targetif == 0) + { + DBG1(DBG_KNL, "unable to delete virtual IP %H, no iface found for %H", + virtual_ip, iface_ip); + return FAILED; + } + + /* beware of deadlocks (e.g. send/receive packets while holding the lock) */ + iterator = this->vips->create_iterator_locked(this->vips, &(this->vips_mutex)); + while (iterator->iterate(iterator, (void**)&listed)) + { + if (listed->if_index == targetif && + virtual_ip->ip_equals(virtual_ip, listed->ip)) + { + listed->refcount--; + if (listed->refcount == 0) + { + iterator->remove(iterator); + vip_entry_destroy(listed); + iterator->destroy(iterator); + return manage_ipaddr(this, RTM_DELADDR, 0, targetif, virtual_ip); + } + iterator->destroy(iterator); + DBG2(DBG_KNL, "virtual IP %H used by other SAs, not deleting", + virtual_ip); + return SUCCESS; + } + } + iterator->destroy(iterator); + + DBG2(DBG_KNL, "virtual IP %H not cached, unable to delete", virtual_ip); + return FAILED; +} + +/** + * Implementation of kernel_interface_t.get_spi. + */ +static status_t get_spi(private_kernel_interface_t *this, + host_t *src, host_t *dst, + protocol_id_t protocol, u_int32_t reqid, + u_int32_t *spi) +{ + unsigned char request[BUFFER_SIZE]; + struct nlmsghdr *hdr, *out; + struct xfrm_userspi_info *userspi; + u_int32_t received_spi = 0; + size_t len; + + memset(&request, 0, sizeof(request)); + + DBG2(DBG_KNL, "getting SPI for reqid %d", reqid); + + hdr = (struct nlmsghdr*)request; + hdr->nlmsg_flags = NLM_F_REQUEST; + hdr->nlmsg_type = XFRM_MSG_ALLOCSPI; + hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userspi_info)); + + userspi = (struct xfrm_userspi_info*)NLMSG_DATA(hdr); + host2xfrm(src, &userspi->info.saddr); + host2xfrm(dst, &userspi->info.id.daddr); + userspi->info.id.proto = (protocol == PROTO_ESP) ? KERNEL_ESP : KERNEL_AH; + userspi->info.mode = TRUE; /* tunnel mode */ + userspi->info.reqid = reqid; + userspi->info.family = src->get_family(src); + userspi->min = 0xc0000000; + userspi->max = 0xcFFFFFFF; + + if (netlink_send(this->socket_xfrm, hdr, &out, &len) == SUCCESS) + { + hdr = out; + while (NLMSG_OK(hdr, len)) + { + switch (hdr->nlmsg_type) + { + case XFRM_MSG_NEWSA: + { + struct xfrm_usersa_info* usersa = NLMSG_DATA(hdr); + received_spi = usersa->id.spi; + break; + } + case NLMSG_ERROR: + { + struct nlmsgerr *err = NLMSG_DATA(hdr); + + DBG1(DBG_KNL, "allocating SPI failed: %s (%d)", + strerror(-err->error), -err->error); + break; + } + default: + hdr = NLMSG_NEXT(hdr, len); + continue; + case NLMSG_DONE: + break; + } + break; + } + free(out); + } + + if (received_spi == 0) + { + DBG1(DBG_KNL, "unable to get SPI for reqid %d", reqid); + return FAILED; + } + + DBG2(DBG_KNL, "got SPI 0x%x for reqid %d", received_spi, reqid); + + *spi = received_spi; + return SUCCESS; +} + +/** + * Implementation of kernel_interface_t.add_sa. + */ +static status_t add_sa(private_kernel_interface_t *this, + host_t *src, host_t *dst, u_int32_t spi, + protocol_id_t protocol, u_int32_t reqid, + u_int64_t expire_soft, u_int64_t expire_hard, + algorithm_t *enc_alg, algorithm_t *int_alg, + prf_plus_t *prf_plus, natt_conf_t *natt, mode_t mode, + bool replace) +{ + unsigned char request[BUFFER_SIZE]; + char *alg_name; + u_int key_size; + struct nlmsghdr *hdr; + struct xfrm_usersa_info *sa; + + memset(&request, 0, sizeof(request)); + + DBG2(DBG_KNL, "adding SAD entry with SPI 0x%x", spi); + + hdr = (struct nlmsghdr*)request; + hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK; + hdr->nlmsg_type = replace ? XFRM_MSG_UPDSA : XFRM_MSG_NEWSA; + hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_info)); + + sa = (struct xfrm_usersa_info*)NLMSG_DATA(hdr); + host2xfrm(src, &sa->saddr); + host2xfrm(dst, &sa->id.daddr); + sa->id.spi = spi; + sa->id.proto = (protocol == PROTO_ESP) ? KERNEL_ESP : KERNEL_AH; + sa->family = src->get_family(src); + sa->mode = mode; + sa->replay_window = 32; + sa->reqid = reqid; + /* we currently do not expire SAs by volume/packet count */ + sa->lft.soft_byte_limit = XFRM_INF; + sa->lft.hard_byte_limit = XFRM_INF; + sa->lft.soft_packet_limit = XFRM_INF; + sa->lft.hard_packet_limit = XFRM_INF; + /* we use lifetimes since added, not since used */ + sa->lft.soft_add_expires_seconds = expire_soft; + sa->lft.hard_add_expires_seconds = expire_hard; + sa->lft.soft_use_expires_seconds = 0; + sa->lft.hard_use_expires_seconds = 0; + + struct rtattr *rthdr = XFRM_RTA(hdr, struct xfrm_usersa_info); + + if (enc_alg->algorithm != ENCR_UNDEFINED) + { + rthdr->rta_type = XFRMA_ALG_CRYPT; + alg_name = lookup_algorithm(encryption_algs, enc_alg, &key_size); + if (alg_name == NULL) + { + DBG1(DBG_KNL, "algorithm %N not supported by kernel!", + encryption_algorithm_names, enc_alg->algorithm); + return FAILED; + } + DBG2(DBG_KNL, " using encryption algorithm %N with key size %d", + encryption_algorithm_names, enc_alg->algorithm, key_size); + + rthdr->rta_len = RTA_LENGTH(sizeof(struct xfrm_algo) + key_size); + hdr->nlmsg_len += rthdr->rta_len; + if (hdr->nlmsg_len > sizeof(request)) + { + return FAILED; + } + + struct xfrm_algo* algo = (struct xfrm_algo*)RTA_DATA(rthdr); + algo->alg_key_len = key_size; + strcpy(algo->alg_name, alg_name); + prf_plus->get_bytes(prf_plus, key_size / 8, algo->alg_key); + + rthdr = XFRM_RTA_NEXT(rthdr); + } + + if (int_alg->algorithm != AUTH_UNDEFINED) + { + rthdr->rta_type = XFRMA_ALG_AUTH; + alg_name = lookup_algorithm(integrity_algs, int_alg, &key_size); + if (alg_name == NULL) + { + DBG1(DBG_KNL, "algorithm %N not supported by kernel!", + integrity_algorithm_names, int_alg->algorithm); + return FAILED; + } + DBG2(DBG_KNL, " using integrity algorithm %N with key size %d", + integrity_algorithm_names, int_alg->algorithm, key_size); + + rthdr->rta_len = RTA_LENGTH(sizeof(struct xfrm_algo) + key_size); + hdr->nlmsg_len += rthdr->rta_len; + if (hdr->nlmsg_len > sizeof(request)) + { + return FAILED; + } + + struct xfrm_algo* algo = (struct xfrm_algo*)RTA_DATA(rthdr); + algo->alg_key_len = key_size; + strcpy(algo->alg_name, alg_name); + prf_plus->get_bytes(prf_plus, key_size / 8, algo->alg_key); + + rthdr = XFRM_RTA_NEXT(rthdr); + } + + /* TODO: add IPComp here */ + + if (natt) + { + rthdr->rta_type = XFRMA_ENCAP; + rthdr->rta_len = RTA_LENGTH(sizeof(struct xfrm_encap_tmpl)); + + hdr->nlmsg_len += rthdr->rta_len; + if (hdr->nlmsg_len > sizeof(request)) + { + return FAILED; + } + + struct xfrm_encap_tmpl* encap = (struct xfrm_encap_tmpl*)RTA_DATA(rthdr); + encap->encap_type = UDP_ENCAP_ESPINUDP; + encap->encap_sport = htons(natt->sport); + encap->encap_dport = htons(natt->dport); + memset(&encap->encap_oa, 0, sizeof (xfrm_address_t)); + /* encap_oa could probably be derived from the + * traffic selectors [rfc4306, p39]. In the netlink kernel implementation + * pluto does the same as we do here but it uses encap_oa in the + * pfkey implementation. BUT as /usr/src/linux/net/key/af_key.c indicates + * the kernel ignores it anyway + * -> does that mean that NAT-T encap doesn't work in transport mode? + * No. The reason the kernel ignores NAT-OA is that it recomputes + * (or, rather, just ignores) the checksum. If packets pass + * the IPsec checks it marks them "checksum ok" so OA isn't needed. */ + rthdr = XFRM_RTA_NEXT(rthdr); + } + + if (netlink_send_ack(this->socket_xfrm, hdr) != SUCCESS) + { + DBG1(DBG_KNL, "unalbe to add SAD entry with SPI 0x%x", spi); + return FAILED; + } + return SUCCESS; +} + +/** + * Implementation of kernel_interface_t.update_sa. + */ +static status_t update_sa(private_kernel_interface_t *this, + host_t *src, host_t *dst, + host_t *new_src, host_t *new_dst, + host_diff_t src_changes, host_diff_t dst_changes, + u_int32_t spi, protocol_id_t protocol) +{ + unsigned char request[BUFFER_SIZE]; + struct nlmsghdr *hdr, *out = NULL; + struct xfrm_usersa_id *sa_id; + struct xfrm_usersa_info *sa = NULL; + size_t len; + + memset(&request, 0, sizeof(request)); + + DBG2(DBG_KNL, "querying SAD entry with SPI 0x%x", spi); + + hdr = (struct nlmsghdr*)request; + hdr->nlmsg_flags = NLM_F_REQUEST; + hdr->nlmsg_type = XFRM_MSG_GETSA; + hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_id)); + + sa_id = (struct xfrm_usersa_id*)NLMSG_DATA(hdr); + host2xfrm(dst, &sa_id->daddr); + sa_id->spi = spi; + sa_id->proto = (protocol == PROTO_ESP) ? KERNEL_ESP : KERNEL_AH; + sa_id->family = dst->get_family(dst); + + if (netlink_send(this->socket_xfrm, hdr, &out, &len) == SUCCESS) + { + hdr = out; + while (NLMSG_OK(hdr, len)) + { + switch (hdr->nlmsg_type) + { + case XFRM_MSG_NEWSA: + { + sa = NLMSG_DATA(hdr); + break; + } + case NLMSG_ERROR: + { + struct nlmsgerr *err = NLMSG_DATA(hdr); + DBG1(DBG_KNL, "querying SAD entry failed: %s (%d)", + strerror(-err->error), -err->error); + break; + } + default: + hdr = NLMSG_NEXT(hdr, len); + continue; + case NLMSG_DONE: + break; + } + break; + } + } + if (sa == NULL) + { + DBG1(DBG_KNL, "unable to update SAD entry with SPI 0x%x", spi); + free(out); + return FAILED; + } + + DBG2(DBG_KNL, "updating SAD entry with SPI 0x%x", spi); + + hdr = out; + hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK; + hdr->nlmsg_type = XFRM_MSG_UPDSA; + + if (src_changes & HOST_DIFF_ADDR) + { + host2xfrm(new_src, &sa->saddr); + } + + if (dst_changes & HOST_DIFF_ADDR) + { + hdr->nlmsg_type = XFRM_MSG_NEWSA; + host2xfrm(new_dst, &sa->id.daddr); + } + + if (src_changes & HOST_DIFF_PORT || dst_changes & HOST_DIFF_PORT) + { + struct rtattr *rtattr = XFRM_RTA(hdr, struct xfrm_usersa_info); + size_t rtsize = XFRM_PAYLOAD(hdr, struct xfrm_usersa_info); + while (RTA_OK(rtattr, rtsize)) + { + if (rtattr->rta_type == XFRMA_ENCAP) + { + struct xfrm_encap_tmpl* encap; + encap = (struct xfrm_encap_tmpl*)RTA_DATA(rtattr); + encap->encap_sport = ntohs(new_src->get_port(new_src)); + encap->encap_dport = ntohs(new_dst->get_port(new_dst)); + break; + } + rtattr = RTA_NEXT(rtattr, rtsize); + } + } + if (netlink_send_ack(this->socket_xfrm, hdr) != SUCCESS) + { + DBG1(DBG_KNL, "unalbe to update SAD entry with SPI 0x%x", spi); + free(out); + return FAILED; + } + free(out); + + if (dst_changes & HOST_DIFF_ADDR) + { + return this->public.del_sa(&this->public, dst, spi, protocol); + } + return SUCCESS; +} + +/** + * Implementation of kernel_interface_t.query_sa. + */ +static status_t query_sa(private_kernel_interface_t *this, host_t *dst, + u_int32_t spi, protocol_id_t protocol, + u_int32_t *use_time) +{ + unsigned char request[BUFFER_SIZE]; + struct nlmsghdr *out = NULL, *hdr; + struct xfrm_usersa_id *sa_id; + struct xfrm_usersa_info *sa = NULL; + size_t len; + + DBG2(DBG_KNL, "querying SAD entry with SPI 0x%x", spi); + memset(&request, 0, sizeof(request)); + + hdr = (struct nlmsghdr*)request; + hdr->nlmsg_flags = NLM_F_REQUEST; + hdr->nlmsg_type = XFRM_MSG_GETSA; + hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_info)); + + sa_id = (struct xfrm_usersa_id*)NLMSG_DATA(hdr); + host2xfrm(dst, &sa_id->daddr); + sa_id->spi = spi; + sa_id->proto = (protocol == PROTO_ESP) ? KERNEL_ESP : KERNEL_AH; + sa_id->family = dst->get_family(dst); + + if (netlink_send(this->socket_xfrm, hdr, &out, &len) == SUCCESS) + { + hdr = out; + while (NLMSG_OK(hdr, len)) + { + switch (hdr->nlmsg_type) + { + case XFRM_MSG_NEWSA: + { + sa = NLMSG_DATA(hdr); + break; + } + case NLMSG_ERROR: + { + struct nlmsgerr *err = NLMSG_DATA(hdr); + DBG1(DBG_KNL, "querying SAD entry failed: %s (%d)", + strerror(-err->error), -err->error); + break; + } + default: + hdr = NLMSG_NEXT(hdr, len); + continue; + case NLMSG_DONE: + break; + } + break; + } + } + + if (sa == NULL) + { + DBG1(DBG_KNL, "unable to query SAD entry with SPI 0x%x", spi); + free(out); + return FAILED; + } + + *use_time = sa->curlft.use_time; + free (out); + return SUCCESS; +} + +/** + * Implementation of kernel_interface_t.del_sa. + */ +static status_t del_sa(private_kernel_interface_t *this, host_t *dst, + u_int32_t spi, protocol_id_t protocol) +{ + unsigned char request[BUFFER_SIZE]; + struct nlmsghdr *hdr; + struct xfrm_usersa_id *sa_id; + + memset(&request, 0, sizeof(request)); + + DBG2(DBG_KNL, "deleting SAD entry with SPI 0x%x", spi); + + hdr = (struct nlmsghdr*)request; + hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK; + hdr->nlmsg_type = XFRM_MSG_DELSA; + hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_id)); + + sa_id = (struct xfrm_usersa_id*)NLMSG_DATA(hdr); + host2xfrm(dst, &sa_id->daddr); + sa_id->spi = spi; + sa_id->proto = (protocol == PROTO_ESP) ? KERNEL_ESP : KERNEL_AH; + sa_id->family = dst->get_family(dst); + + if (netlink_send_ack(this->socket_xfrm, hdr) != SUCCESS) + { + DBG1(DBG_KNL, "unalbe to delete SAD entry with SPI 0x%x", spi); + return FAILED; + } + DBG2(DBG_KNL, "deleted SAD entry with SPI 0x%x", spi); + return SUCCESS; +} + +/** + * Implementation of kernel_interface_t.add_policy. + */ +static status_t add_policy(private_kernel_interface_t *this, + host_t *src, host_t *dst, + traffic_selector_t *src_ts, + traffic_selector_t *dst_ts, + policy_dir_t direction, protocol_id_t protocol, + u_int32_t reqid, bool high_prio, mode_t mode, + bool update) +{ + iterator_t *iterator; + policy_entry_t *current, *policy; + bool found = FALSE; + unsigned char request[BUFFER_SIZE]; + struct xfrm_userpolicy_info *policy_info; + struct nlmsghdr *hdr; + + /* create a policy */ + policy = malloc_thing(policy_entry_t); + memset(policy, 0, sizeof(policy_entry_t)); + policy->sel = ts2selector(src_ts, dst_ts); + policy->direction = direction; + + /* find the policy, which matches EXACTLY */ + pthread_mutex_lock(&this->policies_mutex); + iterator = this->policies->create_iterator(this->policies, TRUE); + while (iterator->iterate(iterator, (void**)¤t)) + { + if (memcmp(¤t->sel, &policy->sel, sizeof(struct xfrm_selector)) == 0 && + policy->direction == current->direction) + { + /* use existing policy */ + if (!update) + { + current->refcount++; + DBG2(DBG_KNL, "policy %R===%R already exists, increasing ", + "refcount", src_ts, dst_ts); + } + free(policy); + policy = current; + found = TRUE; + break; + } + } + iterator->destroy(iterator); + if (!found) + { /* apply the new one, if we have no such policy */ + this->policies->insert_last(this->policies, policy); + policy->refcount = 1; + } + + DBG2(DBG_KNL, "adding policy %R===%R", src_ts, dst_ts); + + memset(&request, 0, sizeof(request)); + hdr = (struct nlmsghdr*)request; + hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK; + hdr->nlmsg_type = XFRM_MSG_UPDPOLICY; + hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userpolicy_info)); + + policy_info = (struct xfrm_userpolicy_info*)NLMSG_DATA(hdr); + policy_info->sel = policy->sel; + policy_info->dir = policy->direction; + /* calculate priority based on source selector size, small size = high prio */ + policy_info->priority = high_prio ? PRIO_HIGH : PRIO_LOW; + policy_info->priority -= policy->sel.prefixlen_s * 10; + policy_info->priority -= policy->sel.proto ? 2 : 0; + policy_info->priority -= policy->sel.sport_mask ? 1 : 0; + policy_info->action = XFRM_POLICY_ALLOW; + policy_info->share = XFRM_SHARE_ANY; + pthread_mutex_unlock(&this->policies_mutex); + + /* policies don't expire */ + policy_info->lft.soft_byte_limit = XFRM_INF; + policy_info->lft.soft_packet_limit = XFRM_INF; + policy_info->lft.hard_byte_limit = XFRM_INF; + policy_info->lft.hard_packet_limit = XFRM_INF; + policy_info->lft.soft_add_expires_seconds = 0; + policy_info->lft.hard_add_expires_seconds = 0; + policy_info->lft.soft_use_expires_seconds = 0; + policy_info->lft.hard_use_expires_seconds = 0; + + struct rtattr *rthdr = XFRM_RTA(hdr, struct xfrm_userpolicy_info); + rthdr->rta_type = XFRMA_TMPL; + + rthdr->rta_len = sizeof(struct xfrm_user_tmpl); + rthdr->rta_len = RTA_LENGTH(rthdr->rta_len); + + hdr->nlmsg_len += rthdr->rta_len; + if (hdr->nlmsg_len > sizeof(request)) + { + return FAILED; + } + + struct xfrm_user_tmpl *tmpl = (struct xfrm_user_tmpl*)RTA_DATA(rthdr); + tmpl->reqid = reqid; + tmpl->id.proto = (protocol == PROTO_AH) ? KERNEL_AH : KERNEL_ESP; + tmpl->aalgos = tmpl->ealgos = tmpl->calgos = ~0; + tmpl->mode = mode; + tmpl->family = src->get_family(src); + + host2xfrm(src, &tmpl->saddr); + host2xfrm(dst, &tmpl->id.daddr); + + if (netlink_send_ack(this->socket_xfrm, hdr) != SUCCESS) + { + DBG1(DBG_KNL, "unable to add policy %R===%R", src_ts, dst_ts); + return FAILED; + } + + /* install a route, if: + * - we are NOT updating a policy + * - this is a forward policy (to just get one for each child) + * - we are in tunnel mode + * - we are not using IPv6 (does not work correctly yet!) + */ + if (policy->route == NULL && direction == POLICY_FWD && + mode != MODE_TRANSPORT && src->get_family(src) != AF_INET6) + { + policy->route = malloc_thing(route_entry_t); + if (get_address_by_ts(this, dst_ts, &policy->route->src_ip) == SUCCESS) + { + policy->route->if_index = get_interface_index(this, dst); + policy->route->dst_net = chunk_alloc(policy->sel.family == AF_INET ? 4 : 16); + memcpy(policy->route->dst_net.ptr, &policy->sel.saddr, policy->route->dst_net.len); + policy->route->prefixlen = policy->sel.prefixlen_s; + + if (manage_srcroute(this, RTM_NEWROUTE, NLM_F_CREATE | NLM_F_EXCL, + policy->route) != SUCCESS) + { + DBG1(DBG_KNL, "unable to install source route for %H", + policy->route->src_ip); + route_entry_destroy(policy->route); + policy->route = NULL; + } + } + else + { + free(policy->route); + policy->route = NULL; + } + } + + return SUCCESS; +} + +/** + * Implementation of kernel_interface_t.query_policy. + */ +static status_t query_policy(private_kernel_interface_t *this, + traffic_selector_t *src_ts, + traffic_selector_t *dst_ts, + policy_dir_t direction, u_int32_t *use_time) +{ + unsigned char request[BUFFER_SIZE]; + struct nlmsghdr *out = NULL, *hdr; + struct xfrm_userpolicy_id *policy_id; + struct xfrm_userpolicy_info *policy = NULL; + size_t len; + + memset(&request, 0, sizeof(request)); + + DBG2(DBG_KNL, "querying policy %R===%R", src_ts, dst_ts); + + hdr = (struct nlmsghdr*)request; + hdr->nlmsg_flags = NLM_F_REQUEST; + hdr->nlmsg_type = XFRM_MSG_GETPOLICY; + hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userpolicy_id)); + + policy_id = (struct xfrm_userpolicy_id*)NLMSG_DATA(hdr); + policy_id->sel = ts2selector(src_ts, dst_ts); + policy_id->dir = direction; + + if (netlink_send(this->socket_xfrm, hdr, &out, &len) == SUCCESS) + { + hdr = out; + while (NLMSG_OK(hdr, len)) + { + switch (hdr->nlmsg_type) + { + case XFRM_MSG_NEWPOLICY: + { + policy = (struct xfrm_userpolicy_info*)NLMSG_DATA(hdr); + break; + } + case NLMSG_ERROR: + { + struct nlmsgerr *err = NLMSG_DATA(hdr); + DBG1(DBG_KNL, "querying policy failed: %s (%d)", + strerror(-err->error), -err->error); + break; + } + default: + hdr = NLMSG_NEXT(hdr, len); + continue; + case NLMSG_DONE: + break; + } + break; + } + } + + if (policy == NULL) + { + DBG2(DBG_KNL, "unable to query policy %R===%R", src_ts, dst_ts); + free(out); + return FAILED; + } + *use_time = (time_t)policy->curlft.use_time; + + free(out); + return SUCCESS; +} + +/** + * Implementation of kernel_interface_t.del_policy. + */ +static status_t del_policy(private_kernel_interface_t *this, + traffic_selector_t *src_ts, + traffic_selector_t *dst_ts, + policy_dir_t direction) +{ + policy_entry_t *current, policy, *to_delete = NULL; + route_entry_t *route; + unsigned char request[BUFFER_SIZE]; + struct nlmsghdr *hdr; + struct xfrm_userpolicy_id *policy_id; + iterator_t *iterator; + + DBG2(DBG_KNL, "deleting policy %R===%R", src_ts, dst_ts); + + /* create a policy */ + memset(&policy, 0, sizeof(policy_entry_t)); + policy.sel = ts2selector(src_ts, dst_ts); + policy.direction = direction; + + /* find the policy */ + pthread_mutex_lock(&this->policies_mutex); + iterator = this->policies->create_iterator(this->policies, TRUE); + while (iterator->iterate(iterator, (void**)¤t)) + { + if (memcmp(¤t->sel, &policy.sel, sizeof(struct xfrm_selector)) == 0 && + policy.direction == current->direction) + { + to_delete = current; + if (--to_delete->refcount > 0) + { + /* is used by more SAs, keep in kernel */ + DBG2(DBG_KNL, "policy still used by another CHILD_SA, not removed"); + iterator->destroy(iterator); + pthread_mutex_unlock(&this->policies_mutex); + return SUCCESS; + } + /* remove if last reference */ + iterator->remove(iterator); + break; + } + } + iterator->destroy(iterator); + pthread_mutex_unlock(&this->policies_mutex); + if (!to_delete) + { + DBG1(DBG_KNL, "deleting policy %R===%R failed, not found", src_ts, dst_ts); + return NOT_FOUND; + } + + memset(&request, 0, sizeof(request)); + + hdr = (struct nlmsghdr*)request; + hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK; + hdr->nlmsg_type = XFRM_MSG_DELPOLICY; + hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userpolicy_id)); + + policy_id = (struct xfrm_userpolicy_id*)NLMSG_DATA(hdr); + policy_id->sel = to_delete->sel; + policy_id->dir = direction; + + route = to_delete->route; + free(to_delete); + + if (netlink_send_ack(this->socket_xfrm, hdr) != SUCCESS) + { + DBG1(DBG_KNL, "unable to delete policy %R===%R", src_ts, dst_ts); + return FAILED; + } + + if (route) + { + if (manage_srcroute(this, RTM_DELROUTE, 0, route) != SUCCESS) + { + DBG1(DBG_KNL, "error uninstalling route installed with " + "policy %R===%R", src_ts, dst_ts); + } + route_entry_destroy(route); + } + return SUCCESS; +} + +/** + * Implementation of kernel_interface_t.destroy. + */ +static void destroy(private_kernel_interface_t *this) +{ + pthread_cancel(this->event_thread); + pthread_join(this->event_thread, NULL); + close(this->socket_xfrm_events); + close(this->socket_xfrm); + close(this->socket_rt); + this->vips->destroy(this->vips); + this->policies->destroy(this->policies); + free(this); +} + +/* + * Described in header. + */ +kernel_interface_t *kernel_interface_create() +{ + private_kernel_interface_t *this = malloc_thing(private_kernel_interface_t); + struct sockaddr_nl addr; + + /* public functions */ + this->public.get_spi = (status_t(*)(kernel_interface_t*,host_t*,host_t*,protocol_id_t,u_int32_t,u_int32_t*))get_spi; + this->public.add_sa = (status_t(*)(kernel_interface_t *,host_t*,host_t*,u_int32_t,protocol_id_t,u_int32_t,u_int64_t,u_int64_t,algorithm_t*,algorithm_t*,prf_plus_t*,natt_conf_t*,mode_t,bool))add_sa; + this->public.update_sa = (status_t(*)(kernel_interface_t*,host_t*,u_int32_t,protocol_id_t,host_t*,host_t*,host_diff_t,host_diff_t))update_sa; + this->public.query_sa = (status_t(*)(kernel_interface_t*,host_t*,u_int32_t,protocol_id_t,u_int32_t*))query_sa; + this->public.del_sa = (status_t(*)(kernel_interface_t*,host_t*,u_int32_t,protocol_id_t))del_sa; + this->public.add_policy = (status_t(*)(kernel_interface_t*,host_t*,host_t*,traffic_selector_t*,traffic_selector_t*,policy_dir_t,protocol_id_t,u_int32_t,bool,mode_t,bool))add_policy; + this->public.query_policy = (status_t(*)(kernel_interface_t*,traffic_selector_t*,traffic_selector_t*,policy_dir_t,u_int32_t*))query_policy; + this->public.del_policy = (status_t(*)(kernel_interface_t*,traffic_selector_t*,traffic_selector_t*,policy_dir_t))del_policy; + + this->public.get_interface = (char*(*)(kernel_interface_t*,host_t*))get_interface_name; + this->public.create_address_list = (linked_list_t*(*)(kernel_interface_t*))create_address_list_public; + this->public.add_ip = (status_t(*)(kernel_interface_t*,host_t*,host_t*)) add_ip; + this->public.del_ip = (status_t(*)(kernel_interface_t*,host_t*,host_t*)) del_ip; + this->public.destroy = (void(*)(kernel_interface_t*)) destroy; + + /* private members */ + this->vips = linked_list_create(); + this->policies = linked_list_create(); + pthread_mutex_init(&this->policies_mutex,NULL); + pthread_mutex_init(&this->vips_mutex,NULL); + + addr.nl_family = AF_NETLINK; + addr.nl_pid = 0; + addr.nl_groups = 0; + + /* create and bind XFRM socket */ + this->socket_xfrm = socket(AF_NETLINK, SOCK_RAW, NETLINK_XFRM); + if (this->socket_xfrm <= 0) + { + charon->kill(charon, "unable to create XFRM netlink socket"); + } + + if (bind(this->socket_xfrm, (struct sockaddr*)&addr, sizeof(addr))) + { + charon->kill(charon, "unable to bind XFRM netlink socket"); + } + + /* create and bind RT socket */ + this->socket_rt = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); + if (this->socket_rt <= 0) + { + charon->kill(charon, "unable to create RT netlink socket"); + } + + if (bind(this->socket_rt, (struct sockaddr*)&addr, sizeof(addr))) + { + charon->kill(charon, "unable to bind RT netlink socket"); + } + + /* create and bind XFRM socket for ACQUIRE & EXPIRE */ + addr.nl_groups = XFRMGRP_ACQUIRE | XFRMGRP_EXPIRE; + this->socket_xfrm_events = socket(AF_NETLINK, SOCK_RAW, NETLINK_XFRM); + if (this->socket_xfrm_events <= 0) + { + charon->kill(charon, "unable to create XFRM event socket"); + } + + if (bind(this->socket_xfrm_events, (struct sockaddr*)&addr, sizeof(addr))) + { + charon->kill(charon, "unable to bind XFRM event socket"); + } + + /* create a thread receiving ACQUIRE & EXPIRE events */ + if (pthread_create(&this->event_thread, NULL, + (void*(*)(void*))receive_events, this)) + { + charon->kill(charon, "unable to create xfrm event dispatcher thread"); + } + + return &this->public; +} + +/* vim: set ts=4 sw=4 noet: */ diff --git a/src/charon/threads/kernel_interface.h b/src/charon/threads/kernel_interface.h new file mode 100644 index 000000000..34b06f594 --- /dev/null +++ b/src/charon/threads/kernel_interface.h @@ -0,0 +1,331 @@ +/** + * @file kernel_interface.h + * + * @brief Interface of kernel_interface_t. + * + */ + +/* + * Copyright (C) 2006 Tobias Brunner, Daniel Roethlisberger + * Copyright (C) 2005-2006 Martin Willi + * Copyright (C) 2005 Jan Hutter + * Hochschule fuer Technik Rapperswil + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * for more details. + */ + +#ifndef KERNEL_INTERFACE_H_ +#define KERNEL_INTERFACE_H_ + +typedef struct natt_conf_t natt_conf_t; +typedef enum policy_dir_t policy_dir_t; +typedef struct kernel_interface_t kernel_interface_t; + +#include <utils/host.h> +#include <crypto/prf_plus.h> +#include <encoding/payloads/proposal_substructure.h> + +/** + * Configuration for NAT-T + */ +struct natt_conf_t { + /** source port to use for UDP-encapsulated packets */ + u_int16_t sport; + /** dest port to use for UDP-encapsulated packets */ + u_int16_t dport; +}; + +/** + * Direction of a policy. These are equal to those + * defined in xfrm.h, but we want to stay implementation + * neutral here. + */ +enum policy_dir_t { + /** Policy for inbound traffic */ + POLICY_IN = 0, + /** Policy for outbound traffic */ + POLICY_OUT = 1, + /** Policy for forwarded traffic */ + POLICY_FWD = 2, +}; + +/** + * @brief Interface to the kernel. + * + * The kernel interface handles the communication with the kernel + * for SA and policy management. It allows setup of these, and provides + * further the handling of kernel events. + * Policy information are cached in the interface. This is necessary to do + * reference counting. The Linux kernel does not allow the same policy + * installed twice, but we need this as CHILD_SA exist multiple times + * when rekeying. Thats why we do reference counting of policies. + * + * @b Constructors: + * - kernel_interface_create() + * + * @ingroup threads + */ +struct kernel_interface_t { + + /** + * @brief Get a SPI from the kernel. + * + * @warning get_spi() implicitely creates an SA with + * the allocated SPI, therefore the replace flag + * in add_sa() must be set when installing this SA. + * + * @param this calling object + * @param src source address of SA + * @param dst destination address of SA + * @param protocol protocol for SA (ESP/AH) + * @param reqid unique ID for this SA + * @param[out] spi allocated spi + * @return + * - SUCCESS + * - FAILED if kernel comm failed + */ + status_t (*get_spi)(kernel_interface_t *this, host_t *src, host_t *dst, + protocol_id_t protocol, u_int32_t reqid, u_int32_t *spi); + + /** + * @brief Add an SA to the SAD. + * + * add_sa() may update an already allocated + * SPI (via get_spi). In this case, the replace + * flag must be set. + * This function does install a single SA for a + * single protocol in one direction. The kernel-interface + * gets the keys itself from the PRF, as we don't know + * his algorithms and key sizes. + * + * @param this calling object + * @param src source address for this SA + * @param dst destination address for this SA + * @param spi SPI allocated by us or remote peer + * @param protocol protocol for this SA (ESP/AH) + * @param reqid unique ID for this SA + * @param expire_soft lifetime in seconds before rekeying + * @param expire_hard lieftime in seconds before delete + * @param enc_alg Algorithm to use for encryption (ESP only) + * @param int_alg Algorithm to use for integrity protection + * @param prf_plus PRF to derive keys from + * @param natt NAT-T Configuration, or NULL of no NAT-T used + * @param mode mode of the SA (tunnel, transport) + * @param replace Should an already installed SA be updated? + * @return + * - SUCCESS + * - FAILED if kernel comm failed + */ + status_t (*add_sa) (kernel_interface_t *this, + host_t *src, host_t *dst, u_int32_t spi, + protocol_id_t protocol, u_int32_t reqid, + u_int64_t expire_soft, u_int64_t expire_hard, + algorithm_t *enc_alg, algorithm_t *int_alg, + prf_plus_t *prf_plus, natt_conf_t *natt, + mode_t mode, bool update); + + /** + * @brief Update the hosts on an installed SA. + * + * We cannot directly update the destination address as the kernel + * requires the spi, the protocol AND the destination address (and family) + * to identify SAs. Therefore if the destination address changed we + * create a new SA and delete the old one. + * + * @param this calling object + * @param dst destination address for this SA + * @param spi SPI of the SA + * @param protocol protocol for this SA (ESP/AH) + * @param new_src new source address for this SA + * @param new_dst new destination address for this SA + * @param src_changes changes in src + * @param dst_changes changes in dst + * @return + * - SUCCESS + * - FAILED if kernel comm failed + */ + status_t (*update_sa)(kernel_interface_t *this, host_t *dst, u_int32_t spi, + protocol_id_t protocol, + host_t *new_src, host_t *new_dst, + host_diff_t src_changes, host_diff_t dst_changes); + + /** + * @brief Query the use time of an SA. + * + * The use time of an SA is not the time of the last usage, but + * the time of the first usage of the SA. + * + * @param this calling object + * @param dst destination address for this SA + * @param spi SPI allocated by us or remote peer + * @param protocol protocol for this SA (ESP/AH) + * @param[out] use_time the time of this SA's last use + * @return + * - SUCCESS + * - FAILED if kernel comm failed + */ + status_t (*query_sa) (kernel_interface_t *this, host_t *dst, u_int32_t spi, + protocol_id_t protocol, u_int32_t *use_time); + + /** + * @brief Delete a previusly installed SA from the SAD. + * + * @param this calling object + * @param dst destination address for this SA + * @param spi SPI allocated by us or remote peer + * @param protocol protocol for this SA (ESP/AH) + * @return + * - SUCCESS + * - FAILED if kernel comm failed + */ + status_t (*del_sa) (kernel_interface_t *this, host_t *dst, u_int32_t spi, + protocol_id_t protocol); + + /** + * @brief Add a policy to the SPD. + * + * A policy is always associated to an SA. Traffic which matches a + * policy is handled by the SA with the same reqid. + * If the update flag is set, the policy is updated with the new + * src/dst addresses. + * If the update flag is not set, but a such policy is already in the + * kernel, the reference count to this policy is increased. + * + * @param this calling object + * @param src source address of SA + * @param dst dest address of SA + * @param src_ts traffic selector to match traffic source + * @param dst_ts traffic selector to match traffic dest + * @param direction direction of traffic, POLICY_IN, POLICY_OUT, POLICY_FWD + * @param protocol protocol to use to protect traffic (AH/ESP) + * @param reqid uniqe ID of an SA to use to enforce policy + * @param high_prio if TRUE, uses a higher priority than any with FALSE + * @param mode mode of SA (tunnel, transport) + * @param update update an existing policy, if TRUE + * @return + * - SUCCESS + * - FAILED if kernel comm failed + */ + status_t (*add_policy) (kernel_interface_t *this, + host_t *src, host_t *dst, + traffic_selector_t *src_ts, + traffic_selector_t *dst_ts, + policy_dir_t direction, protocol_id_t protocol, + u_int32_t reqid, bool high_prio, + mode_t mode, bool update); + + /** + * @brief Query the use time of a policy. + * + * The use time of a policy is the time the policy was used + * for the last time. + * + * @param this calling object + * @param src_ts traffic selector to match traffic source + * @param dst_ts traffic selector to match traffic dest + * @param direction direction of traffic, POLICY_IN, POLICY_OUT, POLICY_FWD + * @param[out] use_time the time of this SA's last use + * @return + * - SUCCESS + * - FAILED if kernel comm failed + */ + status_t (*query_policy) (kernel_interface_t *this, + traffic_selector_t *src_ts, + traffic_selector_t *dst_ts, + policy_dir_t direction, u_int32_t *use_time); + + /** + * @brief Remove a policy from the SPD. + * + * The kernel interface implements reference counting for policies. + * If the same policy is installed multiple times (in the case of rekeying), + * the reference counter is increased. del_policy() decreases the ref counter + * and removes the policy only when no more references are available. + * + * @param this calling object + * @param src_ts traffic selector to match traffic source + * @param dst_ts traffic selector to match traffic dest + * @param direction direction of traffic, POLICY_IN, POLICY_OUT, POLICY_FWD + * @return + * - SUCCESS + * - FAILED if kernel comm failed + */ + status_t (*del_policy) (kernel_interface_t *this, + traffic_selector_t *src_ts, + traffic_selector_t *dst_ts, + policy_dir_t direction); + + /** + * @brief Get the interface name of a local address. + * + * @param this calling object + * @param host address to get interface name from + * @return allocated interface name, or NULL if not found + */ + char* (*get_interface) (kernel_interface_t *this, host_t *host); + + /** + * @brief Creates a list of all local addresses. + * + * @param this calling object + * @return allocated list with host_t objects + */ + linked_list_t *(*create_address_list) (kernel_interface_t *this); + + /** + * @brief Add a virtual IP to an interface. + * + * Virtual IPs are attached to an interface. If an IP is added multiple + * times, the IP is refcounted and not removed until del_ip() was called + * as many times as add_ip(). + * The virtual IP is attached to the interface where the iface_ip is found. + * + * @param this calling object + * @param virtual_ip virtual ip address to assign + * @param iface_ip IP of an interface to attach virtual IP + * @return + * - SUCCESS + * - FAILED if kernel comm failed + */ + status_t (*add_ip) (kernel_interface_t *this, host_t *virtual_ip, + host_t *iface_ip); + + /** + * @brief Remove a virtual IP from an interface. + * + * The kernel interface uses refcounting, see add_ip(). + * + * @param this calling object + * @param virtual_ip virtual ip address to assign + * @param iface_ip IP of an interface to remove virtual IP from + * @return + * - SUCCESS + * - FAILED if kernel comm failed + */ + status_t (*del_ip) (kernel_interface_t *this, host_t *virtual_ip, + host_t *iface_ip); + + /** + * @brief Destroys a kernel_interface object. + * + * @param kernel_interface_t calling object + */ + void (*destroy) (kernel_interface_t *kernel_interface); +}; + +/** + * @brief Creates an object of type kernel_interface_t. + * + * @ingroup threads + */ +kernel_interface_t *kernel_interface_create(void); + +#endif /*KERNEL_INTERFACE_H_*/ diff --git a/src/charon/threads/receiver.c b/src/charon/threads/receiver.c new file mode 100644 index 000000000..7195c162d --- /dev/null +++ b/src/charon/threads/receiver.c @@ -0,0 +1,372 @@ +/** + * @file receiver.c + * + * @brief Implementation of receiver_t. + * + */ + +/* + * Copyright (C) 2005-2006 Martin Willi + * Copyright (C) 2005 Jan Hutter + * Hochschule fuer Technik Rapperswil + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * for more details. + */ + +#include <stdlib.h> +#include <pthread.h> + +#include "receiver.h" + +#include <daemon.h> +#include <network/socket.h> +#include <network/packet.h> +#include <queues/job_queue.h> +#include <queues/jobs/job.h> +#include <queues/jobs/process_message_job.h> + +/** length of the full cookie, including time (u_int32_t + SHA1()) */ +#define COOKIE_LENGTH 24 +/** lifetime of a cookie, in seconds */ +#define COOKIE_LIFETIME 10 +/** how many times to reuse the secret */ +#define COOKIE_REUSE 10000 +/** require cookies after half open IKE_SAs */ +#define COOKIE_TRESHOLD 10 +/** how many half open IKE_SAs per peer before blocking */ +#define BLOCK_TRESHOLD 5 +/** length of the secret to use for cookie calculation */ +#define SECRET_LENGTH 16 + +typedef struct private_receiver_t private_receiver_t; + +/** + * Private data of a receiver_t object. + */ +struct private_receiver_t { + /** + * Public part of a receiver_t object. + */ + receiver_t public; + + /** + * Assigned thread. + */ + pthread_t assigned_thread; + + /** + * current secret to use for cookie calculation + */ + char secret[SECRET_LENGTH]; + + /** + * previous secret used to verify older cookies + */ + char secret_old[SECRET_LENGTH]; + + /** + * how many times we have used "secret" so far + */ + u_int32_t secret_used; + + /** + * time we did the cookie switch + */ + u_int32_t secret_switch; + + /** + * time offset to use, hides our system time + */ + u_int32_t secret_offset; + + /** + * the randomizer to use for secret generation + */ + randomizer_t *randomizer; + + /** + * hasher to use for cookie calculation + */ + hasher_t *hasher; +}; + +/** + * send a notify back to the sender + */ +static void send_notify(message_t *request, notify_type_t type, chunk_t data) +{ + if (request->get_request(request) && + request->get_exchange_type(request) == IKE_SA_INIT) + { + message_t *response; + host_t *src, *dst; + packet_t *packet; + ike_sa_id_t *ike_sa_id; + + response = message_create(); + dst = request->get_source(request); + src = request->get_destination(request); + response->set_source(response, src->clone(src)); + response->set_destination(response, dst->clone(dst)); + response->set_exchange_type(response, request->get_exchange_type(request)); + response->set_request(response, FALSE); + response->set_message_id(response, 0); + ike_sa_id = request->get_ike_sa_id(request); + ike_sa_id->switch_initiator(ike_sa_id); + response->set_ike_sa_id(response, ike_sa_id); + response->add_notify(response, FALSE, type, data); + if (response->generate(response, NULL, NULL, &packet) == SUCCESS) + { + charon->sender->send(charon->sender, packet); + response->destroy(response); + } + } +} + +/** + * build a cookie + */ +static chunk_t cookie_build(private_receiver_t *this, message_t *message, + u_int32_t t, chunk_t secret) +{ + u_int64_t spi = message->get_initiator_spi(message); + host_t *ip = message->get_source(message); + chunk_t input, hash = chunk_alloca(this->hasher->get_hash_size(this->hasher)); + + /* COOKIE = t | sha1( IPi | SPIi | t | secret ) */ + input = chunk_cata("cccc", ip->get_address(ip), chunk_from_thing(spi), + chunk_from_thing(t), secret); + this->hasher->get_hash(this->hasher, input, hash.ptr); + return chunk_cat("cc", chunk_from_thing(t), hash); +} + +/** + * verify a received cookie + */ +static bool cookie_verify(private_receiver_t *this, message_t *message, + chunk_t cookie) +{ + u_int32_t t, now; + chunk_t reference; + chunk_t secret; + + now = time(NULL); + t = *(u_int32_t*)cookie.ptr; + + if (cookie.len != COOKIE_LENGTH || + t < now - this->secret_offset - COOKIE_LIFETIME) + { + DBG2(DBG_NET, "received cookie lifetime expired, rejecting"); + return FALSE; + } + + /* check if cookie is derived from old_secret */ + if (t + this->secret_offset > this->secret_switch) + { + secret = chunk_from_thing(this->secret); + } + else + { + secret = chunk_from_thing(this->secret_old); + } + + /* compare own calculation against received */ + reference = cookie_build(this, message, t, secret); + if (chunk_equals(reference, cookie)) + { + chunk_free(&reference); + return TRUE; + } + chunk_free(&reference); + return FALSE; +} + +/** + * check if cookies are required, and if so, a valid cookie is included + */ +static bool cookie_required(private_receiver_t *this, message_t *message) +{ + bool failed = FALSE; + + if (charon->ike_sa_manager->get_half_open_count(charon->ike_sa_manager, + NULL) >= COOKIE_TRESHOLD) + { + /* check for a cookie. We don't use our parser here and do it + * quick and dirty for performance reasons. + * we assume to cookie is the first payload (which is a MUST), and + * the cookies SPI length is zero. */ + packet_t *packet = message->get_packet(message); + chunk_t data = packet->get_data(packet); + if (data.len < + IKE_HEADER_LENGTH + NOTIFY_PAYLOAD_HEADER_LENGTH + COOKIE_LENGTH || + *(data.ptr + 16) != NOTIFY || + *(u_int16_t*)(data.ptr + IKE_HEADER_LENGTH + 6) != htons(COOKIE)) + { + /* no cookie found */ + failed = TRUE; + } + else + { + data.ptr += IKE_HEADER_LENGTH + NOTIFY_PAYLOAD_HEADER_LENGTH; + data.len = COOKIE_LENGTH; + if (!cookie_verify(this, message, data)) + { + DBG2(DBG_NET, "found cookie, but content invalid"); + failed = TRUE; + } + } + packet->destroy(packet); + } + return failed; +} + +/** + * check if peer has to many half open IKE_SAs + */ +static bool peer_to_aggressive(private_receiver_t *this, message_t *message) +{ + if (charon->ike_sa_manager->get_half_open_count(charon->ike_sa_manager, + message->get_source(message)) >= BLOCK_TRESHOLD) + { + return TRUE; + } + return FALSE; +} + +/** + * Implementation of receiver_t.receive_packets. + */ +static void receive_packets(private_receiver_t *this) +{ + packet_t *packet; + message_t *message; + job_t *job; + + pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL); + DBG1(DBG_NET, "receiver thread running, thread_ID: %06u", + (int)pthread_self()); + + while (TRUE) + { + /* read in a packet */ + if (charon->socket->receive(charon->socket, &packet) != SUCCESS) + { + DBG1(DBG_NET, "receiving from socket failed!"); + continue; + } + + /* parse message header */ + message = message_create_from_packet(packet); + if (message->parse_header(message) != SUCCESS) + { + DBG1(DBG_NET, "received invalid IKE header from %H, ignored", + packet->get_source(packet)); + message->destroy(message); + continue; + } + + /* check IKE major version */ + if (message->get_major_version(message) != IKE_MAJOR_VERSION) + { + DBG1(DBG_NET, "received unsupported IKE version %d.%d from %H, " + "sending INVALID_MAJOR_VERSION", message->get_major_version(message), + message->get_minor_version(message), packet->get_source(packet)); + send_notify(message, INVALID_MAJOR_VERSION, chunk_empty); + message->destroy(message); + continue; + } + + if (message->get_request(message) && + message->get_exchange_type(message) == IKE_SA_INIT) + { + /* check for cookies */ + if (cookie_required(this, message)) + { + u_int32_t now = time(NULL); + chunk_t cookie = cookie_build(this, message, now - this->secret_offset, + chunk_from_thing(this->secret)); + + DBG2(DBG_NET, "received packet from: %#H to %#H", + message->get_source(message), + message->get_destination(message)); + DBG2(DBG_NET, "sending COOKIE notify to %H", + message->get_source(message)); + send_notify(message, COOKIE, cookie); + chunk_free(&cookie); + if (++this->secret_used > COOKIE_REUSE) + { + /* create new cookie */ + DBG1(DBG_NET, "generating new cookie secret after %d uses", + this->secret_used); + memcpy(this->secret_old, this->secret, SECRET_LENGTH); + this->randomizer->get_pseudo_random_bytes(this->randomizer, + SECRET_LENGTH, this->secret); + this->secret_switch = now; + this->secret_used = 0; + } + message->destroy(message); + continue; + } + + /* check if peer has not too many IKE_SAs half open */ + if (peer_to_aggressive(this, message)) + { + DBG1(DBG_NET, "ignoring IKE_SA setup from %H, " + "peer to aggressive", message->get_source(message)); + message->destroy(message); + continue; + } + } + job = (job_t *)process_message_job_create(message); + charon->job_queue->add(charon->job_queue, job); + } +} + +/** + * Implementation of receiver_t.destroy. + */ +static void destroy(private_receiver_t *this) +{ + pthread_cancel(this->assigned_thread); + pthread_join(this->assigned_thread, NULL); + this->randomizer->destroy(this->randomizer); + this->hasher->destroy(this->hasher); + free(this); +} + +/* + * Described in header. + */ +receiver_t *receiver_create() +{ + private_receiver_t *this = malloc_thing(private_receiver_t); + u_int32_t now = time(NULL); + + this->public.destroy = (void(*)(receiver_t*)) destroy; + + this->randomizer = randomizer_create(); + this->hasher = hasher_create(HASH_SHA1); + this->secret_switch = now; + this->secret_offset = random() % now; + this->secret_used = 0; + this->randomizer->get_pseudo_random_bytes(this->randomizer, SECRET_LENGTH, + this->secret); + memcpy(this->secret_old, this->secret, SECRET_LENGTH); + + if (pthread_create(&this->assigned_thread, NULL, + (void*)receive_packets, this) != 0) + { + free(this); + charon->kill(charon, "unable to create receiver thread"); + } + + return &this->public; +} diff --git a/src/charon/threads/receiver.h b/src/charon/threads/receiver.h new file mode 100644 index 000000000..68d9136c0 --- /dev/null +++ b/src/charon/threads/receiver.h @@ -0,0 +1,81 @@ +/** + * @file receiver.h + * + * @brief Interface of receiver_t. + * + */ + +/* + * Copyright (C) 2005-2007 Martin Willi + * Copyright (C) 2005 Jan Hutter + * Hochschule fuer Technik Rapperswil + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * for more details. + */ + +#ifndef RECEIVER_H_ +#define RECEIVER_H_ + +typedef struct receiver_t receiver_t; + +#include <library.h> +#include <utils/host.h> + +/** + * @brief Receives packets from the socket and adds them to the job queue. + * + * The receiver starts a thread, wich reads on the blocking socket. A received + * packet is preparsed and a process_message_job is queued in the job queue. + * + * To endure DoS attacks, cookies are enabled when to many IKE_SAs are half + * open. The calculation of cookies is slightly different from the proposed + * method in RFC4306. We do not include a nonce, because we think the advantage + * we gain does not justify the overhead to parse the whole message. + * Instead of VersionIdOfSecret, we include a timestamp. This allows us to + * find out wich key was used for cookie creation. Further, we can set a + * lifetime for the cookie, which allows us to reuse the secret for a longer + * time. + * COOKIE = time | sha1( IPi | SPIi | time | secret ) + * + * The secret is changed after a certain amount of cookies sent. The old + * secret is stored to allow a clean migration between secret changes. + * + * Further, the number of half-initiated IKE_SAs is limited per peer. This + * mades it impossible for a peer to flood the server with its real IP address. + * + * @b Constructors: + * - receiver_create() + * + * @ingroup threads + */ +struct receiver_t { + + /** + * @brief Destroys a receiver_t object. + * + * @param receiver receiver object + */ + void (*destroy) (receiver_t *receiver); +}; + +/** + * @brief Create a receiver_t object. + * + * The receiver thread will start working, get data + * from the socket and add those packets to the job queue. + * + * @return receiver_t object + * + * @ingroup threads + */ +receiver_t * receiver_create(void); + +#endif /*RECEIVER_H_*/ diff --git a/src/charon/threads/scheduler.c b/src/charon/threads/scheduler.c new file mode 100644 index 000000000..74091e3a3 --- /dev/null +++ b/src/charon/threads/scheduler.c @@ -0,0 +1,102 @@ +/** + * @file scheduler.c + * + * @brief Implementation of scheduler_t. + * + */ + +/* + * Copyright (C) 2005-2006 Martin Willi + * Copyright (C) 2005 Jan Hutter + * Hochschule fuer Technik Rapperswil + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * for more details. + */ + +#include <stdlib.h> +#include <pthread.h> + +#include "scheduler.h" + +#include <daemon.h> +#include <queues/job_queue.h> + + +typedef struct private_scheduler_t private_scheduler_t; + +/** + * Private data of a scheduler_t object. + */ +struct private_scheduler_t { + /** + * Public part of a scheduler_t object. + */ + scheduler_t public; + + /** + * Assigned thread. + */ + pthread_t assigned_thread; +}; + +/** + * Implementation of private_scheduler_t.get_events. + */ +static void get_events(private_scheduler_t * this) +{ + job_t *current_job; + + /* cancellation disabled by default */ + pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL); + + DBG1(DBG_JOB, "scheduler thread running, thread_ID: %06u", + (int)pthread_self()); + + while (TRUE) + { + DBG2(DBG_JOB, "waiting for next event..."); + /* get a job, this block until one is available */ + current_job = charon->event_queue->get(charon->event_queue); + /* queue the job in the job queue, workers will eat them */ + DBG2(DBG_JOB, "got event, adding job %N to job-queue", + job_type_names, current_job->get_type(current_job)); + charon->job_queue->add(charon->job_queue, current_job); + } +} + +/** + * Implementation of scheduler_t.destroy. + */ +static void destroy(private_scheduler_t *this) +{ + pthread_cancel(this->assigned_thread); + pthread_join(this->assigned_thread, NULL); + free(this); +} + +/* + * Described in header. + */ +scheduler_t * scheduler_create() +{ + private_scheduler_t *this = malloc_thing(private_scheduler_t); + + this->public.destroy = (void(*)(scheduler_t*)) destroy; + + if (pthread_create(&(this->assigned_thread), NULL, (void*(*)(void*))get_events, this) != 0) + { + /* thread could not be created */ + free(this); + charon->kill(charon, "unable to create scheduler thread"); + } + + return &(this->public); +} diff --git a/src/charon/threads/scheduler.h b/src/charon/threads/scheduler.h new file mode 100644 index 000000000..daecce3c6 --- /dev/null +++ b/src/charon/threads/scheduler.h @@ -0,0 +1,68 @@ +/** + * @file scheduler.h + * + * @brief Interface of scheduler_t. + * + */ + +/* + * Copyright (C) 2005-2006 Martin Willi + * Copyright (C) 2005 Jan Hutter + * Hochschule fuer Technik Rapperswil + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * for more details. + */ + +#ifndef SCHEDULER_H_ +#define SCHEDULER_H_ + +typedef struct scheduler_t scheduler_t; + +#include <library.h> + +/** + * @brief The scheduler thread is responsible for timed events. + * + * The scheduler thread takes out jobs from the event-queue and adds them + * to the job-queue. + * + * Starts a thread which does the work, since event-queue is blocking. + * + * @b Constructors: + * - scheduler_create() + * + * @ingroup threads + */ +struct scheduler_t { + + /** + * @brief Destroys a scheduler object. + * + * @param scheduler calling object + */ + void (*destroy) (scheduler_t *scheduler); +}; + +/** + * @brief Create a scheduler with its associated thread. + * + * The thread will start to get jobs form the event queue + * and adds them to the job queue. + * + * @return + * - scheduler_t object + * - NULL if thread could not be started + * + * @ingroup threads + */ +scheduler_t * scheduler_create(void); + +#endif /*SCHEDULER_H_*/ diff --git a/src/charon/threads/sender.c b/src/charon/threads/sender.c new file mode 100644 index 000000000..c1cd0a68c --- /dev/null +++ b/src/charon/threads/sender.c @@ -0,0 +1,149 @@ +/** + * @file sender.c + * + * @brief Implementation of sender_t. + * + */ + +/* + * Copyright (C) 2005-2006 Martin Willi + * Copyright (C) 2005 Jan Hutter + * Hochschule fuer Technik Rapperswil + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * for more details. + */ + +#include <stdlib.h> +#include <pthread.h> + +#include "sender.h" + +#include <daemon.h> +#include <network/socket.h> + + +typedef struct private_sender_t private_sender_t; + +/** + * Private data of a sender_t object. + */ +struct private_sender_t { + /** + * Public part of a sender_t object. + */ + sender_t public; + + /** + * Assigned thread. + */ + pthread_t assigned_thread; + + /** + * The packets are stored in a linked list + */ + linked_list_t *list; + + /** + * mutex to synchronize access to list + */ + pthread_mutex_t mutex; + + /** + * condvar to signal for packets in list + */ + pthread_cond_t condvar; +}; + +/** + * implements sender_t.send + */ +static void send_(private_sender_t *this, packet_t *packet) +{ + host_t *src, *dst; + + src = packet->get_source(packet); + dst = packet->get_destination(packet); + DBG1(DBG_NET, "sending packet: from %#H to %#H", src, dst); + + pthread_mutex_lock(&this->mutex); + this->list->insert_last(this->list, packet); + pthread_mutex_unlock(&this->mutex); + pthread_cond_signal(&this->condvar); +} + +/** + * Implementation of private_sender_t.send_packets. + */ +static void send_packets(private_sender_t * this) +{ + + /* cancellation disabled by default */ + pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL); + DBG1(DBG_NET, "sender thread running, thread_ID: %06u", (int)pthread_self()); + + while (TRUE) + { + packet_t *packet; + int oldstate; + + pthread_mutex_lock(&this->mutex); + /* go to wait while no packets available */ + while (this->list->get_count(this->list) == 0) + { + /* add cleanup handler, wait for packet, remove cleanup handler */ + pthread_cleanup_push((void(*)(void*))pthread_mutex_unlock, (void*)&this->mutex); + pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldstate); + pthread_cond_wait(&this->condvar, &this->mutex); + + pthread_setcancelstate(oldstate, NULL); + pthread_cleanup_pop(0); + } + this->list->remove_first(this->list, (void**)&packet); + pthread_mutex_unlock(&this->mutex); + + charon->socket->send(charon->socket, packet); + packet->destroy(packet); + } +} + +/** + * Implementation of sender_t.destroy. + */ +static void destroy(private_sender_t *this) +{ + pthread_cancel(this->assigned_thread); + pthread_join(this->assigned_thread, NULL); + this->list->destroy_offset(this->list, offsetof(packet_t, destroy)); + free(this); +} + +/* + * Described in header. + */ +sender_t * sender_create() +{ + private_sender_t *this = malloc_thing(private_sender_t); + + this->public.send = (void(*)(sender_t*,packet_t*))send_; + this->public.destroy = (void(*)(sender_t*)) destroy; + + this->list = linked_list_create(); + pthread_mutex_init(&this->mutex, NULL); + pthread_cond_init(&this->condvar, NULL); + + if (pthread_create(&this->assigned_thread, NULL, + (void*)send_packets, this) != 0) + { + charon->kill(charon, "unable to create sender thread"); + } + + return &(this->public); +} diff --git a/src/charon/threads/sender.h b/src/charon/threads/sender.h new file mode 100644 index 000000000..4f42f6f9e --- /dev/null +++ b/src/charon/threads/sender.h @@ -0,0 +1,74 @@ +/** + * @file sender.h + * + * @brief Interface of sender_t. + * + */ + +/* + * Copyright (C) 2005-2007 Martin Willi + * Copyright (C) 2005 Jan Hutter + * Hochschule fuer Technik Rapperswil + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * for more details. + */ + +#ifndef SENDER_H_ +#define SENDER_H_ + +typedef struct sender_t sender_t; + +#include <library.h> +#include <network/packet.h> + +/** + * @brief Thread responsible for sending packets over the socket. + * + * @b Constructors: + * - sender_create() + * + * @ingroup threads + */ +struct sender_t { + + /** + * @brief Send a packet over the network. + * + * This function is non blocking and adds the packet to a queue. + * Whenever the sender thread things it's good to send the packet, + * it'll do so. + * + * @param this calling object + * @param packet packet to send + */ + void (*send) (sender_t *this, packet_t *packet); + + /** + * @brief Destroys a sender object. + * + * @param this calling object + */ + void (*destroy) (sender_t *this); +}; + +/** + * @brief Create the sender thread. + * + * The thread will start to work, getting packets + * from its queue and sends them out. + * + * @return created sender object + * + * @ingroup threads + */ +sender_t * sender_create(void); + +#endif /*SENDER_H_*/ diff --git a/src/charon/threads/stroke_interface.c b/src/charon/threads/stroke_interface.c new file mode 100755 index 000000000..a9074debb --- /dev/null +++ b/src/charon/threads/stroke_interface.c @@ -0,0 +1,1456 @@ +/** + * @file stroke.c + * + * @brief Implementation of stroke_t. + * + */ + +/* + * Copyright (C) 2006 Martin Willi + * Hochschule fuer Technik Rapperswil + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * for more details. + */ + +#include <stdlib.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <sys/socket.h> +#include <sys/un.h> +#include <sys/fcntl.h> +#include <unistd.h> +#include <dirent.h> +#include <errno.h> +#include <pthread.h> +#include <signal.h> + +#include "stroke_interface.h" + +#include <library.h> +#include <stroke.h> +#include <daemon.h> +#include <crypto/x509.h> +#include <crypto/ca.h> +#include <crypto/crl.h> +#include <queues/jobs/initiate_job.h> +#include <queues/jobs/route_job.h> +#include <utils/leak_detective.h> + +#define IKE_PORT 500 +#define PATH_BUF 256 + + +struct sockaddr_un socket_addr = { AF_UNIX, STROKE_SOCKET}; + + +typedef struct private_stroke_t private_stroke_t; + +/** + * Private data of an stroke_t object. + */ +struct private_stroke_t { + + /** + * Public part of stroke_t object. + */ + stroke_t public; + + /** + * Output stream (stroke console) + */ + FILE *out; + + /** + * Unix socket to listen for strokes + */ + int socket; + + /** + * Thread which reads from the Socket + */ + pthread_t assigned_thread; +}; + +/** + * Helper function which corrects the string pointers + * in a stroke_msg_t. Strings in a stroke_msg sent over "wire" + * contains RELATIVE addresses (relative to the beginning of the + * stroke_msg). They must be corrected if they reach our address + * space... + */ +static void pop_string(stroke_msg_t *msg, char **string) +{ + if (*string == NULL) + return; + + /* check for sanity of string pointer and string */ + if (string < (char**)msg + || string > (char**)msg + sizeof(stroke_msg_t) + || (unsigned long)*string < (unsigned long)((char*)msg->buffer - (char*)msg) + || (unsigned long)*string > msg->length) + { + *string = "(invalid pointer in stroke msg)"; + } + else + { + *string = (char*)msg + (unsigned long)*string; + } +} + +/** + * Load end entitity certificate + */ +static x509_t* load_end_certificate(const char *filename, identification_t **idp) +{ + char path[PATH_BUF]; + x509_t *cert; + + if (*filename == '/') + { + /* absolute path name */ + snprintf(path, sizeof(path), "%s", filename); + } + else + { + /* relative path name */ + snprintf(path, sizeof(path), "%s/%s", CERTIFICATE_DIR, filename); + } + + cert = x509_create_from_file(path, "end entity"); + + if (cert) + { + identification_t *id = *idp; + identification_t *subject = cert->get_subject(cert); + + err_t ugh = cert->is_valid(cert, NULL); + + if (ugh != NULL) + { + DBG1(DBG_CFG, "warning: certificate %s", ugh); + } + if (!id->equals(id, subject) && !cert->equals_subjectAltName(cert, id)) + { + id->destroy(id); + id = subject; + *idp = id->clone(id); + } + return charon->credentials->add_end_certificate(charon->credentials, cert); + } + return NULL; +} + +/** + * Load ca certificate + */ +static x509_t* load_ca_certificate(const char *filename) +{ + char path[PATH_BUF]; + x509_t *cert; + + if (*filename == '/') + { + /* absolute path name */ + snprintf(path, sizeof(path), "%s", filename); + } + else + { + /* relative path name */ + snprintf(path, sizeof(path), "%s/%s", CA_CERTIFICATE_DIR, filename); + } + + cert = x509_create_from_file(path, "ca"); + + if (cert) + { + if (cert->is_ca(cert)) + { + return charon->credentials->add_auth_certificate(charon->credentials, cert, AUTH_CA); + } + else + { + DBG1(DBG_CFG, " CA basic constraints flag not set, cert discarded"); + cert->destroy(cert); + } + } + return NULL; +} + +/** + * Add a connection to the configuration list + */ +static void stroke_add_conn(stroke_msg_t *msg, FILE *out) +{ + connection_t *connection; + policy_t *policy; + identification_t *my_id, *other_id; + identification_t *my_ca = NULL; + identification_t *other_ca = NULL; + bool my_ca_same = FALSE; + bool other_ca_same =FALSE; + host_t *my_host, *other_host, *my_subnet, *other_subnet; + host_t *my_vip = NULL, *other_vip = NULL; + proposal_t *proposal; + traffic_selector_t *my_ts, *other_ts; + char *interface; + + pop_string(msg, &msg->add_conn.name); + pop_string(msg, &msg->add_conn.me.address); + pop_string(msg, &msg->add_conn.other.address); + pop_string(msg, &msg->add_conn.me.subnet); + pop_string(msg, &msg->add_conn.other.subnet); + pop_string(msg, &msg->add_conn.me.sourceip); + pop_string(msg, &msg->add_conn.other.sourceip); + pop_string(msg, &msg->add_conn.me.id); + pop_string(msg, &msg->add_conn.other.id); + pop_string(msg, &msg->add_conn.me.cert); + pop_string(msg, &msg->add_conn.other.cert); + pop_string(msg, &msg->add_conn.me.ca); + pop_string(msg, &msg->add_conn.other.ca); + pop_string(msg, &msg->add_conn.me.updown); + pop_string(msg, &msg->add_conn.other.updown); + pop_string(msg, &msg->add_conn.algorithms.ike); + pop_string(msg, &msg->add_conn.algorithms.esp); + + DBG1(DBG_CFG, "received stroke: add connection '%s'", msg->add_conn.name); + + DBG2(DBG_CFG, "conn %s", msg->add_conn.name); + DBG2(DBG_CFG, " left=%s", msg->add_conn.me.address); + DBG2(DBG_CFG, " right=%s", msg->add_conn.other.address); + DBG2(DBG_CFG, " leftsubnet=%s", msg->add_conn.me.subnet); + DBG2(DBG_CFG, " rightsubnet=%s", msg->add_conn.other.subnet); + DBG2(DBG_CFG, " leftsourceip=%s", msg->add_conn.me.sourceip); + DBG2(DBG_CFG, " rightsourceip=%s", msg->add_conn.other.sourceip); + DBG2(DBG_CFG, " leftid=%s", msg->add_conn.me.id); + DBG2(DBG_CFG, " rightid=%s", msg->add_conn.other.id); + DBG2(DBG_CFG, " leftcert=%s", msg->add_conn.me.cert); + DBG2(DBG_CFG, " rightcert=%s", msg->add_conn.other.cert); + DBG2(DBG_CFG, " leftca=%s", msg->add_conn.me.ca); + DBG2(DBG_CFG, " rightca=%s", msg->add_conn.other.ca); + DBG2(DBG_CFG, " ike=%s", msg->add_conn.algorithms.ike); + DBG2(DBG_CFG, " esp=%s", msg->add_conn.algorithms.esp); + + my_host = msg->add_conn.me.address? + host_create_from_string(msg->add_conn.me.address, IKE_PORT) : NULL; + if (my_host == NULL) + { + DBG1(DBG_CFG, "invalid host: %s\n", msg->add_conn.me.address); + return; + } + + other_host = msg->add_conn.other.address ? + host_create_from_string(msg->add_conn.other.address, IKE_PORT) : NULL; + if (other_host == NULL) + { + DBG1(DBG_CFG, "invalid host: %s\n", msg->add_conn.other.address); + my_host->destroy(my_host); + return; + } + + interface = charon->kernel_interface->get_interface(charon->kernel_interface, + other_host); + if (interface) + { + stroke_end_t tmp_end; + host_t *tmp_host; + + DBG2(DBG_CFG, "left is other host, swapping ends\n"); + + tmp_host = my_host; + my_host = other_host; + other_host = tmp_host; + + tmp_end = msg->add_conn.me; + msg->add_conn.me = msg->add_conn.other; + msg->add_conn.other = tmp_end; + free(interface); + } + if (!interface) + { + interface = charon->kernel_interface->get_interface( + charon->kernel_interface, my_host); + if (!interface) + { + DBG1(DBG_CFG, "left nor right host is our side, aborting\n"); + goto destroy_hosts; + } + free(interface); + } + + my_id = identification_create_from_string(msg->add_conn.me.id ? + msg->add_conn.me.id : msg->add_conn.me.address); + if (my_id == NULL) + { + DBG1(DBG_CFG, "invalid ID: %s\n", msg->add_conn.me.id); + goto destroy_hosts; + } + + other_id = identification_create_from_string(msg->add_conn.other.id ? + msg->add_conn.other.id : msg->add_conn.other.address); + if (other_id == NULL) + { + DBG1(DBG_CFG, "invalid ID: %s\n", msg->add_conn.other.id); + my_id->destroy(my_id); + goto destroy_hosts; + } + + my_subnet = host_create_from_string(msg->add_conn.me.subnet ? + msg->add_conn.me.subnet : msg->add_conn.me.address, IKE_PORT); + if (my_subnet == NULL) + { + DBG1(DBG_CFG, "invalid subnet: %s\n", msg->add_conn.me.subnet); + goto destroy_ids; + } + + other_subnet = host_create_from_string(msg->add_conn.other.subnet ? + msg->add_conn.other.subnet : msg->add_conn.other.address, IKE_PORT); + if (other_subnet == NULL) + { + DBG1(DBG_CFG, "invalid subnet: %s\n", msg->add_conn.me.subnet); + my_subnet->destroy(my_subnet); + goto destroy_ids; + } + + if (msg->add_conn.me.virtual_ip) + { + my_vip = host_create_from_string(msg->add_conn.me.sourceip, 0); + } + other_vip = host_create_from_string(msg->add_conn.other.sourceip, 0); + + if (msg->add_conn.me.tohost) + { + my_ts = traffic_selector_create_dynamic(msg->add_conn.me.protocol, + my_host->get_family(my_host) == AF_INET ? + TS_IPV4_ADDR_RANGE : TS_IPV6_ADDR_RANGE, + msg->add_conn.me.port ? msg->add_conn.me.port : 0, + msg->add_conn.me.port ? msg->add_conn.me.port : 65535); + } + else + { + my_ts = traffic_selector_create_from_subnet(my_subnet, + msg->add_conn.me.subnet ? msg->add_conn.me.subnet_mask : 0, + msg->add_conn.me.protocol, msg->add_conn.me.port); + } + my_subnet->destroy(my_subnet); + + if (msg->add_conn.other.tohost) + { + other_ts = traffic_selector_create_dynamic(msg->add_conn.other.protocol, + other_host->get_family(other_host) == AF_INET ? + TS_IPV4_ADDR_RANGE : TS_IPV6_ADDR_RANGE, + msg->add_conn.other.port ? msg->add_conn.other.port : 0, + msg->add_conn.other.port ? msg->add_conn.other.port : 65535); + } + else + { + other_ts = traffic_selector_create_from_subnet(other_subnet, + msg->add_conn.other.subnet ? msg->add_conn.other.subnet_mask : 0, + msg->add_conn.other.protocol, msg->add_conn.other.port); + } + other_subnet->destroy(other_subnet); + + if (msg->add_conn.me.ca) + { + if (streq(msg->add_conn.me.ca, "%same")) + { + my_ca_same = TRUE; + } + else + { + my_ca = identification_create_from_string(msg->add_conn.me.ca); + } + } + if (msg->add_conn.other.ca) + { + if (streq(msg->add_conn.other.ca, "%same")) + { + other_ca_same = TRUE; + } + else + { + other_ca = identification_create_from_string(msg->add_conn.other.ca); + } + } + if (msg->add_conn.me.cert) + { + x509_t *cert = load_end_certificate(msg->add_conn.me.cert, &my_id); + + if (my_ca == NULL && !my_ca_same && cert) + { + identification_t *issuer = cert->get_issuer(cert); + + my_ca = issuer->clone(issuer); + } + } + if (msg->add_conn.other.cert) + { + x509_t *cert = load_end_certificate(msg->add_conn.other.cert, &other_id); + + if (other_ca == NULL && !other_ca_same && cert) + { + identification_t *issuer = cert->get_issuer(cert); + + other_ca = issuer->clone(issuer); + } + } + if (other_ca_same && my_ca) + { + other_ca = my_ca->clone(my_ca); + } + else if (my_ca_same && other_ca) + { + my_ca = other_ca->clone(other_ca); + } + if (my_ca == NULL) + { + my_ca = identification_create_from_string("%any"); + } + if (other_ca == NULL) + { + other_ca = identification_create_from_string("%any"); + } + DBG2(DBG_CFG, " my ca: '%D'", my_ca); + DBG2(DBG_CFG, " other ca:'%D'", other_ca); + DBG2(DBG_CFG, " updown: '%s'", msg->add_conn.me.updown); + + connection = connection_create(msg->add_conn.name, + msg->add_conn.ikev2, + msg->add_conn.me.sendcert, + msg->add_conn.other.sendcert, + my_host, other_host, + msg->add_conn.dpd.delay, + msg->add_conn.rekey.reauth, + msg->add_conn.rekey.tries, + msg->add_conn.rekey.ike_lifetime, + msg->add_conn.rekey.ike_lifetime - msg->add_conn.rekey.margin, + msg->add_conn.rekey.margin * msg->add_conn.rekey.fuzz / 100); + + if (msg->add_conn.algorithms.ike) + { + char *proposal_string; + char *strict = msg->add_conn.algorithms.ike + strlen(msg->add_conn.algorithms.ike) - 1; + + if (*strict == '!') + *strict = '\0'; + else + strict = NULL; + + while ((proposal_string = strsep(&msg->add_conn.algorithms.ike, ","))) + { + proposal = proposal_create_from_string(PROTO_IKE, proposal_string); + if (proposal == NULL) + { + DBG1(DBG_CFG, "invalid IKE proposal string: %s", proposal_string); + my_id->destroy(my_id); + other_id->destroy(other_id); + my_ts->destroy(my_ts); + other_ts->destroy(other_ts); + my_ca->destroy(my_ca); + other_ca->destroy(other_ca); + connection->destroy(connection); + return; + } + connection->add_proposal(connection, proposal); + } + if (!strict) + { + proposal = proposal_create_default(PROTO_IKE); + connection->add_proposal(connection, proposal); + } + } + else + { + proposal = proposal_create_default(PROTO_IKE); + connection->add_proposal(connection, proposal); + } + + policy = policy_create(msg->add_conn.name, my_id, other_id, my_vip, other_vip, + msg->add_conn.auth_method, msg->add_conn.eap_type, + msg->add_conn.rekey.ipsec_lifetime, + msg->add_conn.rekey.ipsec_lifetime - msg->add_conn.rekey.margin, + msg->add_conn.rekey.margin * msg->add_conn.rekey.fuzz / 100, + msg->add_conn.me.updown, msg->add_conn.me.hostaccess, + msg->add_conn.mode, msg->add_conn.dpd.action); + policy->add_my_traffic_selector(policy, my_ts); + policy->add_other_traffic_selector(policy, other_ts); + policy->add_authorities(policy, my_ca, other_ca); + + if (msg->add_conn.algorithms.esp) + { + char *proposal_string; + char *strict = msg->add_conn.algorithms.esp + strlen(msg->add_conn.algorithms.esp) - 1; + + if (*strict == '!') + *strict = '\0'; + else + strict = NULL; + + while ((proposal_string = strsep(&msg->add_conn.algorithms.esp, ","))) + { + proposal = proposal_create_from_string(PROTO_ESP, proposal_string); + if (proposal == NULL) + { + DBG1(DBG_CFG, "invalid ESP proposal string: %s", proposal_string); + policy->destroy(policy); + connection->destroy(connection); + return; + } + policy->add_proposal(policy, proposal); + } + if (!strict) + { + proposal = proposal_create_default(PROTO_ESP); + policy->add_proposal(policy, proposal); + } + } + else + { + proposal = proposal_create_default(PROTO_ESP); + policy->add_proposal(policy, proposal); + } + + /* add to global connection list */ + charon->connections->add_connection(charon->connections, connection); + DBG1(DBG_CFG, "added connection '%s': %H[%D]...%H[%D]", + msg->add_conn.name, my_host, my_id, other_host, other_id); + /* add to global policy list */ + charon->policies->add_policy(charon->policies, policy); + + return; + + /* mopping up after parsing errors */ + +destroy_ids: + my_id->destroy(my_id); + other_id->destroy(other_id); + +destroy_hosts: + my_host->destroy(my_host); + other_host->destroy(other_host); +} + +/** + * Delete a connection from the list + */ +static void stroke_del_conn(stroke_msg_t *msg, FILE *out) +{ + status_t status; + + pop_string(msg, &(msg->del_conn.name)); + DBG1(DBG_CFG, "received stroke: delete connection '%s'", msg->del_conn.name); + + status = charon->connections->delete_connection(charon->connections, + msg->del_conn.name); + charon->policies->delete_policy(charon->policies, msg->del_conn.name); + if (status == SUCCESS) + { + fprintf(out, "deleted connection '%s'\n", msg->del_conn.name); + } + else + { + fprintf(out, "no connection named '%s'\n", msg->del_conn.name); + } +} + +/** + * initiate a connection by name + */ +static void stroke_initiate(stroke_msg_t *msg, FILE *out) +{ + initiate_job_t *job; + connection_t *connection; + policy_t *policy; + ike_sa_t *init_ike_sa = NULL; + signal_t signal; + + pop_string(msg, &(msg->initiate.name)); + DBG1(DBG_CFG, "received stroke: initiate '%s'", msg->initiate.name); + + connection = charon->connections->get_connection_by_name(charon->connections, + msg->initiate.name); + if (connection == NULL) + { + if (msg->output_verbosity >= 0) + { + fprintf(out, "no connection named '%s'\n", msg->initiate.name); + } + return; + } + if (!connection->is_ikev2(connection)) + { + connection->destroy(connection); + return; + } + + policy = charon->policies->get_policy_by_name(charon->policies, + msg->initiate.name); + if (policy == NULL) + { + if (msg->output_verbosity >= 0) + { + fprintf(out, "no policy named '%s'\n", msg->initiate.name); + } + connection->destroy(connection); + return; + } + + job = initiate_job_create(connection, policy); + charon->bus->set_listen_state(charon->bus, TRUE); + charon->job_queue->add(charon->job_queue, (job_t*)job); + while (TRUE) + { + level_t level; + int thread; + ike_sa_t *ike_sa; + char* format; + va_list args; + + signal = charon->bus->listen(charon->bus, &level, &thread, &ike_sa, &format, &args); + + if ((init_ike_sa == NULL || ike_sa == init_ike_sa) && + level <= msg->output_verbosity) + { + if (vfprintf(out, format, args) < 0 || + fprintf(out, "\n") < 0 || + fflush(out)) + { + charon->bus->set_listen_state(charon->bus, FALSE); + break; + } + } + + switch (signal) + { + case CHILD_UP_SUCCESS: + case CHILD_UP_FAILED: + case IKE_UP_FAILED: + if (ike_sa == init_ike_sa) + { + charon->bus->set_listen_state(charon->bus, FALSE); + return; + } + continue; + case CHILD_UP_START: + case IKE_UP_START: + if (init_ike_sa == NULL) + { + init_ike_sa = ike_sa; + } + continue; + default: + continue; + } + } +} + +/** + * route/unroute a policy (install SPD entries) + */ +static void stroke_route(stroke_msg_t *msg, FILE *out, bool route) +{ + route_job_t *job; + connection_t *connection; + policy_t *policy; + + pop_string(msg, &(msg->route.name)); + DBG1(DBG_CFG, "received stroke: %s '%s'", + route ? "route" : "unroute", msg->route.name); + + /* we wouldn't need a connection, but we only want to route policies + * whose connections are keyexchange=ikev2. */ + connection = charon->connections->get_connection_by_name(charon->connections, + msg->route.name); + if (connection == NULL) + { + fprintf(out, "no connection named '%s'\n", msg->route.name); + return; + } + if (!connection->is_ikev2(connection)) + { + connection->destroy(connection); + return; + } + + policy = charon->policies->get_policy_by_name(charon->policies, + msg->route.name); + if (policy == NULL) + { + fprintf(out, "no policy named '%s'\n", msg->route.name); + connection->destroy(connection); + return; + } + fprintf(out, "%s policy '%s'\n", + route ? "routing" : "unrouting", msg->route.name); + job = route_job_create(connection, policy, route); + charon->job_queue->add(charon->job_queue, (job_t*)job); +} + +/** + * terminate a connection by name + */ +static void stroke_terminate(stroke_msg_t *msg, FILE *out) +{ + char *string, *pos = NULL, *name = NULL; + u_int32_t id = 0; + bool child; + int len; + status_t status = SUCCESS;; + ike_sa_t *ike_sa; + + pop_string(msg, &(msg->terminate.name)); + string = msg->terminate.name; + DBG1(DBG_CFG, "received stroke: terminate '%s'", string); + + len = strlen(string); + if (len < 1) + { + DBG1(DBG_CFG, "error parsing string"); + return; + } + switch (string[len-1]) + { + case '}': + child = TRUE; + pos = strchr(string, '{'); + break; + case ']': + child = FALSE; + pos = strchr(string, '['); + break; + default: + name = string; + child = FALSE; + break; + } + + if (name) + { /* must be a single name */ + DBG1(DBG_CFG, "check out by single name '%s'", name); + ike_sa = charon->ike_sa_manager->checkout_by_name(charon->ike_sa_manager, + name, child); + } + else if (pos == string + len - 2) + { /* must be name[] or name{} */ + string[len-2] = '\0'; + DBG1(DBG_CFG, "check out by name '%s'", string); + ike_sa = charon->ike_sa_manager->checkout_by_name(charon->ike_sa_manager, + string, child); + } + else + { /* must be name[123] or name{23} */ + string[len-1] = '\0'; + id = atoi(pos + 1); + if (id == 0) + { + DBG1(DBG_CFG, "error parsing string"); + return; + } + DBG1(DBG_CFG, "check out by id '%d'", id); + ike_sa = charon->ike_sa_manager->checkout_by_id(charon->ike_sa_manager, + id, child); + } + if (ike_sa == NULL) + { + DBG1(DBG_CFG, "no such IKE_SA found"); + return; + } + + if (!child) + { + status = ike_sa->delete(ike_sa); + } + else + { + child_sa_t *child_sa; + iterator_t *iterator = ike_sa->create_child_sa_iterator(ike_sa); + while (iterator->iterate(iterator, (void**)&child_sa)) + { + if ((id && id == child_sa->get_reqid(child_sa)) || + (string && streq(string, child_sa->get_name(child_sa)))) + { + u_int32_t spi = child_sa->get_spi(child_sa, TRUE); + protocol_id_t proto = child_sa->get_protocol(child_sa); + + status = ike_sa->delete_child_sa(ike_sa, proto, spi); + break; + } + } + iterator->destroy(iterator); + } + if (status == DESTROY_ME) + { + charon->ike_sa_manager->checkin_and_destroy(charon->ike_sa_manager, + ike_sa); + return; + } + charon->ike_sa_manager->checkin(charon->ike_sa_manager, ike_sa); +} + +/** + * Add a ca information record to the cainfo list + */ +static void stroke_add_ca(stroke_msg_t *msg, FILE *out) +{ + x509_t *cacert; + ca_info_t *ca_info; + + pop_string(msg, &msg->add_ca.name); + pop_string(msg, &msg->add_ca.cacert); + pop_string(msg, &msg->add_ca.crluri); + pop_string(msg, &msg->add_ca.crluri2); + pop_string(msg, &msg->add_ca.ocspuri); + pop_string(msg, &msg->add_ca.ocspuri2); + + DBG1(DBG_CFG, "received stroke: add ca '%s'", msg->add_ca.name); + + DBG2(DBG_CFG, "ca %s", msg->add_ca.name); + DBG2(DBG_CFG, " cacert=%s", msg->add_ca.cacert); + DBG2(DBG_CFG, " crluri=%s", msg->add_ca.crluri); + DBG2(DBG_CFG, " crluri2=%s", msg->add_ca.crluri2); + DBG2(DBG_CFG, " ocspuri=%s", msg->add_ca.ocspuri); + DBG2(DBG_CFG, " ocspuri2=%s", msg->add_ca.ocspuri2); + + if (msg->add_ca.cacert == NULL) + { + DBG1(DBG_CFG, "missing cacert parameter\n"); + return; + } + + cacert = load_ca_certificate(msg->add_ca.cacert); + + if (cacert == NULL) + { + return; + } + ca_info = ca_info_create(msg->add_ca.name, cacert); + + if (msg->add_ca.crluri) + { + chunk_t uri = { msg->add_ca.crluri, strlen(msg->add_ca.crluri) }; + + ca_info->add_crluri(ca_info, uri); + } + if (msg->add_ca.crluri2) + { + chunk_t uri = { msg->add_ca.crluri2, strlen(msg->add_ca.crluri2) }; + + ca_info->add_crluri(ca_info, uri); + } + if (msg->add_ca.ocspuri) + { + chunk_t uri = { msg->add_ca.ocspuri, strlen(msg->add_ca.ocspuri) }; + + ca_info->add_ocspuri(ca_info, uri); + } + if (msg->add_ca.ocspuri2) + { + chunk_t uri = { msg->add_ca.ocspuri2, strlen(msg->add_ca.ocspuri2) }; + + ca_info->add_ocspuri(ca_info, uri); + } + charon->credentials->add_ca_info(charon->credentials, ca_info); + DBG1(DBG_CFG, "added ca '%s'", msg->add_ca.name); + +} + +/** + * Delete a ca information record from the cainfo list + */ +static void stroke_del_ca(stroke_msg_t *msg, FILE *out) +{ + status_t status; + + pop_string(msg, &(msg->del_ca.name)); + DBG1(DBG_CFG, "received stroke: delete ca '%s'", msg->del_ca.name); + + status = charon->credentials->release_ca_info(charon->credentials, + msg->del_ca.name); + + if (status == SUCCESS) + { + fprintf(out, "deleted ca '%s'\n", msg->del_ca.name); + } + else + { + fprintf(out, "no ca named '%s'\n", msg->del_ca.name); + } +} + +/** + * show status of daemon + */ +static void stroke_statusall(stroke_msg_t *msg, FILE *out) +{ + iterator_t *iterator; + linked_list_t *list; + host_t *host; + connection_t *connection; + policy_t *policy; + ike_sa_t *ike_sa; + char *name = NULL; + + leak_detective_status(out); + + fprintf(out, "Performance:\n"); + fprintf(out, " worker threads: %d idle of %d,", + charon->thread_pool->get_idle_threads(charon->thread_pool), + charon->thread_pool->get_pool_size(charon->thread_pool)); + fprintf(out, " job queue load: %d,", + charon->job_queue->get_count(charon->job_queue)); + fprintf(out, " scheduled events: %d\n", + charon->event_queue->get_count(charon->event_queue)); + list = charon->kernel_interface->create_address_list(charon->kernel_interface); + + fprintf(out, "Listening on %d IP addresses:\n", list->get_count(list)); + while (list->remove_first(list, (void**)&host) == SUCCESS) + { + fprintf(out, " %H\n", host); + host->destroy(host); + } + list->destroy(list); + + if (msg->status.name) + { + pop_string(msg, &(msg->status.name)); + name = msg->status.name; + } + + iterator = charon->connections->create_iterator(charon->connections); + if (iterator->get_count(iterator) > 0) + { + fprintf(out, "Connections:\n"); + } + while (iterator->iterate(iterator, (void**)&connection)) + { + if (connection->is_ikev2(connection) + && (name == NULL || streq(name, connection->get_name(connection)))) + { + fprintf(out, "%12s: %H...%H\n", + connection->get_name(connection), + connection->get_my_host(connection), + connection->get_other_host(connection)); + } + } + iterator->destroy(iterator); + + iterator = charon->policies->create_iterator(charon->policies); + if (iterator->get_count(iterator) > 0) + { + fprintf(out, "Policies:\n"); + } + while (iterator->iterate(iterator, (void**)&policy)) + { + if (name == NULL || streq(name, policy->get_name(policy))) + { + fprintf(out, "%12s: '%D'...'%D'\n", + policy->get_name(policy), + policy->get_my_id(policy), + policy->get_other_id(policy)); + } + } + iterator->destroy(iterator); + + iterator = charon->ike_sa_manager->create_iterator(charon->ike_sa_manager); + if (iterator->get_count(iterator) > 0) + { + fprintf(out, "Security Associations:\n"); + } + while (iterator->iterate(iterator, (void**)&ike_sa)) + { + bool ike_sa_printed = FALSE; + child_sa_t *child_sa; + iterator_t *children = ike_sa->create_child_sa_iterator(ike_sa); + + /* print IKE_SA */ + if (name == NULL || strncmp(name, ike_sa->get_name(ike_sa), strlen(name)) == 0) + { + fprintf(out, "%#K\n", ike_sa); + ike_sa_printed = TRUE; + } + + while (children->iterate(children, (void**)&child_sa)) + { + bool child_sa_match = name == NULL || + strncmp(name, child_sa->get_name(child_sa), strlen(name)) == 0; + + /* print IKE_SA if its name differs from the CHILD_SA's name */ + if (!ike_sa_printed && child_sa_match) + { + fprintf(out, "%#K\n", ike_sa); + ike_sa_printed = TRUE; + } + + /* print CHILD_SA */ + if (child_sa_match) + { + fprintf(out, "%#P\n", child_sa); + } + } + children->destroy(children); + } + iterator->destroy(iterator); +} + +/** + * show status of daemon + */ +static void stroke_status(stroke_msg_t *msg, FILE *out) +{ + iterator_t *iterator; + ike_sa_t *ike_sa; + char *name = NULL; + + if (msg->status.name) + { + pop_string(msg, &(msg->status.name)); + name = msg->status.name; + } + + iterator = charon->ike_sa_manager->create_iterator(charon->ike_sa_manager); + while (iterator->iterate(iterator, (void**)&ike_sa)) + { + bool ike_sa_printed = FALSE; + child_sa_t *child_sa; + iterator_t *children = ike_sa->create_child_sa_iterator(ike_sa); + + /* print IKE_SA */ + if (name == NULL || strncmp(name, ike_sa->get_name(ike_sa), strlen(name)) == 0) + { + fprintf(out, "%K\n", ike_sa); + ike_sa_printed = TRUE; + } + + while (children->iterate(children, (void**)&child_sa)) + { + bool child_sa_match = name == NULL || + strncmp(name, child_sa->get_name(child_sa), strlen(name)) == 0; + + /* print IKE_SA if its name differs from the CHILD_SA's name */ + if (!ike_sa_printed && child_sa_match) + { + fprintf(out, "%K\n", ike_sa); + ike_sa_printed = TRUE; + } + + /* print CHILD_SA */ + if (child_sa_match) + { + fprintf(out, "%P\n", child_sa); + } + } + children->destroy(children); + } + iterator->destroy(iterator); +} + +/** + * list all authority certificates matching a specified flag + */ +static void list_auth_certificates(u_int flag, const char *label, bool utc, FILE *out) +{ + bool first = TRUE; + x509_t *cert; + + iterator_t *iterator = charon->credentials->create_auth_cert_iterator(charon->credentials); + + while (iterator->iterate(iterator, (void**)&cert)) + { + if (cert->has_authority_flag(cert, flag)) + { + if (first) + { + fprintf(out, "\n"); + fprintf(out, "List of X.509 %s Certificates:\n", label); + fprintf(out, "\n"); + first = FALSE; + } + fprintf(out, "%#Q\n", cert, utc); + } + } + iterator->destroy(iterator); +} + +/** + * list various information + */ +static void stroke_list(stroke_msg_t *msg, FILE *out) +{ + iterator_t *iterator; + + if (msg->list.flags & LIST_CERTS) + { + x509_t *cert; + + iterator = charon->credentials->create_cert_iterator(charon->credentials); + if (iterator->get_count(iterator)) + { + fprintf(out, "\n"); + fprintf(out, "List of X.509 End Entity Certificates:\n"); + fprintf(out, "\n"); + } + while (iterator->iterate(iterator, (void**)&cert)) + { + fprintf(out, "%#Q", cert, msg->list.utc); + if (charon->credentials->has_rsa_private_key( + charon->credentials, cert->get_public_key(cert))) + { + fprintf(out, ", has private key"); + } + fprintf(out, "\n"); + + } + iterator->destroy(iterator); + } + if (msg->list.flags & LIST_CACERTS) + { + list_auth_certificates(AUTH_CA, "CA", msg->list.utc, out); + } + if (msg->list.flags & LIST_CAINFOS) + { + ca_info_t *ca_info; + + iterator = charon->credentials->create_cainfo_iterator(charon->credentials); + if (iterator->get_count(iterator)) + { + fprintf(out, "\n"); + fprintf(out, "List of X.509 CA Information Records:\n"); + fprintf(out, "\n"); + } + while (iterator->iterate(iterator, (void**)&ca_info)) + { + fprintf(out, "%#W", ca_info, msg->list.utc); + } + iterator->destroy(iterator); + } + if (msg->list.flags & LIST_CRLS) + { + ca_info_t *ca_info; + bool first = TRUE; + + iterator = charon->credentials->create_cainfo_iterator(charon->credentials); + + while (iterator->iterate(iterator, (void **)&ca_info)) + { + if (ca_info->has_crl(ca_info)) + { + if (first) + { + fprintf(out, "\n"); + fprintf(out, "List of X.509 CRLs:\n"); + fprintf(out, "\n"); + first = FALSE; + } + ca_info->list_crl(ca_info, out, msg->list.utc); + } + } + iterator->destroy(iterator); + } + if (msg->list.flags & LIST_OCSPCERTS) + { + list_auth_certificates(AUTH_OCSP, "OCSP", msg->list.utc, out); + } + if (msg->list.flags & LIST_OCSP) + { + ca_info_t *ca_info; + bool first = TRUE; + + iterator = charon->credentials->create_cainfo_iterator(charon->credentials); + + while (iterator->iterate(iterator, (void **)&ca_info)) + { + if (ca_info->has_certinfos(ca_info)) + { + if (first) + { + fprintf(out, "\n"); + fprintf(out, "List of OCSP responses:\n"); + first = FALSE; + } + fprintf(out, "\n"); + ca_info->list_certinfos(ca_info, out, msg->list.utc); + } + } + iterator->destroy(iterator); + } +} + +/** + * reread various information + */ +static void stroke_reread(stroke_msg_t *msg, FILE *out) +{ + if (msg->reread.flags & REREAD_CACERTS) + { + charon->credentials->load_ca_certificates(charon->credentials); + } + if (msg->reread.flags & REREAD_OCSPCERTS) + { + charon->credentials->load_ocsp_certificates(charon->credentials); + } + if (msg->reread.flags & REREAD_CRLS) + { + charon->credentials->load_crls(charon->credentials); + } +} + +/** + * purge various information + */ +static void stroke_purge(stroke_msg_t *msg, FILE *out) +{ + if (msg->purge.flags & PURGE_OCSP) + { + iterator_t *iterator = charon->credentials->create_cainfo_iterator(charon->credentials); + ca_info_t *ca_info; + + while (iterator->iterate(iterator, (void**)&ca_info)) + { + ca_info->purge_ocsp(ca_info); + } + iterator->destroy(iterator); + } +} + +signal_t get_signal_from_logtype(char *type) +{ + if (strcasecmp(type, "any") == 0) return SIG_ANY; + else if (strcasecmp(type, "mgr") == 0) return DBG_MGR; + else if (strcasecmp(type, "ike") == 0) return DBG_IKE; + else if (strcasecmp(type, "chd") == 0) return DBG_CHD; + else if (strcasecmp(type, "job") == 0) return DBG_JOB; + else if (strcasecmp(type, "cfg") == 0) return DBG_CFG; + else if (strcasecmp(type, "knl") == 0) return DBG_KNL; + else if (strcasecmp(type, "net") == 0) return DBG_NET; + else if (strcasecmp(type, "enc") == 0) return DBG_ENC; + else if (strcasecmp(type, "lib") == 0) return DBG_LIB; + else return -1; +} + +/** + * set the verbosity debug output + */ +static void stroke_loglevel(stroke_msg_t *msg, FILE *out) +{ + signal_t signal; + + pop_string(msg, &(msg->loglevel.type)); + DBG1(DBG_CFG, "received stroke: loglevel %d for %s", + msg->loglevel.level, msg->loglevel.type); + + signal = get_signal_from_logtype(msg->loglevel.type); + if (signal < 0) + { + fprintf(out, "invalid type (%s)!\n", msg->loglevel.type); + return; + } + + charon->outlog->set_level(charon->outlog, signal, msg->loglevel.level); + charon->syslog->set_level(charon->syslog, signal, msg->loglevel.level); +} + +/** + * process a stroke request from the socket pointed by "fd" + */ +static void stroke_process(int *fd) +{ + stroke_msg_t *msg; + u_int16_t msg_length; + ssize_t bytes_read; + FILE *out; + int strokefd = *fd; + + /* peek the length */ + bytes_read = recv(strokefd, &msg_length, sizeof(msg_length), MSG_PEEK); + if (bytes_read != sizeof(msg_length)) + { + DBG1(DBG_CFG, "reading length of stroke message failed"); + close(strokefd); + return; + } + + /* read message */ + msg = malloc(msg_length); + bytes_read = recv(strokefd, msg, msg_length, 0); + if (bytes_read != msg_length) + { + DBG1(DBG_CFG, "reading stroke message failed: %m"); + close(strokefd); + return; + } + + out = fdopen(dup(strokefd), "w"); + if (out == NULL) + { + DBG1(DBG_CFG, "opening stroke output channel failed: %m"); + close(strokefd); + free(msg); + return; + } + + DBG3(DBG_CFG, "stroke message %b", (void*)msg, msg_length); + + switch (msg->type) + { + case STR_INITIATE: + stroke_initiate(msg, out); + break; + case STR_ROUTE: + stroke_route(msg, out, TRUE); + break; + case STR_UNROUTE: + stroke_route(msg, out, FALSE); + break; + case STR_TERMINATE: + stroke_terminate(msg, out); + break; + case STR_STATUS: + stroke_status(msg, out); + break; + case STR_STATUS_ALL: + stroke_statusall(msg, out); + break; + case STR_ADD_CONN: + stroke_add_conn(msg, out); + break; + case STR_DEL_CONN: + stroke_del_conn(msg, out); + break; + case STR_ADD_CA: + stroke_add_ca(msg, out); + break; + case STR_DEL_CA: + stroke_del_ca(msg, out); + break; + case STR_LOGLEVEL: + stroke_loglevel(msg, out); + break; + case STR_LIST: + stroke_list(msg, out); + break; + case STR_REREAD: + stroke_reread(msg, out); + break; + case STR_PURGE: + stroke_purge(msg, out); + break; + default: + DBG1(DBG_CFG, "received unknown stroke"); + } + fclose(out); + close(strokefd); + free(msg); +} + +/** + * Implementation of private_stroke_t.stroke_receive. + */ +static void stroke_receive(private_stroke_t *this) +{ + struct sockaddr_un strokeaddr; + int strokeaddrlen = sizeof(strokeaddr); + int strokefd; + int oldstate; + pthread_t thread; + + /* ignore sigpipe. writing over the pipe back to the console + * only fails if SIGPIPE is ignored. */ + signal(SIGPIPE, SIG_IGN); + + /* disable cancellation by default */ + pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL); + + while (TRUE) + { + /* wait for connections, but allow thread to terminate */ + pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldstate); + strokefd = accept(this->socket, (struct sockaddr *)&strokeaddr, &strokeaddrlen); + pthread_setcancelstate(oldstate, NULL); + + if (strokefd < 0) + { + DBG1(DBG_CFG, "accepting stroke connection failed: %m"); + continue; + } + + /* handle request asynchronously */ + if (pthread_create(&thread, NULL, (void*(*)(void*))stroke_process, (void*)&strokefd) != 0) + { + DBG1(DBG_CFG, "failed to spawn stroke thread: %m"); + } + /* detach so the thread terminates cleanly */ + pthread_detach(thread); + } +} + +/** + * Implementation of stroke_t.destroy. + */ +static void destroy(private_stroke_t *this) +{ + pthread_cancel(this->assigned_thread); + pthread_join(this->assigned_thread, NULL); + + close(this->socket); + unlink(socket_addr.sun_path); + free(this); +} + +/* + * Described in header-file + */ +stroke_t *stroke_create() +{ + private_stroke_t *this = malloc_thing(private_stroke_t); + mode_t old; + + /* public functions */ + this->public.destroy = (void (*)(stroke_t*))destroy; + + /* set up unix socket */ + this->socket = socket(AF_UNIX, SOCK_STREAM, 0); + if (this->socket == -1) + { + DBG1(DBG_CFG, "could not create whack socket"); + free(this); + return NULL; + } + + old = umask(~S_IRWXU); + if (bind(this->socket, (struct sockaddr *)&socket_addr, sizeof(socket_addr)) < 0) + { + DBG1(DBG_CFG, "could not bind stroke socket: %m"); + close(this->socket); + free(this); + return NULL; + } + umask(old); + + if (listen(this->socket, 0) < 0) + { + DBG1(DBG_CFG, "could not listen on stroke socket: %m"); + close(this->socket); + unlink(socket_addr.sun_path); + free(this); + return NULL; + } + + /* start a thread reading from the socket */ + if (pthread_create(&(this->assigned_thread), NULL, (void*(*)(void*))stroke_receive, this) != 0) + { + DBG1(DBG_CFG, "could not spawn stroke thread"); + close(this->socket); + unlink(socket_addr.sun_path); + free(this); + return NULL; + } + + return (&this->public); +} diff --git a/src/charon/threads/stroke_interface.h b/src/charon/threads/stroke_interface.h new file mode 100644 index 000000000..0def5167e --- /dev/null +++ b/src/charon/threads/stroke_interface.h @@ -0,0 +1,61 @@ +/** + * @file stroke.h + * + * @brief Interface of stroke_t. + * + */ + +/* + * Copyright (C) 2006 Martin Willi + * Hochschule fuer Technik Rapperswil + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * for more details. + */ + +#ifndef STROKE_INTERFACE_H_ +#define STROKE_INTERFACE_H_ + +typedef struct stroke_t stroke_t; + +/** + * @brief Stroke is a configuration and control interface which + * allows other processes to modify charons behavior. + * + * stroke_t allows config manipulation (as whack in pluto). + * Messages of type stroke_msg_t's are sent over a unix socket + * (/var/run/charon.ctl). + * + * @b Constructors: + * - stroke_create() + * + * @ingroup threads + */ +struct stroke_t { + + /** + * @brief Destroy a stroke_t instance. + * + * @param this stroke_t objec to destroy + */ + void (*destroy) (stroke_t *this); +}; + + +/** + * @brief Create the stroke interface and listen on the socket. + * + * @return stroke_t object + * + * @ingroup threads + */ +stroke_t *stroke_create(void); + +#endif /* STROKE_INTERFACE_H_ */ diff --git a/src/charon/threads/thread_pool.c b/src/charon/threads/thread_pool.c new file mode 100644 index 000000000..052b5aab9 --- /dev/null +++ b/src/charon/threads/thread_pool.c @@ -0,0 +1,181 @@ +/** + * @file thread_pool.c + * + * @brief Implementation of thread_pool_t. + * + */ + +/* + * Copyright (C) 2005-2006 Martin Willi + * Copyright (C) 2005 Jan Hutter + * Hochschule fuer Technik Rapperswil + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * for more details. + */ + +#include <stdlib.h> +#include <pthread.h> +#include <string.h> +#include <errno.h> + +#include "thread_pool.h" + +#include <daemon.h> +#include <queues/job_queue.h> + + +typedef struct private_thread_pool_t private_thread_pool_t; + +/** + * @brief Private data of thread_pool_t class. + */ +struct private_thread_pool_t { + /** + * Public thread_pool_t interface. + */ + thread_pool_t public; + + /** + * Number of running threads. + */ + u_int pool_size; + + /** + * Number of threads waiting for work + */ + u_int idle_threads; + + /** + * Array of thread ids. + */ + pthread_t *threads; +} ; + +/** + * Implementation of private_thread_pool_t.process_jobs. + */ +static void process_jobs(private_thread_pool_t *this) +{ + job_t *job; + status_t status; + + /* cancellation disabled by default */ + pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL); + + DBG1(DBG_JOB, "worker thread running, thread_ID: %06u", + (int)pthread_self()); + + while (TRUE) + { + /* TODO: should be atomic, but is not mission critical */ + this->idle_threads++; + job = charon->job_queue->get(charon->job_queue); + this->idle_threads--; + + status = job->execute(job); + + if (status == DESTROY_ME) + { + job->destroy(job); + } + } +} + +/** + * Implementation of thread_pool_t.get_pool_size. + */ +static u_int get_pool_size(private_thread_pool_t *this) +{ + return this->pool_size; +} + +/** + * Implementation of thread_pool_t.get_idle_threads. + */ +static u_int get_idle_threads(private_thread_pool_t *this) +{ + return this->idle_threads; +} + +/** + * Implementation of thread_pool_t.destroy. + */ +static void destroy(private_thread_pool_t *this) +{ + int current; + /* flag thread for termination */ + for (current = 0; current < this->pool_size; current++) + { + DBG1(DBG_JOB, "cancelling worker thread #%d", current+1); + pthread_cancel(this->threads[current]); + } + + /* wait for all threads */ + for (current = 0; current < this->pool_size; current++) { + if (pthread_join(this->threads[current], NULL) == 0) + { + DBG1(DBG_JOB, "worker thread #%d terminated", current+1); + } + else + { + DBG1(DBG_JOB, "could not terminate worker thread #%d", current+1); + } + } + + /* free mem */ + free(this->threads); + free(this); +} + +/* + * Described in header. + */ +thread_pool_t *thread_pool_create(size_t pool_size) +{ + int current; + private_thread_pool_t *this = malloc_thing(private_thread_pool_t); + + /* fill in public fields */ + this->public.destroy = (void(*)(thread_pool_t*))destroy; + this->public.get_pool_size = (u_int(*)(thread_pool_t*))get_pool_size; + this->public.get_idle_threads = (u_int(*)(thread_pool_t*))get_idle_threads; + + /* initialize member */ + this->pool_size = pool_size; + this->idle_threads = 0; + this->threads = malloc(sizeof(pthread_t) * pool_size); + + /* try to create as many threads as possible, up to pool_size */ + for (current = 0; current < pool_size; current++) + { + if (pthread_create(&(this->threads[current]), NULL, + (void*(*)(void*))process_jobs, this) == 0) + { + DBG1(DBG_JOB, "created worker thread #%d", current+1); + } + else + { + /* creation failed, is it the first one? */ + if (current == 0) + { + free(this->threads); + free(this); + charon->kill(charon, "could not create any worker threads"); + } + /* not all threads could be created, but at least one :-/ */ + DBG1(DBG_JOB, "could only create %d from requested %d threads!", + current, pool_size); + this->pool_size = current; + break; + } + } + return (thread_pool_t*)this; +} diff --git a/src/charon/threads/thread_pool.h b/src/charon/threads/thread_pool.h new file mode 100644 index 000000000..8e1989bda --- /dev/null +++ b/src/charon/threads/thread_pool.h @@ -0,0 +1,87 @@ +/** + * @file thread_pool.h + * + * @brief Interface of thread_pool_t. + * + */ + +/* + * Copyright (C) 2005-2006 Martin Willi + * Copyright (C) 2005 Jan Hutter + * Hochschule fuer Technik Rapperswil + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * for more details. + */ + +#ifndef THREAD_POOL_H_ +#define THREAD_POOL_H_ + +typedef struct thread_pool_t thread_pool_t; + +#include <stdlib.h> + +#include <library.h> + +/** + * @brief A thread_pool consists of a pool of threads processing jobs from the job queue. + * + * Current implementation uses as many threads as specified in constructor. + * A more improved version would dynamically increase thread count if necessary. + * + * @b Constructors: + * - thread_pool_create() + * + * @todo Add support for dynamic thread handling + * + * @ingroup threads + */ +struct thread_pool_t { + + /** + * @brief Return currently instanciated thread count. + * + * @param thread_pool calling object + * @return size of thread pool + */ + u_int (*get_pool_size) (thread_pool_t *thread_pool); + + /** + * @brief Get the number of threads currently waiting for work. + * + * @param thread_pool calling object + * @return number of idle threads + */ + u_int (*get_idle_threads) (thread_pool_t *thread_pool); + + /** + * @brief Destroy a thread_pool_t object. + * + * Sends cancellation request to all threads and AWAITS their termination. + * + * @param thread_pool calling object + */ + void (*destroy) (thread_pool_t *thread_pool); +}; + +/** + * @brief Create the thread pool using using pool_size of threads. + * + * @param pool_size desired pool size + * @return + * - thread_pool_t object if one ore more threads could be started, or + * - NULL if no threads could be created + * + * @ingroup threads + */ +thread_pool_t *thread_pool_create(size_t pool_size); + + +#endif /*THREAD_POOL_H_*/ |