debug and logging improvements
[strongswan.git] / src / charon / network / socket.c
1 /**
2 * @file socket.c
3 *
4 * @brief Implementation of socket_t.
5 *
6 */
7
8 /*
9 * Copyright (C) 2005 Jan Hutter, Martin Willi
10 * Hochschule fuer Technik Rapperswil
11 * Copyright (C) 1998-2002 D. Hugh Redelmeier.
12 * Copyright (C) 1997 Angelos D. Keromytis.
13 *
14 * Some parts of interface lookup code from pluto.
15 *
16 * This program is free software; you can redistribute it and/or modify it
17 * under the terms of the GNU General Public License as published by the
18 * Free Software Foundation; either version 2 of the License, or (at your
19 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
20 *
21 * This program is distributed in the hope that it will be useful, but
22 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
23 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
24 * for more details.
25 */
26
27 #include <pthread.h>
28 #include <sys/types.h>
29 #include <sys/socket.h>
30 #include <string.h>
31 #include <errno.h>
32 #include <unistd.h>
33 #include <stdlib.h>
34 #include <fcntl.h>
35 #include <net/if.h>
36 #include <sys/ioctl.h>
37 #include <netinet/in.h>
38 #include <linux/filter.h>
39
40 #include "socket.h"
41
42 #include <daemon.h>
43 #include <utils/logger_manager.h>
44
45
46 #define IP_HEADER_LENGTH 20
47 #define UDP_HEADER_LENGTH 8
48
49
50 /**
51 * This filter code filters out all non-IKEv2 traffic on
52 * a SOCK_RAW IP_PROTP_UDP socket. Handling of other
53 * IKE versions is done in pluto.
54 */
55 struct sock_filter ikev2_filter_code[] =
56 {
57 /* Protocol must be UDP */
58 BPF_STMT(BPF_LD+BPF_B+BPF_ABS, 9),
59 BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, IPPROTO_UDP, 0, 7),
60 /* Destination Port must be 500 */
61 BPF_STMT(BPF_LD+BPF_H+BPF_ABS, 22),
62 BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 500, 0, 5),
63 /* IKE version must be 2.0 */
64 BPF_STMT(BPF_LD+BPF_B+BPF_ABS, 45),
65 BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0x20, 0, 3),
66 /* packet length is length in IKEv2 header + ip header + udp header */
67 BPF_STMT(BPF_LD+BPF_W+BPF_ABS, 52),
68 BPF_STMT(BPF_ALU+BPF_ADD+BPF_K, IP_HEADER_LENGTH + UDP_HEADER_LENGTH),
69 BPF_STMT(BPF_RET+BPF_A, 0),
70 /* packet doesn't match IKEv2, ignore */
71 BPF_STMT(BPF_RET+BPF_K, 0),
72 };
73
74 /**
75 * Filter struct to use with setsockopt
76 */
77 struct sock_fprog ikev2_filter = {
78 sizeof(ikev2_filter_code) / sizeof(struct sock_filter),
79 ikev2_filter_code
80 };
81
82
83 typedef struct interface_t interface_t;
84
85 /**
86 * An interface on which we listen.
87 */
88 struct interface_t {
89
90 /**
91 * Name of the interface
92 */
93 char name[IFNAMSIZ];
94
95 /**
96 * Associated socket
97 */
98 int socket_fd;
99
100 /**
101 * Host with listening address
102 */
103 host_t *address;
104 };
105
106 typedef struct private_socket_t private_socket_t;
107
108 /**
109 * Private data of an socket_t object
110 */
111 struct private_socket_t{
112 /**
113 * public functions
114 */
115 socket_t public;
116
117 /**
118 * Master socket
119 */
120 int master_fd;
121
122 /**
123 * List of all socket to listen
124 */
125 linked_list_t* interfaces;
126
127 /**
128 * logger for this socket
129 */
130 logger_t *logger;
131 };
132
133 /**
134 * implementation of socket_t.receive
135 */
136 static status_t receiver(private_socket_t *this, packet_t **packet)
137 {
138 char buffer[MAX_PACKET];
139 chunk_t data;
140 packet_t *pkt;
141 host_t *source, *dest;
142 int bytes_read = 0;
143
144
145 while (bytes_read >= 0)
146 {
147 int max_fd = 1;
148 fd_set readfds;
149 iterator_t *iterator;
150 int oldstate;
151 interface_t *interface;
152
153 /* build fd_set */
154 FD_ZERO(&readfds);
155 iterator = this->interfaces->create_iterator(this->interfaces, TRUE);
156 while (iterator->has_next(iterator))
157 {
158 iterator->current(iterator, (void**)&interface);
159 FD_SET(interface->socket_fd, &readfds);
160 if (interface->socket_fd > max_fd)
161 {
162 max_fd = interface->socket_fd + 1;
163 }
164 }
165 iterator->destroy(iterator);
166
167 this->logger->log(this->logger, CONTROL|LEVEL1, "waiting on sockets");
168
169 /* allow cancellation while select()-ing */
170 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldstate);
171 bytes_read = select(max_fd, &readfds, NULL, NULL, NULL);
172 pthread_setcancelstate(oldstate, NULL);
173
174 /* read on the first nonblocking socket */
175 bytes_read = 0;
176 iterator = this->interfaces->create_iterator(this->interfaces, TRUE);
177 while (iterator->has_next(iterator))
178 {
179 iterator->current(iterator, (void**)&interface);
180 if (FD_ISSET(interface->socket_fd, &readfds))
181 {
182 /* do the read */
183 bytes_read = recv(interface->socket_fd, buffer, MAX_PACKET, 0);
184 break;
185 }
186 }
187 iterator->destroy(iterator);
188
189 if (bytes_read < 0)
190 {
191 this->logger->log(this->logger, ERROR, "error reading from socket: %s", strerror(errno));
192 continue;
193 }
194 /* insert a delay to simulate small bandwith/RTT */
195 #ifdef PACKET_RECV_DELAY
196 usleep(PACKET_RECV_DELAY * 1000);
197 #endif
198 /* simulate packet loss of every PACKET_RECV_LOSS'th packet */
199 #ifdef PACKET_RECV_LOSS
200 srandom(time(NULL) + getpid());
201 if (random() % PACKET_RECV_LOSS == 0)
202 {
203 return SUCCESS;
204 }
205 #endif
206 if (bytes_read > IP_HEADER_LENGTH + UDP_HEADER_LENGTH)
207 {
208 /* read source/dest from raw IP/UDP header */
209 chunk_t source_chunk = {buffer + 12, 4};
210 chunk_t dest_chunk = {buffer + 16, 4};
211 u_int16_t source_port = ntohs(*(u_int16_t*)(buffer + 20));
212 u_int16_t dest_port = ntohs(*(u_int16_t*)(buffer + 22));
213 source = host_create_from_chunk(AF_INET, source_chunk, source_port);
214 dest = host_create_from_chunk(AF_INET, dest_chunk, dest_port);
215 pkt = packet_create();
216 pkt->set_source(pkt, source);
217 pkt->set_destination(pkt, dest);
218 break;
219 }
220 this->logger->log(this->logger, ERROR|LEVEL1, "too short packet received");
221 }
222
223 this->logger->log(this->logger, CONTROL, "received packet: from %s:%d to %s:%d",
224 source->get_address(source), source->get_port(source),
225 dest->get_address(dest), dest->get_port(dest));
226
227 /* fill in packet */
228 data.len = bytes_read - IP_HEADER_LENGTH - UDP_HEADER_LENGTH;
229 data.ptr = malloc(data.len);
230 memcpy(data.ptr, buffer + IP_HEADER_LENGTH + UDP_HEADER_LENGTH, data.len);
231 pkt->set_data(pkt, data);
232
233 /* return packet */
234 *packet = pkt;
235
236 return SUCCESS;
237 }
238
239 /**
240 * implementation of socket_t.send
241 */
242 status_t sender(private_socket_t *this, packet_t *packet)
243 {
244 ssize_t bytes_sent;
245 chunk_t data;
246 host_t *src, *dst;
247
248 src = packet->get_source(packet);
249 dst = packet->get_destination(packet);
250 data = packet->get_data(packet);
251
252 this->logger->log(this->logger, CONTROL, "sending packet: from %s:%d to %s:%d",
253 src->get_address(src), src->get_port(src),
254 dst->get_address(dst), dst->get_port(dst));
255 /* insert a delay to simulate small bandwith/RTT */
256 #ifdef PACKET_SEND_DELAY
257 usleep(PACKET_SEND_DELAY * 1000);
258 #endif
259 /* simulate packet loss of every PACKET_LOSS'th packet */
260 #ifdef PACKET_SEND_LOSS
261 srandom(time(NULL) + getpid());
262 if (random() % PACKET_SEND_LOSS == 0)
263 {
264 return SUCCESS;
265 }
266 #endif
267 /* send data */
268 bytes_sent = sendto(this->master_fd, data.ptr, data.len, 0,
269 dst->get_sockaddr(dst), *(dst->get_sockaddr_len(dst)));
270
271 if (bytes_sent != data.len)
272 {
273 this->logger->log(this->logger, ERROR, "error writing to socket: %s", strerror(errno));
274 return FAILED;
275 }
276 return SUCCESS;
277 }
278
279 /**
280 * Find all suitable interfaces, bind them and add them to the list
281 */
282 static status_t build_interface_list(private_socket_t *this, u_int16_t port)
283 {
284 int on = TRUE;
285 int i;
286 struct sockaddr_in addr;
287 struct ifconf ifconf;
288 struct ifreq buf[300];
289
290 /* master socket for querying socket for a specific interfaces */
291 this->master_fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
292 if (this->master_fd == -1)
293 {
294 this->logger->log(this->logger, ERROR, "could not open IPv4 master socket!");
295 return FAILED;
296 }
297
298 /* allow binding of multiplo sockets */
299 if (setsockopt(this->master_fd, SOL_SOCKET, SO_REUSEADDR, (void*)&on, sizeof(on)) < 0)
300 {
301 this->logger->log(this->logger, ERROR, "unable to set SO_REUSEADDR on master socket!");
302 return FAILED;
303 }
304
305 /* bind the master socket */
306 addr.sin_family = AF_INET;
307 addr.sin_addr.s_addr = INADDR_ANY;
308 addr.sin_port = htons(port);
309 if (bind(this->master_fd,(struct sockaddr*)&addr, sizeof(addr)) < 0)
310 {
311 this->logger->log(this->logger, ERROR, "unable to bind master socket: %s!", strerror(errno));
312 return FAILED;
313 }
314
315 /* get all interfaces */
316 ifconf.ifc_len = sizeof(buf);
317 ifconf.ifc_buf = (void*) buf;
318 memset(buf, 0, sizeof(buf));
319 if (ioctl(this->master_fd, SIOCGIFCONF, &ifconf) == -1)
320 {
321 this->logger->log(this->logger, ERROR, "unable to get interfaces!");
322 return FAILED;
323 }
324
325 /* add every interesting interfaces to our interface list */
326 for (i = 0; (i+1) * sizeof(*buf) <= (size_t)ifconf.ifc_len; i++)
327 {
328 struct sockaddr_in *current = (struct sockaddr_in*) &buf[i].ifr_addr;
329 struct ifreq auxinfo;
330 int skt;
331 interface_t *interface;
332
333 if (current->sin_family != AF_INET && current->sin_family != AF_INET6)
334 {
335 /* ignore all but IPv4 and IPv6 interfaces */
336 continue;
337 }
338
339 /* get auxilary info about socket */
340 memset(&auxinfo, 0, sizeof(auxinfo));
341 memcpy(auxinfo.ifr_name, buf[i].ifr_name, IFNAMSIZ);
342 if (ioctl(this->master_fd, SIOCGIFFLAGS, &auxinfo) == -1)
343 {
344 this->logger->log(this->logger, ERROR, "unable to SIOCGIFFLAGS master socket!");
345 continue;
346 }
347 if (!(auxinfo.ifr_flags & IFF_UP))
348 {
349 /* ignore an interface that isn't up */
350 continue;
351 }
352 if (current->sin_addr.s_addr == 0)
353 {
354 /* ignore unconfigured interfaces */
355 continue;
356 }
357
358 /* set up interface socket */
359 skt = socket(current->sin_family, SOCK_RAW, IPPROTO_UDP);
360 if (socket < 0)
361 {
362 this->logger->log(this->logger, ERROR, "unable to open interface socket!");
363 continue;
364 }
365 if (setsockopt(skt, SOL_SOCKET, SO_REUSEADDR, (void*)&on, sizeof(on)) < 0)
366 {
367 this->logger->log(this->logger, ERROR, "unable to set SO_REUSEADDR on interface socket!");
368 close(skt);
369 continue;
370 }
371 current->sin_port = htons(port);
372
373 if (bind(skt, (struct sockaddr*)current, sizeof(struct sockaddr_in)) < 0)
374 {
375 this->logger->log(this->logger, ERROR, "unable to bind interface socket!");
376 close(skt);
377 continue;
378 }
379
380 if (setsockopt(skt, SOL_SOCKET, SO_ATTACH_FILTER, &ikev2_filter, sizeof(ikev2_filter)) < 0)
381 {
382 this->logger->log(this->logger, ERROR, "unable to attack IKEv2 filter to interface socket!");
383 close(skt);
384 continue;
385 }
386
387 /* add socket with interface name to list */
388 interface = malloc_thing(interface_t);
389 strncpy(interface->name, buf[i].ifr_name, IFNAMSIZ);
390 interface->socket_fd = skt;
391 interface->address = host_create_from_sockaddr((struct sockaddr*)current);
392 this->logger->log(this->logger, CONTROL, "listening on %s (%s)",
393 interface->name, interface->address->get_address(interface->address));
394 this->interfaces->insert_last(this->interfaces, (void*)interface);
395 }
396
397 if (this->interfaces->get_count(this->interfaces) == 0)
398 {
399 this->logger->log(this->logger, ERROR, "unable to find any usable interface!");
400 return FAILED;
401 }
402 return SUCCESS;
403 }
404
405 /**
406 * implementation of socket_t.is_listening_on
407 */
408 static bool is_listening_on(private_socket_t *this, host_t *host)
409 {
410 iterator_t *iterator;
411
412 /* listening on wildcard 0.0.0.0 is always FALSE */
413 if (host->is_anyaddr(host))
414 return FALSE;
415
416 /* compare host with all interfaces */
417 iterator = this->interfaces->create_iterator(this->interfaces, TRUE);
418 while (iterator->has_next(iterator))
419 {
420 interface_t *interface;
421 iterator->current(iterator, (void**)&interface);
422 if (host->equals(host, interface->address))
423 {
424 iterator->destroy(iterator);
425 return TRUE;
426 }
427 }
428 iterator->destroy(iterator);
429 return FALSE;
430 }
431
432 /**
433 * implementation of socket_t.destroy
434 */
435 static void destroy(private_socket_t *this)
436 {
437 interface_t *interface;
438 while (this->interfaces->remove_last(this->interfaces, (void**)&interface) == SUCCESS)
439 {
440 interface->address->destroy(interface->address);
441 close(interface->socket_fd);
442 free(interface);
443 }
444 this->interfaces->destroy(this->interfaces);
445 close(this->master_fd);
446 free(this);
447 }
448
449 /*
450 * See header for description
451 */
452 socket_t *socket_create(u_int16_t port)
453 {
454 private_socket_t *this = malloc_thing(private_socket_t);
455
456 /* public functions */
457 this->public.send = (status_t(*)(socket_t*, packet_t*))sender;
458 this->public.receive = (status_t(*)(socket_t*, packet_t**))receiver;
459 this->public.is_listening_on = (bool (*)(socket_t*,host_t*))is_listening_on;
460 this->public.destroy = (void(*)(socket_t*)) destroy;
461
462 this->logger = logger_manager->get_logger(logger_manager, SOCKET);
463 this->interfaces = linked_list_create();
464
465 if (build_interface_list(this, port) != SUCCESS)
466 {
467 this->interfaces->destroy(this->interfaces);
468 free(this);
469 charon->kill(charon, "could not bind any interface!");
470 }
471
472 return (socket_t*)this;
473 }