Merge branch 'multi-cert'
[strongswan.git] / src / charon / charon.c
1 /*
2 * Copyright (C) 2006-2012 Tobias Brunner
3 * Copyright (C) 2005-2009 Martin Willi
4 * Copyright (C) 2006 Daniel Roethlisberger
5 * Copyright (C) 2005 Jan Hutter
6 * Hochschule fuer Technik Rapperswil
7 *
8 * This program is free software; you can redistribute it and/or modify it
9 * under the terms of the GNU General Public License as published by the
10 * Free Software Foundation; either version 2 of the License, or (at your
11 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
12 *
13 * This program is distributed in the hope that it will be useful, but
14 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
15 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 * for more details.
17 */
18
19 #include <stdio.h>
20 #define _POSIX_PTHREAD_SEMANTICS /* for two param sigwait on OpenSolaris */
21 #include <signal.h>
22 #undef _POSIX_PTHREAD_SEMANTICS
23 #include <pthread.h>
24 #include <sys/stat.h>
25 #include <sys/types.h>
26 #include <sys/utsname.h>
27 #include <unistd.h>
28 #include <getopt.h>
29
30 #include <hydra.h>
31 #include <daemon.h>
32
33 #include <library.h>
34 #include <utils/backtrace.h>
35 #include <threading/thread.h>
36
37 #ifdef ANDROID
38 #include <private/android_filesystem_config.h> /* for AID_VPN */
39 #endif
40
41 /**
42 * PID file, in which charon stores its process id
43 */
44 #define PID_FILE IPSEC_PIDDIR "/charon.pid"
45
46 /**
47 * Global reference to PID file (required to truncate, if undeletable)
48 */
49 static FILE *pidfile = NULL;
50
51 /**
52 * Log levels as defined via command line arguments
53 */
54 static level_t levels[DBG_MAX];
55
56 /**
57 * Whether to only use syslog when logging
58 */
59 static bool use_syslog = FALSE;
60
61 /**
62 * hook in library for debugging messages
63 */
64 extern void (*dbg) (debug_t group, level_t level, char *fmt, ...);
65
66 /**
67 * Logging hook for library logs, using stderr output
68 */
69 static void dbg_stderr(debug_t group, level_t level, char *fmt, ...)
70 {
71 va_list args;
72
73 if (level <= 1)
74 {
75 va_start(args, fmt);
76 fprintf(stderr, "00[%N] ", debug_names, group);
77 vfprintf(stderr, fmt, args);
78 fprintf(stderr, "\n");
79 va_end(args);
80 }
81 }
82
83 /**
84 * Run the daemon and handle unix signals
85 */
86 static void run()
87 {
88 sigset_t set;
89
90 /* handle SIGINT, SIGHUP ans SIGTERM in this handler */
91 sigemptyset(&set);
92 sigaddset(&set, SIGINT);
93 sigaddset(&set, SIGHUP);
94 sigaddset(&set, SIGTERM);
95 sigprocmask(SIG_BLOCK, &set, NULL);
96
97 while (TRUE)
98 {
99 int sig;
100 int error;
101
102 error = sigwait(&set, &sig);
103 if (error)
104 {
105 DBG1(DBG_DMN, "error %d while waiting for a signal", error);
106 return;
107 }
108 switch (sig)
109 {
110 case SIGHUP:
111 {
112 DBG1(DBG_DMN, "signal of type SIGHUP received. Reloading "
113 "configuration");
114 if (lib->settings->load_files(lib->settings, NULL, FALSE))
115 {
116 charon->load_loggers(charon, levels, !use_syslog);
117 lib->plugins->reload(lib->plugins, NULL);
118 }
119 else
120 {
121 DBG1(DBG_DMN, "reloading config failed, keeping old");
122 }
123 break;
124 }
125 case SIGINT:
126 {
127 DBG1(DBG_DMN, "signal of type SIGINT received. Shutting down");
128 charon->bus->alert(charon->bus, ALERT_SHUTDOWN_SIGNAL, sig);
129 return;
130 }
131 case SIGTERM:
132 {
133 DBG1(DBG_DMN, "signal of type SIGTERM received. Shutting down");
134 charon->bus->alert(charon->bus, ALERT_SHUTDOWN_SIGNAL, sig);
135 return;
136 }
137 default:
138 {
139 DBG1(DBG_DMN, "unknown signal %d received. Ignored", sig);
140 break;
141 }
142 }
143 }
144 }
145
146 /**
147 * lookup UID and GID
148 */
149 static bool lookup_uid_gid()
150 {
151 #ifdef IPSEC_USER
152 if (!charon->caps->resolve_uid(charon->caps, IPSEC_USER))
153 {
154 return FALSE;
155 }
156 #endif
157 #ifdef IPSEC_GROUP
158 if (!charon->caps->resolve_gid(charon->caps, IPSEC_GROUP))
159 {
160 return FALSE;
161 }
162 #endif
163 #ifdef ANDROID
164 charon->caps->set_uid(charon->caps, AID_VPN);
165 #endif
166 return TRUE;
167 }
168
169 /**
170 * Handle SIGSEGV/SIGILL signals raised by threads
171 */
172 static void segv_handler(int signal)
173 {
174 backtrace_t *backtrace;
175
176 DBG1(DBG_DMN, "thread %u received %d", thread_current_id(), signal);
177 backtrace = backtrace_create(2);
178 backtrace->log(backtrace, stderr, TRUE);
179 backtrace->destroy(backtrace);
180
181 DBG1(DBG_DMN, "killing ourself, received critical signal");
182 abort();
183 }
184
185 /**
186 * Check/create PID file, return TRUE if already running
187 */
188 static bool check_pidfile()
189 {
190 struct stat stb;
191
192 if (stat(PID_FILE, &stb) == 0)
193 {
194 pidfile = fopen(PID_FILE, "r");
195 if (pidfile)
196 {
197 char buf[64];
198 pid_t pid = 0;
199
200 memset(buf, 0, sizeof(buf));
201 if (fread(buf, 1, sizeof(buf), pidfile))
202 {
203 buf[sizeof(buf) - 1] = '\0';
204 pid = atoi(buf);
205 }
206 fclose(pidfile);
207 if (pid && kill(pid, 0) == 0)
208 { /* such a process is running */
209 return TRUE;
210 }
211 }
212 DBG1(DBG_DMN, "removing pidfile '"PID_FILE"', process not running");
213 unlink(PID_FILE);
214 }
215
216 /* create new pidfile */
217 pidfile = fopen(PID_FILE, "w");
218 if (pidfile)
219 {
220 ignore_result(fchown(fileno(pidfile),
221 charon->caps->get_uid(charon->caps),
222 charon->caps->get_gid(charon->caps)));
223 fprintf(pidfile, "%d\n", getpid());
224 fflush(pidfile);
225 }
226 return FALSE;
227 }
228
229 /**
230 * Delete/truncate the PID file
231 */
232 static void unlink_pidfile()
233 {
234 /* because unlinking the PID file may fail, we truncate it to ensure the
235 * daemon can be properly restarted. one probable cause for this is the
236 * combination of not running as root and the effective user lacking
237 * permissions on the parent dir(s) of the PID file */
238 if (pidfile)
239 {
240 ignore_result(ftruncate(fileno(pidfile), 0));
241 fclose(pidfile);
242 }
243 unlink(PID_FILE);
244 }
245
246 /**
247 * print command line usage and exit
248 */
249 static void usage(const char *msg)
250 {
251 if (msg != NULL && *msg != '\0')
252 {
253 fprintf(stderr, "%s\n", msg);
254 }
255 fprintf(stderr, "Usage: charon\n"
256 " [--help]\n"
257 " [--version]\n"
258 " [--use-syslog]\n"
259 " [--debug-<type> <level>]\n"
260 " <type>: log context type (dmn|mgr|ike|chd|job|cfg|knl|net|asn|enc|tnc|imc|imv|pts|tls|esp|lib)\n"
261 " <level>: log verbosity (-1 = silent, 0 = audit, 1 = control,\n"
262 " 2 = controlmore, 3 = raw, 4 = private)\n"
263 "\n"
264 );
265 }
266
267 /**
268 * Main function, starts the daemon.
269 */
270 int main(int argc, char *argv[])
271 {
272 struct sigaction action;
273 int group, status = SS_RC_INITIALIZATION_FAILED;
274 struct utsname utsname;
275
276 /* logging for library during initialization, as we have no bus yet */
277 dbg = dbg_stderr;
278
279 /* initialize library */
280 if (!library_init(NULL))
281 {
282 library_deinit();
283 exit(SS_RC_LIBSTRONGSWAN_INTEGRITY);
284 }
285
286 if (lib->integrity &&
287 !lib->integrity->check_file(lib->integrity, "charon", argv[0]))
288 {
289 dbg_stderr(DBG_DMN, 1, "integrity check of charon failed");
290 library_deinit();
291 exit(SS_RC_DAEMON_INTEGRITY);
292 }
293
294 if (!libhydra_init("charon"))
295 {
296 dbg_stderr(DBG_DMN, 1, "initialization failed - aborting charon");
297 libhydra_deinit();
298 library_deinit();
299 exit(SS_RC_INITIALIZATION_FAILED);
300 }
301
302 if (!libcharon_init("charon"))
303 {
304 dbg_stderr(DBG_DMN, 1, "initialization failed - aborting charon");
305 goto deinit;
306 }
307
308 /* use CTRL loglevel for default */
309 for (group = 0; group < DBG_MAX; group++)
310 {
311 levels[group] = LEVEL_CTRL;
312 }
313
314 /* handle arguments */
315 for (;;)
316 {
317 struct option long_opts[] = {
318 { "help", no_argument, NULL, 'h' },
319 { "version", no_argument, NULL, 'v' },
320 { "use-syslog", no_argument, NULL, 'l' },
321 /* TODO: handle "debug-all" */
322 { "debug-dmn", required_argument, &group, DBG_DMN },
323 { "debug-mgr", required_argument, &group, DBG_MGR },
324 { "debug-ike", required_argument, &group, DBG_IKE },
325 { "debug-chd", required_argument, &group, DBG_CHD },
326 { "debug-job", required_argument, &group, DBG_JOB },
327 { "debug-cfg", required_argument, &group, DBG_CFG },
328 { "debug-knl", required_argument, &group, DBG_KNL },
329 { "debug-net", required_argument, &group, DBG_NET },
330 { "debug-asn", required_argument, &group, DBG_ASN },
331 { "debug-enc", required_argument, &group, DBG_ENC },
332 { "debug-tnc", required_argument, &group, DBG_TNC },
333 { "debug-imc", required_argument, &group, DBG_IMC },
334 { "debug-imv", required_argument, &group, DBG_IMV },
335 { "debug-pts", required_argument, &group, DBG_PTS },
336 { "debug-tls", required_argument, &group, DBG_TLS },
337 { "debug-esp", required_argument, &group, DBG_ESP },
338 { "debug-lib", required_argument, &group, DBG_LIB },
339 { 0,0,0,0 }
340 };
341
342 int c = getopt_long(argc, argv, "", long_opts, NULL);
343 switch (c)
344 {
345 case EOF:
346 break;
347 case 'h':
348 usage(NULL);
349 status = 0;
350 goto deinit;
351 case 'v':
352 printf("Linux strongSwan %s\n", VERSION);
353 status = 0;
354 goto deinit;
355 case 'l':
356 use_syslog = TRUE;
357 continue;
358 case 0:
359 /* option is in group */
360 levels[group] = atoi(optarg);
361 continue;
362 default:
363 usage("");
364 status = 1;
365 goto deinit;
366 }
367 break;
368 }
369
370 if (!lookup_uid_gid())
371 {
372 dbg_stderr(DBG_DMN, 1, "invalid uid/gid - aborting charon");
373 goto deinit;
374 }
375
376 charon->load_loggers(charon, levels, !use_syslog);
377
378 if (uname(&utsname) != 0)
379 {
380 memset(&utsname, 0, sizeof(utsname));
381 }
382 DBG1(DBG_DMN, "Starting IKE charon daemon (strongSwan "VERSION", %s %s, %s)",
383 utsname.sysname, utsname.release, utsname.machine);
384 if (lib->integrity)
385 {
386 DBG1(DBG_DMN, "integrity tests enabled:");
387 DBG1(DBG_DMN, "lib 'libstrongswan': passed file and segment integrity tests");
388 DBG1(DBG_DMN, "lib 'libhydra': passed file and segment integrity tests");
389 DBG1(DBG_DMN, "lib 'libcharon': passed file and segment integrity tests");
390 DBG1(DBG_DMN, "daemon 'charon': passed file integrity test");
391 }
392
393 /* initialize daemon */
394 if (!charon->initialize(charon,
395 lib->settings->get_str(lib->settings, "charon.load", PLUGINS)))
396 {
397 DBG1(DBG_DMN, "initialization failed - aborting charon");
398 goto deinit;
399 }
400
401 if (check_pidfile())
402 {
403 DBG1(DBG_DMN, "charon already running (\""PID_FILE"\" exists)");
404 goto deinit;
405 }
406
407 if (!charon->caps->drop(charon->caps))
408 {
409 DBG1(DBG_DMN, "capability dropping failed - aborting charon");
410 goto deinit;
411 }
412
413 /* add handler for SEGV and ILL,
414 * INT, TERM and HUP are handled by sigwait() in run() */
415 action.sa_handler = segv_handler;
416 action.sa_flags = 0;
417 sigemptyset(&action.sa_mask);
418 sigaddset(&action.sa_mask, SIGINT);
419 sigaddset(&action.sa_mask, SIGTERM);
420 sigaddset(&action.sa_mask, SIGHUP);
421 sigaction(SIGSEGV, &action, NULL);
422 sigaction(SIGILL, &action, NULL);
423 sigaction(SIGBUS, &action, NULL);
424 action.sa_handler = SIG_IGN;
425 sigaction(SIGPIPE, &action, NULL);
426
427 pthread_sigmask(SIG_SETMASK, &action.sa_mask, NULL);
428
429 /* start daemon (i.e. the threads in the thread-pool) */
430 charon->start(charon);
431
432 /* main thread goes to run loop */
433 run();
434
435 /* normal termination, cleanup and exit */
436 unlink_pidfile();
437 status = 0;
438
439 deinit:
440 libcharon_deinit();
441 libhydra_deinit();
442 library_deinit();
443 return status;
444 }
445