Loggers specify what log messages they want to receive during registration.
[strongswan.git] / src / charon / charon.c
1 /*
2 * Copyright (C) 2006-2010 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 #ifdef HAVE_PRCTL
21 #include <sys/prctl.h>
22 #endif
23 #define _POSIX_PTHREAD_SEMANTICS /* for two param sigwait on OpenSolaris */
24 #include <signal.h>
25 #undef _POSIX_PTHREAD_SEMANTICS
26 #include <pthread.h>
27 #include <sys/stat.h>
28 #include <sys/types.h>
29 #include <syslog.h>
30 #include <errno.h>
31 #include <unistd.h>
32 #include <getopt.h>
33 #include <pwd.h>
34 #include <grp.h>
35
36 #include <hydra.h>
37 #include <daemon.h>
38
39 #include <library.h>
40 #include <utils/backtrace.h>
41 #include <threading/thread.h>
42
43 #ifdef ANDROID
44 #include <private/android_filesystem_config.h> /* for AID_VPN */
45 #endif
46
47 #ifndef LOG_AUTHPRIV /* not defined on OpenSolaris */
48 #define LOG_AUTHPRIV LOG_AUTH
49 #endif
50
51 /**
52 * PID file, in which charon stores its process id
53 */
54 #define PID_FILE IPSEC_PIDDIR "/charon.pid"
55
56 /**
57 * Global reference to PID file (required to truncate, if undeletable)
58 */
59 static FILE *pidfile = NULL;
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 lib->plugins->reload(lib->plugins, NULL);
117 }
118 else
119 {
120 DBG1(DBG_DMN, "reloading config failed, keeping old");
121 }
122 break;
123 }
124 case SIGINT:
125 {
126 DBG1(DBG_DMN, "signal of type SIGINT received. Shutting down");
127 charon->bus->alert(charon->bus, ALERT_SHUTDOWN_SIGNAL, sig);
128 return;
129 }
130 case SIGTERM:
131 {
132 DBG1(DBG_DMN, "signal of type SIGTERM received. Shutting down");
133 charon->bus->alert(charon->bus, ALERT_SHUTDOWN_SIGNAL, sig);
134 return;
135 }
136 default:
137 {
138 DBG1(DBG_DMN, "unknown signal %d received. Ignored", sig);
139 break;
140 }
141 }
142 }
143 }
144
145 /**
146 * drop daemon capabilities
147 */
148 static bool drop_capabilities()
149 {
150 #ifdef HAVE_PRCTL
151 prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
152 #endif
153
154 if (setgid(charon->gid) != 0)
155 {
156 DBG1(DBG_DMN, "change to unprivileged group failed");
157 return FALSE;
158 }
159 if (setuid(charon->uid) != 0)
160 {
161 DBG1(DBG_DMN, "change to unprivileged user failed");
162 return FALSE;
163 }
164 if (!charon->drop_capabilities(charon))
165 {
166 DBG1(DBG_DMN, "unable to drop daemon capabilities");
167 return FALSE;
168 }
169 return TRUE;
170 }
171
172 /**
173 * lookup UID and GID
174 */
175 static bool lookup_uid_gid()
176 {
177 #ifdef IPSEC_USER
178 {
179 char buf[1024];
180 struct passwd passwd, *pwp;
181
182 if (getpwnam_r(IPSEC_USER, &passwd, buf, sizeof(buf), &pwp) != 0 ||
183 pwp == NULL)
184 {
185 DBG1(DBG_DMN, "resolving user '"IPSEC_USER"' failed");
186 return FALSE;
187 }
188 charon->uid = pwp->pw_uid;
189 }
190 #endif
191 #ifdef IPSEC_GROUP
192 {
193 char buf[1024];
194 struct group group, *grp;
195
196 if (getgrnam_r(IPSEC_GROUP, &group, buf, sizeof(buf), &grp) != 0 ||
197 grp == NULL)
198 {
199 DBG1(DBG_DMN, "resolving group '"IPSEC_GROUP"' failed");
200 return FALSE;
201 }
202 charon->gid = grp->gr_gid;
203 }
204 #endif
205 #ifdef ANDROID
206 charon->uid = AID_VPN;
207 #endif
208 return TRUE;
209 }
210
211 /**
212 * Handle SIGSEGV/SIGILL signals raised by threads
213 */
214 static void segv_handler(int signal)
215 {
216 backtrace_t *backtrace;
217
218 DBG1(DBG_DMN, "thread %u received %d", thread_current_id(), signal);
219 backtrace = backtrace_create(2);
220 backtrace->log(backtrace, stderr, TRUE);
221 backtrace->destroy(backtrace);
222
223 DBG1(DBG_DMN, "killing ourself, received critical signal");
224 abort();
225 }
226
227 /**
228 * Check/create PID file, return TRUE if already running
229 */
230 static bool check_pidfile()
231 {
232 struct stat stb;
233
234 if (stat(PID_FILE, &stb) == 0)
235 {
236 pidfile = fopen(PID_FILE, "r");
237 if (pidfile)
238 {
239 char buf[64];
240 pid_t pid = 0;
241
242 memset(buf, 0, sizeof(buf));
243 if (fread(buf, 1, sizeof(buf), pidfile))
244 {
245 buf[sizeof(buf) - 1] = '\0';
246 pid = atoi(buf);
247 }
248 fclose(pidfile);
249 if (pid && kill(pid, 0) == 0)
250 { /* such a process is running */
251 return TRUE;
252 }
253 }
254 DBG1(DBG_DMN, "removing pidfile '"PID_FILE"', process not running");
255 unlink(PID_FILE);
256 }
257
258 /* create new pidfile */
259 pidfile = fopen(PID_FILE, "w");
260 if (pidfile)
261 {
262 ignore_result(fchown(fileno(pidfile), charon->uid, charon->gid));
263 fprintf(pidfile, "%d\n", getpid());
264 fflush(pidfile);
265 }
266 return FALSE;
267 }
268
269 /**
270 * Delete/truncate the PID file
271 */
272 static void unlink_pidfile()
273 {
274 /* because unlinking the PID file may fail, we truncate it to ensure the
275 * daemon can be properly restarted. one probable cause for this is the
276 * combination of not running as root and the effective user lacking
277 * permissions on the parent dir(s) of the PID file */
278 if (pidfile)
279 {
280 ignore_result(ftruncate(fileno(pidfile), 0));
281 fclose(pidfile);
282 }
283 unlink(PID_FILE);
284 }
285
286 /**
287 * Initialize logging
288 */
289 static void initialize_loggers(bool use_stderr, level_t levels[])
290 {
291 sys_logger_t *sys_logger;
292 file_logger_t *file_logger;
293 enumerator_t *enumerator;
294 char *identifier, *facility, *filename;
295 int loggers_defined = 0;
296 debug_t group;
297 level_t def;
298 bool append, ike_name;
299 FILE *file;
300
301 /* setup sysloggers */
302 identifier = lib->settings->get_str(lib->settings,
303 "charon.syslog.identifier", NULL);
304 if (identifier)
305 { /* set identifier, which is prepended to each log line */
306 openlog(identifier, 0, 0);
307 }
308 enumerator = lib->settings->create_section_enumerator(lib->settings,
309 "charon.syslog");
310 while (enumerator->enumerate(enumerator, &facility))
311 {
312 loggers_defined++;
313
314 ike_name = lib->settings->get_bool(lib->settings,
315 "charon.syslog.%s.ike_name", FALSE, facility);
316 if (streq(facility, "daemon"))
317 {
318 sys_logger = sys_logger_create(LOG_DAEMON, ike_name);
319 }
320 else if (streq(facility, "auth"))
321 {
322 sys_logger = sys_logger_create(LOG_AUTHPRIV, ike_name);
323 }
324 else
325 {
326 continue;
327 }
328 def = lib->settings->get_int(lib->settings,
329 "charon.syslog.%s.default", 1, facility);
330 for (group = 0; group < DBG_MAX; group++)
331 {
332 sys_logger->set_level(sys_logger, group,
333 lib->settings->get_int(lib->settings,
334 "charon.syslog.%s.%N", def,
335 facility, debug_lower_names, group));
336 }
337 charon->sys_loggers->insert_last(charon->sys_loggers, sys_logger);
338 charon->bus->add_logger(charon->bus, &sys_logger->logger);
339 }
340 enumerator->destroy(enumerator);
341
342 /* and file loggers */
343 enumerator = lib->settings->create_section_enumerator(lib->settings,
344 "charon.filelog");
345 while (enumerator->enumerate(enumerator, &filename))
346 {
347 loggers_defined++;
348 if (streq(filename, "stderr"))
349 {
350 file = stderr;
351 }
352 else if (streq(filename, "stdout"))
353 {
354 file = stdout;
355 }
356 else
357 {
358 append = lib->settings->get_bool(lib->settings,
359 "charon.filelog.%s.append", TRUE, filename);
360 file = fopen(filename, append ? "a" : "w");
361 if (file == NULL)
362 {
363 DBG1(DBG_DMN, "opening file %s for logging failed: %s",
364 filename, strerror(errno));
365 continue;
366 }
367 if (lib->settings->get_bool(lib->settings,
368 "charon.filelog.%s.flush_line", FALSE, filename))
369 {
370 setlinebuf(file);
371 }
372 }
373 file_logger = file_logger_create(file,
374 lib->settings->get_str(lib->settings,
375 "charon.filelog.%s.time_format", NULL, filename),
376 lib->settings->get_bool(lib->settings,
377 "charon.filelog.%s.ike_name", FALSE, filename));
378 def = lib->settings->get_int(lib->settings,
379 "charon.filelog.%s.default", 1, filename);
380 for (group = 0; group < DBG_MAX; group++)
381 {
382 file_logger->set_level(file_logger, group,
383 lib->settings->get_int(lib->settings,
384 "charon.filelog.%s.%N", def,
385 filename, debug_lower_names, group));
386 }
387 charon->file_loggers->insert_last(charon->file_loggers, file_logger);
388 charon->bus->add_logger(charon->bus, &file_logger->logger);
389
390 }
391 enumerator->destroy(enumerator);
392
393 /* set up legacy style default loggers provided via command-line */
394 if (!loggers_defined)
395 {
396 /* set up default stdout file_logger */
397 file_logger = file_logger_create(stdout, NULL, FALSE);
398 charon->file_loggers->insert_last(charon->file_loggers, file_logger);
399 /* set up default daemon sys_logger */
400 sys_logger = sys_logger_create(LOG_DAEMON, FALSE);
401 charon->sys_loggers->insert_last(charon->sys_loggers, sys_logger);
402 for (group = 0; group < DBG_MAX; group++)
403 {
404 sys_logger->set_level(sys_logger, group, levels[group]);
405 if (use_stderr)
406 {
407 file_logger->set_level(file_logger, group, levels[group]);
408 }
409 }
410 charon->bus->add_logger(charon->bus, &file_logger->logger);
411 charon->bus->add_logger(charon->bus, &sys_logger->logger);
412
413 /* set up default auth sys_logger */
414 sys_logger = sys_logger_create(LOG_AUTHPRIV, FALSE);
415 sys_logger->set_level(sys_logger, DBG_ANY, LEVEL_AUDIT);
416 charon->sys_loggers->insert_last(charon->sys_loggers, sys_logger);
417 charon->bus->add_logger(charon->bus, &sys_logger->logger);
418 }
419 }
420
421 /**
422 * print command line usage and exit
423 */
424 static void usage(const char *msg)
425 {
426 if (msg != NULL && *msg != '\0')
427 {
428 fprintf(stderr, "%s\n", msg);
429 }
430 fprintf(stderr, "Usage: charon\n"
431 " [--help]\n"
432 " [--version]\n"
433 " [--use-syslog]\n"
434 " [--debug-<type> <level>]\n"
435 " <type>: log context type (dmn|mgr|ike|chd|job|cfg|knl|net|asn|enc|tnc|imc|imv|pts|tls|lib)\n"
436 " <level>: log verbosity (-1 = silent, 0 = audit, 1 = control,\n"
437 " 2 = controlmore, 3 = raw, 4 = private)\n"
438 "\n"
439 );
440 }
441
442 /**
443 * Main function, starts the daemon.
444 */
445 int main(int argc, char *argv[])
446 {
447 struct sigaction action;
448 bool use_syslog = FALSE;
449 level_t levels[DBG_MAX];
450 int group, status = SS_RC_INITIALIZATION_FAILED;
451
452 /* logging for library during initialization, as we have no bus yet */
453 dbg = dbg_stderr;
454
455 /* initialize library */
456 if (!library_init(NULL))
457 {
458 library_deinit();
459 exit(SS_RC_LIBSTRONGSWAN_INTEGRITY);
460 }
461
462 if (lib->integrity &&
463 !lib->integrity->check_file(lib->integrity, "charon", argv[0]))
464 {
465 dbg_stderr(DBG_DMN, 1, "integrity check of charon failed");
466 library_deinit();
467 exit(SS_RC_DAEMON_INTEGRITY);
468 }
469
470 if (!libhydra_init("charon"))
471 {
472 dbg_stderr(DBG_DMN, 1, "initialization failed - aborting charon");
473 libhydra_deinit();
474 library_deinit();
475 exit(SS_RC_INITIALIZATION_FAILED);
476 }
477
478 if (!libcharon_init())
479 {
480 dbg_stderr(DBG_DMN, 1, "initialization failed - aborting charon");
481 goto deinit;
482 }
483
484 /* use CTRL loglevel for default */
485 for (group = 0; group < DBG_MAX; group++)
486 {
487 levels[group] = LEVEL_CTRL;
488 }
489
490 /* handle arguments */
491 for (;;)
492 {
493 struct option long_opts[] = {
494 { "help", no_argument, NULL, 'h' },
495 { "version", no_argument, NULL, 'v' },
496 { "use-syslog", no_argument, NULL, 'l' },
497 /* TODO: handle "debug-all" */
498 { "debug-dmn", required_argument, &group, DBG_DMN },
499 { "debug-mgr", required_argument, &group, DBG_MGR },
500 { "debug-ike", required_argument, &group, DBG_IKE },
501 { "debug-chd", required_argument, &group, DBG_CHD },
502 { "debug-job", required_argument, &group, DBG_JOB },
503 { "debug-cfg", required_argument, &group, DBG_CFG },
504 { "debug-knl", required_argument, &group, DBG_KNL },
505 { "debug-net", required_argument, &group, DBG_NET },
506 { "debug-asn", required_argument, &group, DBG_ASN },
507 { "debug-enc", required_argument, &group, DBG_ENC },
508 { "debug-tnc", required_argument, &group, DBG_TNC },
509 { "debug-imc", required_argument, &group, DBG_IMC },
510 { "debug-imv", required_argument, &group, DBG_IMV },
511 { "debug-pts", required_argument, &group, DBG_PTS },
512 { "debug-tls", required_argument, &group, DBG_TLS },
513 { "debug-lib", required_argument, &group, DBG_LIB },
514 { 0,0,0,0 }
515 };
516
517 int c = getopt_long(argc, argv, "", long_opts, NULL);
518 switch (c)
519 {
520 case EOF:
521 break;
522 case 'h':
523 usage(NULL);
524 status = 0;
525 goto deinit;
526 case 'v':
527 printf("Linux strongSwan %s\n", VERSION);
528 status = 0;
529 goto deinit;
530 case 'l':
531 use_syslog = TRUE;
532 continue;
533 case 0:
534 /* option is in group */
535 levels[group] = atoi(optarg);
536 continue;
537 default:
538 usage("");
539 status = 1;
540 goto deinit;
541 }
542 break;
543 }
544
545 if (!lookup_uid_gid())
546 {
547 dbg_stderr(DBG_DMN, 1, "invalid uid/gid - aborting charon");
548 goto deinit;
549 }
550
551 initialize_loggers(!use_syslog, levels);
552
553 /* initialize daemon */
554 if (!charon->initialize(charon))
555 {
556 DBG1(DBG_DMN, "initialization failed - aborting charon");
557 goto deinit;
558 }
559
560 if (check_pidfile())
561 {
562 DBG1(DBG_DMN, "charon already running (\""PID_FILE"\" exists)");
563 status = -1;
564 goto deinit;
565 }
566
567 if (!drop_capabilities())
568 {
569 DBG1(DBG_DMN, "capability dropping failed - aborting charon");
570 goto deinit;
571 }
572
573 /* add handler for SEGV and ILL,
574 * INT, TERM and HUP are handled by sigwait() in run() */
575 action.sa_handler = segv_handler;
576 action.sa_flags = 0;
577 sigemptyset(&action.sa_mask);
578 sigaddset(&action.sa_mask, SIGINT);
579 sigaddset(&action.sa_mask, SIGTERM);
580 sigaddset(&action.sa_mask, SIGHUP);
581 sigaction(SIGSEGV, &action, NULL);
582 sigaction(SIGILL, &action, NULL);
583 sigaction(SIGBUS, &action, NULL);
584 action.sa_handler = SIG_IGN;
585 sigaction(SIGPIPE, &action, NULL);
586
587 pthread_sigmask(SIG_SETMASK, &action.sa_mask, NULL);
588
589 /* start daemon (i.e. the threads in the thread-pool) */
590 charon->start(charon);
591
592 /* main thread goes to run loop */
593 run();
594
595 /* normal termination, cleanup and exit */
596 unlink_pidfile();
597 status = 0;
598
599 deinit:
600 libcharon_deinit();
601 libhydra_deinit();
602 library_deinit();
603 return status;
604 }
605