- fixed some memleaks/freebugs
[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 if (bytes_read > IP_HEADER_LENGTH + UDP_HEADER_LENGTH)
195 {
196 /* read source/dest from raw IP/UDP header */
197 chunk_t source_chunk = {buffer + 12, 4};
198 chunk_t dest_chunk = {buffer + 16, 4};
199 u_int16_t source_port = ntohs(*(u_int16_t*)(buffer + 20));
200 u_int16_t dest_port = ntohs(*(u_int16_t*)(buffer + 22));
201 source = host_create_from_chunk(AF_INET, source_chunk, source_port);
202 dest = host_create_from_chunk(AF_INET, dest_chunk, dest_port);
203 pkt = packet_create();
204 pkt->set_source(pkt, source);
205 pkt->set_destination(pkt, dest);
206 break;
207 }
208 this->logger->log(this->logger, ERROR|LEVEL1, "too short packet received");
209 }
210
211 this->logger->log(this->logger, CONTROL, "received packet: from %s:%d to %s:%d",
212 source->get_address(source), source->get_port(source),
213 dest->get_address(dest), dest->get_port(dest));
214
215 /* fill in packet */
216 data.len = bytes_read - IP_HEADER_LENGTH - UDP_HEADER_LENGTH;
217 data.ptr = malloc(data.len);
218 memcpy(data.ptr, buffer + IP_HEADER_LENGTH + UDP_HEADER_LENGTH, data.len);
219 pkt->set_data(pkt, data);
220
221 /* return packet */
222 *packet = pkt;
223
224 return SUCCESS;
225 }
226
227 /**
228 * implementation of socket_t.send
229 */
230 status_t sender(private_socket_t *this, packet_t *packet)
231 {
232 ssize_t bytes_sent;
233 chunk_t data;
234 host_t *src, *dst;
235
236 src = packet->get_source(packet);
237 dst = packet->get_destination(packet);
238 data = packet->get_data(packet);
239
240 this->logger->log(this->logger, CONTROL, "sending packet: from %s:%d to %s:%d",
241 src->get_address(src), src->get_port(src),
242 dst->get_address(dst), dst->get_port(dst));
243
244 /* send data */
245 /* TODO: should we send via the interface we received the packet? */
246 bytes_sent = sendto(this->master_fd, data.ptr, data.len, 0,
247 dst->get_sockaddr(dst), *(dst->get_sockaddr_len(dst)));
248
249 if (bytes_sent != data.len)
250 {
251 this->logger->log(this->logger, ERROR, "error writing to socket: %s", strerror(errno));
252 return FAILED;
253 }
254 return SUCCESS;
255 }
256
257 /**
258 * Find all suitable interfaces, bind them and add them to the list
259 */
260 static status_t build_interface_list(private_socket_t *this, u_int16_t port)
261 {
262 int on = TRUE;
263 int i;
264 struct sockaddr_in addr;
265 struct ifconf ifconf;
266 struct ifreq buf[300];
267
268 /* master socket for querying socket for a specific interfaces */
269 this->master_fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
270 if (this->master_fd == -1)
271 {
272 this->logger->log(this->logger, ERROR, "could not open IPv4 master socket!");
273 return FAILED;
274 }
275
276 /* allow binding of multiplo sockets */
277 if (setsockopt(this->master_fd, SOL_SOCKET, SO_REUSEADDR, (void*)&on, sizeof(on)) < 0)
278 {
279 this->logger->log(this->logger, ERROR, "unable to set SO_REUSEADDR on master socket!");
280 return FAILED;
281 }
282
283 /* bind the master socket */
284 addr.sin_family = AF_INET;
285 addr.sin_addr.s_addr = INADDR_ANY;
286 addr.sin_port = htons(port);
287 if (bind(this->master_fd,(struct sockaddr*)&addr, sizeof(addr)) < 0)
288 {
289 this->logger->log(this->logger, ERROR, "unable to bind master socket: %s!", strerror(errno));
290 return FAILED;
291 }
292
293 /* get all interfaces */
294 ifconf.ifc_len = sizeof(buf);
295 ifconf.ifc_buf = (void*) buf;
296 memset(buf, 0, sizeof(buf));
297 if (ioctl(this->master_fd, SIOCGIFCONF, &ifconf) == -1)
298 {
299 this->logger->log(this->logger, ERROR, "unable to get interfaces!");
300 return FAILED;
301 }
302
303 /* add every interesting interfaces to our interface list */
304 for (i = 0; (i+1) * sizeof(*buf) <= (size_t)ifconf.ifc_len; i++)
305 {
306 struct sockaddr_in *current = (struct sockaddr_in*) &buf[i].ifr_addr;
307 struct ifreq auxinfo;
308 int skt;
309 interface_t *interface;
310
311 if (current->sin_family != AF_INET)
312 {
313 /* ignore all but AF_INET interfaces */
314 continue;
315 }
316
317 /* get auxilary info about socket */
318 memset(&auxinfo, 0, sizeof(auxinfo));
319 memcpy(auxinfo.ifr_name, buf[i].ifr_name, IFNAMSIZ);
320 if (ioctl(this->master_fd, SIOCGIFFLAGS, &auxinfo) == -1)
321 {
322 this->logger->log(this->logger, ERROR, "unable to SIOCGIFFLAGS master socket!");
323 continue;
324 }
325 if (!(auxinfo.ifr_flags & IFF_UP))
326 {
327 /* ignore an interface that isn't up */
328 continue;
329 }
330 if (current->sin_addr.s_addr == 0)
331 {
332 /* ignore unconfigured interfaces */
333 continue;
334 }
335
336 /* set up interface socket */
337 skt = socket(AF_INET, SOCK_RAW, IPPROTO_UDP);
338 if (socket < 0)
339 {
340 this->logger->log(this->logger, ERROR, "unable to open interface socket!");
341 continue;
342 }
343 if (setsockopt(skt, SOL_SOCKET, SO_REUSEADDR, (void*)&on, sizeof(on)) < 0)
344 {
345 this->logger->log(this->logger, ERROR, "unable to set SO_REUSEADDR on interface socket!");
346 close(skt);
347 continue;
348 }
349 current->sin_port = htons(port);
350 current->sin_family = AF_INET;
351 if (bind(skt, (struct sockaddr*)current, sizeof(struct sockaddr_in)) < 0)
352 {
353 this->logger->log(this->logger, ERROR, "unable to bind interface socket!");
354 close(skt);
355 continue;
356 }
357
358 if (setsockopt(skt, SOL_SOCKET, SO_ATTACH_FILTER, &ikev2_filter, sizeof(ikev2_filter)) < 0)
359 {
360 this->logger->log(this->logger, ERROR, "unable to attack IKEv2 filter to interface socket!");
361 close(skt);
362 continue;
363 }
364
365 /* add socket with interface name to list */
366 interface = malloc_thing(interface_t);
367 strncpy(interface->name, buf[i].ifr_name, IFNAMSIZ);
368 interface->socket_fd = skt;
369 interface->address = host_create_from_sockaddr((struct sockaddr*)current);
370 this->logger->log(this->logger, CONTROL, "listening on %s (%s)",
371 interface->name, interface->address->get_address(interface->address));
372 this->interfaces->insert_last(this->interfaces, (void*)interface);
373 }
374
375 if (this->interfaces->get_count(this->interfaces) == 0)
376 {
377 this->logger->log(this->logger, ERROR, "unable to find any usable interface!");
378 return FAILED;
379 }
380 return SUCCESS;
381 }
382
383 /**
384 * implementation of socket_t.is_listening_on
385 */
386 static bool is_listening_on(private_socket_t *this, host_t *host)
387 {
388 iterator_t *iterator;
389
390 /* listening on wildcard 0.0.0.0 is always FALSE */
391 if (host->is_anyaddr(host))
392 return FALSE;
393
394 /* compare host with all interfaces */
395 iterator = this->interfaces->create_iterator(this->interfaces, TRUE);
396 while (iterator->has_next(iterator))
397 {
398 interface_t *interface;
399 iterator->current(iterator, (void**)&interface);
400 if (host->equals(host, interface->address))
401 {
402 iterator->destroy(iterator);
403 return TRUE;
404 }
405 }
406 iterator->destroy(iterator);
407 return FALSE;
408 }
409
410 /**
411 * implementation of socket_t.destroy
412 */
413 static void destroy(private_socket_t *this)
414 {
415 interface_t *interface;
416 while (this->interfaces->remove_last(this->interfaces, (void**)&interface) == SUCCESS)
417 {
418 interface->address->destroy(interface->address);
419 close(interface->socket_fd);
420 free(interface);
421 }
422 this->interfaces->destroy(this->interfaces);
423 close(this->master_fd);
424 free(this);
425 }
426
427 /*
428 * See header for description
429 */
430 socket_t *socket_create(u_int16_t port)
431 {
432 private_socket_t *this = malloc_thing(private_socket_t);
433
434 /* public functions */
435 this->public.send = (status_t(*)(socket_t*, packet_t*))sender;
436 this->public.receive = (status_t(*)(socket_t*, packet_t**))receiver;
437 this->public.is_listening_on = (bool (*)(socket_t*,host_t*))is_listening_on;
438 this->public.destroy = (void(*)(socket_t*)) destroy;
439
440 this->logger = logger_manager->get_logger(logger_manager, SOCKET);
441 this->interfaces = linked_list_create();
442
443 if (build_interface_list(this, port) != SUCCESS)
444 {
445 this->interfaces->destroy(this->interfaces);
446 free(this);
447 charon->kill(charon, "could not bind any interface!");
448 }
449
450 return (socket_t*)this;
451 }