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