implemented proper refcounting using atomic operations
[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.interfaces = interfaces_create(IKEV2_UDP_PORT);
182 this->public.ike_sa_manager = ike_sa_manager_create();
183 this->public.job_queue = job_queue_create();
184 this->public.event_queue = event_queue_create();
185 this->public.send_queue = send_queue_create();
186 this->public.connections = (connection_store_t*)local_connection_store_create();
187 this->public.policies = (policy_store_t*)local_policy_store_create();
188 this->public.credentials = (credential_store_t*)local_credential_store_create(strict);
189
190 /* load keys, ca certificates and crls */
191 credentials = this->public.credentials;
192 credentials->load_ca_certificates(credentials);
193 credentials->load_crls(credentials);
194 credentials->load_private_keys(credentials);
195
196 /* start building threads, we are multi-threaded NOW */
197 this->public.stroke = stroke_create();
198 this->public.sender = sender_create();
199 this->public.receiver = receiver_create();
200 this->public.scheduler = scheduler_create();
201 this->public.kernel_interface = kernel_interface_create();
202 this->public.thread_pool = thread_pool_create(NUMBER_OF_WORKING_THREADS);
203 }
204
205 /**
206 * Destory all initiated objects
207 */
208 static void destroy(private_daemon_t *this)
209 {
210 /* destruction is a non trivial task, we need to follow
211 * a strict order to prevent threading issues!
212 * Kill active threads first, except the sender, as
213 * the killed IKE_SA want to send delete messages.
214 */
215 if (this->public.receiver != NULL)
216 { /* we don't want to receive anything... */
217 this->public.receiver->destroy(this->public.receiver);
218 }
219 if (this->public.stroke != NULL)
220 { /* ignore all incoming user requests */
221 this->public.stroke->destroy(this->public.stroke);
222 }
223 if (this->public.scheduler != NULL)
224 { /* stop scheduing jobs */
225 this->public.scheduler->destroy(this->public.scheduler);
226 }
227 if (this->public.thread_pool != NULL)
228 { /* stop processing jobs */
229 this->public.thread_pool->destroy(this->public.thread_pool);
230 }
231 if (this->public.ike_sa_manager != NULL)
232 { /* shut down manager with all IKE SAs */
233 this->public.ike_sa_manager->destroy(this->public.ike_sa_manager);
234 }
235 if (this->public.kernel_interface != NULL)
236 { /* all child SAs should be down now, so kill kernel interface */
237 this->public.kernel_interface->destroy(this->public.kernel_interface);
238 }
239 /* destroy other infrastructure */
240 if (this->public.job_queue != NULL)
241 {
242 this->public.job_queue->destroy(this->public.job_queue);
243 }
244 if (this->public.event_queue != NULL)
245 {
246 this->public.event_queue->destroy(this->public.event_queue);
247 }
248 if (this->public.interfaces != NULL)
249 {
250 this->public.interfaces->destroy(this->public.interfaces);
251 }
252 if (this->public.configuration != NULL)
253 {
254 this->public.configuration->destroy(this->public.configuration);
255 }
256 if (this->public.credentials != NULL)
257 {
258 this->public.credentials->destroy(this->public.credentials);
259 }
260 if (this->public.connections != NULL)
261 {
262 this->public.connections->destroy(this->public.connections);
263 }
264 if (this->public.policies != NULL)
265 {
266 this->public.policies->destroy(this->public.policies);
267 }
268 /* we hope the sender could send the outstanding deletes, but
269 * we shut down here at any cost */
270 if (this->public.sender != NULL)
271 {
272 this->public.sender->destroy(this->public.sender);
273 }
274 if (this->public.send_queue != NULL)
275 {
276 this->public.send_queue->destroy(this->public.send_queue);
277 }
278 if (this->public.socket != NULL)
279 {
280 this->public.socket->destroy(this->public.socket);
281 }
282 free(this);
283 }
284
285 void signal_handler(int signal)
286 {
287 void *array[20];
288 size_t size;
289 char **strings;
290 size_t i;
291 logger_t *logger;
292
293 size = backtrace(array, 20);
294 strings = backtrace_symbols(array, size);
295 logger = logger_manager->get_logger(logger_manager, DAEMON);
296
297 logger->log(logger, ERROR, "Thread %u received SIGSEGV. Dumping %d frames from stack:", pthread_self(), size);
298
299 for (i = 0; i < size; i++)
300 {
301 logger->log(logger, ERROR, " %s", strings[i]);
302 }
303 free (strings);
304 logger->log(logger, ERROR, "Killing ourself hard after SIGSEGV");
305 raise(SIGKILL);
306 }
307
308 /**
309 * @brief Create the daemon.
310 *
311 * @return created daemon_t
312 */
313 private_daemon_t *daemon_create(void)
314 {
315 private_daemon_t *this = malloc_thing(private_daemon_t);
316 struct sigaction action;
317
318 /* assign methods */
319 this->run = run;
320 this->destroy = destroy;
321 this->initialize = initialize;
322 this->public.kill = (void (*) (daemon_t*,char*))kill_daemon;
323
324 /* NULL members for clean destruction */
325 this->public.socket = NULL;
326 this->public.interfaces = NULL;
327 this->public.ike_sa_manager = NULL;
328 this->public.job_queue = NULL;
329 this->public.event_queue = NULL;
330 this->public.send_queue = NULL;
331 this->public.configuration = NULL;
332 this->public.credentials = NULL;
333 this->public.connections = NULL;
334 this->public.policies = NULL;
335 this->public.sender= NULL;
336 this->public.receiver = NULL;
337 this->public.scheduler = NULL;
338 this->public.kernel_interface = NULL;
339 this->public.thread_pool = NULL;
340 this->public.stroke = NULL;
341
342 this->main_thread_id = pthread_self();
343
344 /* setup signal handling for all threads */
345 sigemptyset(&(this->signal_set));
346 sigaddset(&(this->signal_set), SIGSEGV);
347 sigaddset(&(this->signal_set), SIGINT);
348 sigaddset(&(this->signal_set), SIGHUP);
349 sigaddset(&(this->signal_set), SIGTERM);
350 pthread_sigmask(SIG_BLOCK, &(this->signal_set), 0);
351
352 /* setup SIGSEGV handler for all threads */
353 action.sa_handler = signal_handler;
354 action.sa_mask = this->signal_set;
355 action.sa_flags = 0;
356 if (sigaction(SIGSEGV, &action, NULL) == -1)
357 {
358 this->logger->log(this->logger, ERROR, "signal handler setup for SIGSEGV failed");
359 }
360 return this;
361 }
362
363 static void usage(const char *msg)
364 {
365 if (msg != NULL && *msg != '\0')
366 fprintf(stderr, "%s\n", msg);
367 fprintf(stderr, "Usage: charon"
368 " [--help]"
369 " [--version]"
370 " [--use-syslog]"
371 " [--strictcrlpolicy]"
372 "\n"
373 );
374 exit(msg == NULL? 0 : 1);
375 }
376
377
378 /**
379 * Main function, manages the daemon.
380 */
381 int main(int argc, char *argv[])
382 {
383 bool strict_crl_policy = FALSE;
384
385 private_daemon_t *private_charon;
386 FILE *pid_file;
387 struct stat stb;
388
389 /* handle arguments */
390 for (;;)
391 {
392 static const struct option long_opts[] = {
393 { "help", no_argument, NULL, 'h' },
394 { "version", no_argument, NULL, 'v' },
395 { "use-syslog", no_argument, NULL, 'l' },
396 { "strictcrlpolicy", no_argument, NULL, 'r' },
397 { 0,0,0,0 }
398 };
399
400 int c = getopt_long(argc, argv, "", long_opts, NULL);
401
402 /* Note: "breaking" from case terminates loop */
403 switch (c)
404 {
405 case EOF: /* end of flags */
406 break;
407 case 'h':
408 usage(NULL);
409 break; /* not actually reached */
410 case 'v':
411 printf("Linux strongSwan %s\n", VERSION);
412 exit(0);
413 case 'l':
414 logger_manager->set_output(logger_manager, ALL_LOGGERS, NULL);
415 continue;
416 case 'r':
417 strict_crl_policy = TRUE;
418 continue;
419 default:
420 usage("");
421 break; /* not actually reached */
422 }
423 break;
424 }
425
426 private_charon = daemon_create();
427 charon = (daemon_t*)private_charon;
428
429 private_charon->logger = logger_manager->get_logger(logger_manager, DAEMON);
430
431 private_charon->logger->log(private_charon->logger, CONTROL,
432 "Starting Charon (strongSwan Version %s)", VERSION);
433
434 /* initialize daemon */
435 private_charon->initialize(private_charon, strict_crl_policy);
436
437 /* check/setup PID file */
438 if (stat(PID_FILE, &stb) == 0)
439 {
440 private_charon->logger->log(private_charon->logger, ERROR,
441 "charon already running (\""PID_FILE"\" exists)");
442 private_charon->destroy(private_charon);
443 exit(-1);
444 }
445 pid_file = fopen(PID_FILE, "w");
446 if (pid_file)
447 {
448 fprintf(pid_file, "%d\n", getpid());
449 fclose(pid_file);
450 }
451
452 /* run daemon */
453 private_charon->run(private_charon);
454
455 /* normal termination, cleanup and exit */
456 private_charon->destroy(private_charon);
457 unlink(PID_FILE);
458
459 return 0;
460 }
461
462