68846fc2e0b9a641540014f2cf6e8d5f934a4dfc
[strongswan.git] / src / charon / daemon.c
1 /**
2 * @file daemon.c
3 *
4 * @brief Implementation of daemon_t and main of IKEv2-Daemon.
5 *
6 */
7
8 /*
9 * Copyright (C) 2006 Tobias Brunner, Daniel Roethlisberger
10 * Copyright (C) 2005-2006 Martin Willi
11 * Copyright (C) 2005 Jan Hutter
12 * Hochschule fuer Technik Rapperswil
13 *
14 * This program is free software; you can redistribute it and/or modify it
15 * under the terms of the GNU General Public License as published by the
16 * Free Software Foundation; either version 2 of the License, or (at your
17 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
18 *
19 * This program is distributed in the hope that it will be useful, but
20 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
21 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
22 * for more details.
23 */
24
25 #include <stdio.h>
26 #include <signal.h>
27 #include <pthread.h>
28 #include <sys/stat.h>
29 #include <sys/types.h>
30 #include <unistd.h>
31 #include <time.h>
32 #include <execinfo.h>
33 #include <string.h>
34 #include <getopt.h>
35 #include <errno.h>
36
37 #include "daemon.h"
38
39 #include <types.h>
40 #include <config/credentials/local_credential_store.h>
41 #include <config/connections/local_connection_store.h>
42 #include <config/policies/local_policy_store.h>
43
44
45 typedef struct private_daemon_t private_daemon_t;
46
47 /**
48 * Private additions to daemon_t, contains threads and internal functions.
49 */
50 struct private_daemon_t {
51 /**
52 * Public members of daemon_t.
53 */
54 daemon_t public;
55
56 /**
57 * A logger_t object assigned for daemon things.
58 */
59 logger_t *logger;
60
61 /**
62 * Signal set used for signal handling.
63 */
64 sigset_t signal_set;
65
66 /**
67 * The thread_id of main-thread.
68 */
69 pthread_t main_thread_id;
70
71 /**
72 * Main loop function.
73 *
74 * @param this calling object
75 */
76 void (*run) (private_daemon_t *this);
77
78 /**
79 * Initialize the daemon.
80 *
81 * @param this calling object
82 * @param strict enforce a strict crl policy
83 */
84 void (*initialize) (private_daemon_t *this, bool strict);
85
86 /**
87 * Destroy the daemon.
88 *
89 * @param this calling object
90 */
91 void (*destroy) (private_daemon_t *this);
92 };
93
94 /**
95 * One and only instance of the daemon.
96 */
97 daemon_t *charon;
98
99 /**
100 * Implementation of private_daemon_t.run.
101 */
102 static void run(private_daemon_t *this)
103 {
104 /* reselect signals for this thread */
105 sigemptyset(&(this->signal_set));
106 sigaddset(&(this->signal_set), SIGINT);
107 sigaddset(&(this->signal_set), SIGHUP);
108 sigaddset(&(this->signal_set), SIGTERM);
109 pthread_sigmask(SIG_BLOCK, &(this->signal_set), 0);
110
111 while(TRUE)
112 {
113 int signal_number;
114 int error;
115
116 error = sigwait(&(this->signal_set), &signal_number);
117 if(error)
118 {
119 this->logger->log(this->logger, ERROR, "Error %d when waiting for signal", error);
120 return;
121 }
122 switch (signal_number)
123 {
124 case SIGHUP:
125 {
126 this->logger->log(this->logger, CONTROL, "Signal of type SIGHUP received. Do nothing");
127 break;
128 }
129 case SIGINT:
130 {
131 this->logger->log(this->logger, CONTROL, "Signal of type SIGINT received. Exit main loop");
132 return;
133 }
134 case SIGTERM:
135 this->logger->log(this->logger, CONTROL, "Signal of type SIGTERM received. Exit main loop");
136 return;
137 default:
138 {
139 this->logger->log(this->logger, CONTROL, "Unknown signal %d received. Do nothing", signal_number);
140 break;
141 }
142 }
143 }
144 }
145
146 /**
147 * Implementation of daemon_t.kill.
148 */
149 static void kill_daemon(private_daemon_t *this, char *reason)
150 {
151 /* we send SIGTERM, so the daemon can cleanly shut down */
152 this->logger->log(this->logger, CONTROL, "Killing daemon: %s", reason);
153 if (this->main_thread_id == pthread_self())
154 {
155 /* initialization failed, terminate daemon */
156 this->destroy(this);
157 unlink(PID_FILE);
158 exit(-1);
159 }
160 else
161 {
162 this->logger->log(this->logger, CONTROL, "sending SIGTERM to ourself", reason);
163 raise(SIGTERM);
164 /* thread must die, since he produced a ciritcal failure and can't continue */
165 pthread_exit(NULL);
166 }
167 }
168
169 /**
170 * Implementation of private_daemon_t.initialize.
171 */
172 static void initialize(private_daemon_t *this, bool strict)
173 {
174 credential_store_t* credentials;
175
176 /* for uncritical pseudo random numbers */
177 srandom(time(NULL) + getpid());
178
179 this->public.configuration = configuration_create();
180 this->public.socket = socket_create(IKEV2_UDP_PORT, IKEV2_NATT_PORT);
181 this->public.ike_sa_manager = ike_sa_manager_create();
182 this->public.job_queue = job_queue_create();
183 this->public.event_queue = event_queue_create();
184 this->public.send_queue = send_queue_create();
185 this->public.connections = (connection_store_t*)local_connection_store_create();
186 this->public.policies = (policy_store_t*)local_policy_store_create();
187 this->public.credentials = (credential_store_t*)local_credential_store_create(strict);
188
189 /* load keys, ca certificates and crls */
190 credentials = this->public.credentials;
191 credentials->load_ca_certificates(credentials);
192 credentials->load_crls(credentials);
193 credentials->load_private_keys(credentials);
194
195 /* start building threads, we are multi-threaded NOW */
196 this->public.stroke = stroke_create();
197 this->public.sender = sender_create();
198 this->public.receiver = receiver_create();
199 this->public.scheduler = scheduler_create();
200 this->public.kernel_interface = kernel_interface_create();
201 this->public.thread_pool = thread_pool_create(NUMBER_OF_WORKING_THREADS);
202 }
203
204 /**
205 * Destory all initiated objects
206 */
207 static void destroy(private_daemon_t *this)
208 {
209 /* destruction is a non trivial task, we need to follow
210 * a strict order to prevent threading issues!
211 * Kill active threads first, except the sender, as
212 * the killed IKE_SA want to send delete messages.
213 */
214 /* we don't want to receive anything anymore... */
215 DESTROY_IF(this->public.receiver);
216 /* ignore all incoming user requests */
217 DESTROY_IF(this->public.stroke);
218 /* stop scheduing jobs */
219 DESTROY_IF(this->public.scheduler);
220 /* stop processing jobs */
221 DESTROY_IF(this->public.thread_pool);
222 /* shut down manager with all IKE SAs */
223 DESTROY_IF(this->public.ike_sa_manager);
224 /* all child SAs should be down now, so kill kernel interface */
225 DESTROY_IF(this->public.kernel_interface);
226 /* destroy other infrastructure */
227 DESTROY_IF(this->public.job_queue);
228 DESTROY_IF(this->public.event_queue);
229 DESTROY_IF(this->public.configuration);
230 DESTROY_IF(this->public.credentials);
231 DESTROY_IF(this->public.connections);
232 DESTROY_IF(this->public.policies);
233 /* we hope the sender could send the outstanding deletes, but
234 * we shut down here at any cost */
235 DESTROY_IF(this->public.sender);
236 DESTROY_IF(this->public.send_queue);
237 DESTROY_IF(this->public.socket);
238 free(this);
239 }
240
241 void signal_handler(int signal)
242 {
243 void *array[20];
244 size_t size;
245 char **strings;
246 size_t i;
247 logger_t *logger;
248
249 size = backtrace(array, 20);
250 strings = backtrace_symbols(array, size);
251 logger = logger_manager->get_logger(logger_manager, DAEMON);
252
253 logger->log(logger, ERROR,
254 "Thread %u received %s. Dumping %d frames from stack:",
255 signal == SIGSEGV ? "SIGSEGV" : "SIGILL",
256 pthread_self(), size);
257
258 for (i = 0; i < size; i++)
259 {
260 logger->log(logger, ERROR, " %s", strings[i]);
261 }
262 free (strings);
263 logger->log(logger, ERROR, "Killing ourself hard after SIGSEGV");
264 raise(SIGKILL);
265 }
266
267 /**
268 * @brief Create the daemon.
269 *
270 * @return created daemon_t
271 */
272 private_daemon_t *daemon_create(void)
273 {
274 private_daemon_t *this = malloc_thing(private_daemon_t);
275 struct sigaction action;
276
277 /* assign methods */
278 this->run = run;
279 this->destroy = destroy;
280 this->initialize = initialize;
281 this->public.kill = (void (*) (daemon_t*,char*))kill_daemon;
282
283 /* NULL members for clean destruction */
284 this->public.socket = NULL;
285 this->public.ike_sa_manager = NULL;
286 this->public.job_queue = NULL;
287 this->public.event_queue = NULL;
288 this->public.send_queue = NULL;
289 this->public.configuration = NULL;
290 this->public.credentials = NULL;
291 this->public.connections = NULL;
292 this->public.policies = NULL;
293 this->public.sender= NULL;
294 this->public.receiver = NULL;
295 this->public.scheduler = NULL;
296 this->public.kernel_interface = NULL;
297 this->public.thread_pool = NULL;
298 this->public.stroke = NULL;
299
300 this->main_thread_id = pthread_self();
301
302 /* setup signal handling for all threads */
303 sigemptyset(&(this->signal_set));
304 sigaddset(&(this->signal_set), SIGSEGV);
305 sigaddset(&(this->signal_set), SIGINT);
306 sigaddset(&(this->signal_set), SIGHUP);
307 sigaddset(&(this->signal_set), SIGTERM);
308 pthread_sigmask(SIG_BLOCK, &(this->signal_set), 0);
309
310 /* setup SIGSEGV handler for all threads */
311 action.sa_handler = signal_handler;
312 action.sa_mask = this->signal_set;
313 action.sa_flags = 0;
314 if (sigaction(SIGSEGV, &action, NULL) == -1)
315 {
316 this->logger->log(this->logger, ERROR, "signal handler setup for SIGSEGV failed");
317 }
318 if (sigaction(SIGILL, &action, NULL) == -1)
319 {
320 this->logger->log(this->logger, ERROR, "signal handler setup for SIGILL failed");
321 }
322 return this;
323 }
324
325 static void usage(const char *msg)
326 {
327 if (msg != NULL && *msg != '\0')
328 fprintf(stderr, "%s\n", msg);
329 fprintf(stderr, "Usage: charon"
330 " [--help]"
331 " [--version]"
332 " [--use-syslog]"
333 " [--strictcrlpolicy]"
334 "\n"
335 );
336 exit(msg == NULL? 0 : 1);
337 }
338
339
340 /**
341 * Main function, manages the daemon.
342 */
343 int main(int argc, char *argv[])
344 {
345 bool strict_crl_policy = FALSE;
346
347 private_daemon_t *private_charon;
348 FILE *pid_file;
349 struct stat stb;
350 linked_list_t *list;
351 host_t *host;
352
353 /* handle arguments */
354 for (;;)
355 {
356 static const struct option long_opts[] = {
357 { "help", no_argument, NULL, 'h' },
358 { "version", no_argument, NULL, 'v' },
359 { "use-syslog", no_argument, NULL, 'l' },
360 { "strictcrlpolicy", no_argument, NULL, 'r' },
361 { 0,0,0,0 }
362 };
363
364 int c = getopt_long(argc, argv, "", long_opts, NULL);
365
366 /* Note: "breaking" from case terminates loop */
367 switch (c)
368 {
369 case EOF: /* end of flags */
370 break;
371 case 'h':
372 usage(NULL);
373 break; /* not actually reached */
374 case 'v':
375 printf("Linux strongSwan %s\n", VERSION);
376 exit(0);
377 case 'l':
378 logger_manager->set_output(logger_manager, ALL_LOGGERS, NULL);
379 continue;
380 case 'r':
381 strict_crl_policy = TRUE;
382 continue;
383 default:
384 usage("");
385 break; /* not actually reached */
386 }
387 break;
388 }
389
390 private_charon = daemon_create();
391 charon = (daemon_t*)private_charon;
392
393 private_charon->logger = logger_manager->get_logger(logger_manager, DAEMON);
394
395 private_charon->logger->log(private_charon->logger, CONTROL,
396 "Starting Charon (strongSwan Version %s)", VERSION);
397
398 /* initialize daemon */
399 private_charon->initialize(private_charon, strict_crl_policy);
400
401 /* check/setup PID file */
402 if (stat(PID_FILE, &stb) == 0)
403 {
404 private_charon->logger->log(private_charon->logger, ERROR,
405 "charon already running (\""PID_FILE"\" exists)");
406 private_charon->destroy(private_charon);
407 exit(-1);
408 }
409 pid_file = fopen(PID_FILE, "w");
410 if (pid_file)
411 {
412 fprintf(pid_file, "%d\n", getpid());
413 fclose(pid_file);
414 }
415 /* log socket info */
416 list = charon->socket->create_local_address_list(charon->socket);
417 private_charon->logger->log(private_charon->logger, CONTROL,
418 "listening on %d addresses:",
419 list->get_count(list));
420 while (list->remove_first(list, (void**)&host) == SUCCESS)
421 {
422 private_charon->logger->log(private_charon->logger, CONTROL,
423 " %s", host->get_string(host));
424 host->destroy(host);
425 }
426 list->destroy(list);
427
428 /* run daemon */
429 private_charon->run(private_charon);
430
431 /* normal termination, cleanup and exit */
432 private_charon->destroy(private_charon);
433 unlink(PID_FILE);
434
435 return 0;
436 }
437
438