dcc1c88e529b36640f95c5e73b127b48904928e3
[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>
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 pid = atoi(buf);
246 }
247 fclose(pidfile);
248 if (pid && kill(pid, 0) == 0)
249 { /* such a process is running */
250 return TRUE;
251 }
252 }
253 DBG1(DBG_DMN, "removing pidfile '"PID_FILE"', process not running");
254 unlink(PID_FILE);
255 }
256
257 /* create new pidfile */
258 pidfile = fopen(PID_FILE, "w");
259 if (pidfile)
260 {
261 ignore_result(fchown(fileno(pidfile), charon->uid, charon->gid));
262 fprintf(pidfile, "%d\n", getpid());
263 fflush(pidfile);
264 }
265 return FALSE;
266 }
267
268 /**
269 * Delete/truncate the PID file
270 */
271 static void unlink_pidfile()
272 {
273 /* because unlinking the PID file may fail, we truncate it to ensure the
274 * daemon can be properly restarted. one probable cause for this is the
275 * combination of not running as root and the effective user lacking
276 * permissions on the parent dir(s) of the PID file */
277 if (pidfile)
278 {
279 ignore_result(ftruncate(fileno(pidfile), 0));
280 fclose(pidfile);
281 }
282 unlink(PID_FILE);
283 }
284
285 /**
286 * Initialize logging
287 */
288 static void initialize_loggers(bool use_stderr, level_t levels[])
289 {
290 sys_logger_t *sys_logger;
291 file_logger_t *file_logger;
292 enumerator_t *enumerator;
293 char *facility, *filename;
294 int loggers_defined = 0;
295 debug_t group;
296 level_t def;
297 bool append, ike_name;
298 FILE *file;
299
300 /* setup sysloggers */
301 enumerator = lib->settings->create_section_enumerator(lib->settings,
302 "charon.syslog");
303 while (enumerator->enumerate(enumerator, &facility))
304 {
305 loggers_defined++;
306
307 ike_name = lib->settings->get_bool(lib->settings,
308 "charon.syslog.%s.ike_name", FALSE, facility);
309 if (streq(facility, "daemon"))
310 {
311 sys_logger = sys_logger_create(LOG_DAEMON, ike_name);
312 }
313 else if (streq(facility, "auth"))
314 {
315 sys_logger = sys_logger_create(LOG_AUTHPRIV, ike_name);
316 }
317 else
318 {
319 continue;
320 }
321 def = lib->settings->get_int(lib->settings,
322 "charon.syslog.%s.default", 1, facility);
323 for (group = 0; group < DBG_MAX; group++)
324 {
325 sys_logger->set_level(sys_logger, group,
326 lib->settings->get_int(lib->settings,
327 "charon.syslog.%s.%N", def,
328 facility, debug_lower_names, group));
329 }
330 charon->sys_loggers->insert_last(charon->sys_loggers, sys_logger);
331 charon->bus->add_listener(charon->bus, &sys_logger->listener);
332 }
333 enumerator->destroy(enumerator);
334
335 /* and file loggers */
336 enumerator = lib->settings->create_section_enumerator(lib->settings,
337 "charon.filelog");
338 while (enumerator->enumerate(enumerator, &filename))
339 {
340 loggers_defined++;
341 if (streq(filename, "stderr"))
342 {
343 file = stderr;
344 }
345 else if (streq(filename, "stdout"))
346 {
347 file = stdout;
348 }
349 else
350 {
351 append = lib->settings->get_bool(lib->settings,
352 "charon.filelog.%s.append", TRUE, filename);
353 file = fopen(filename, append ? "a" : "w");
354 if (file == NULL)
355 {
356 DBG1(DBG_DMN, "opening file %s for logging failed: %s",
357 filename, strerror(errno));
358 continue;
359 }
360 if (lib->settings->get_bool(lib->settings,
361 "charon.filelog.%s.flush_line", FALSE, filename))
362 {
363 setlinebuf(file);
364 }
365 }
366 file_logger = file_logger_create(file,
367 lib->settings->get_str(lib->settings,
368 "charon.filelog.%s.time_format", NULL, filename),
369 lib->settings->get_bool(lib->settings,
370 "charon.filelog.%s.ike_name", FALSE, filename));
371 def = lib->settings->get_int(lib->settings,
372 "charon.filelog.%s.default", 1, filename);
373 for (group = 0; group < DBG_MAX; group++)
374 {
375 file_logger->set_level(file_logger, group,
376 lib->settings->get_int(lib->settings,
377 "charon.filelog.%s.%N", def,
378 filename, debug_lower_names, group));
379 }
380 charon->file_loggers->insert_last(charon->file_loggers, file_logger);
381 charon->bus->add_listener(charon->bus, &file_logger->listener);
382
383 }
384 enumerator->destroy(enumerator);
385
386 /* set up legacy style default loggers provided via command-line */
387 if (!loggers_defined)
388 {
389 /* set up default stdout file_logger */
390 file_logger = file_logger_create(stdout, NULL, FALSE);
391 charon->bus->add_listener(charon->bus, &file_logger->listener);
392 charon->file_loggers->insert_last(charon->file_loggers, file_logger);
393 /* set up default daemon sys_logger */
394 sys_logger = sys_logger_create(LOG_DAEMON, FALSE);
395 charon->bus->add_listener(charon->bus, &sys_logger->listener);
396 charon->sys_loggers->insert_last(charon->sys_loggers, sys_logger);
397 for (group = 0; group < DBG_MAX; group++)
398 {
399 sys_logger->set_level(sys_logger, group, levels[group]);
400 if (use_stderr)
401 {
402 file_logger->set_level(file_logger, group, levels[group]);
403 }
404 }
405
406 /* set up default auth sys_logger */
407 sys_logger = sys_logger_create(LOG_AUTHPRIV, FALSE);
408 charon->bus->add_listener(charon->bus, &sys_logger->listener);
409 charon->sys_loggers->insert_last(charon->sys_loggers, sys_logger);
410 sys_logger->set_level(sys_logger, DBG_ANY, LEVEL_AUDIT);
411 }
412 }
413
414 /**
415 * print command line usage and exit
416 */
417 static void usage(const char *msg)
418 {
419 if (msg != NULL && *msg != '\0')
420 {
421 fprintf(stderr, "%s\n", msg);
422 }
423 fprintf(stderr, "Usage: charon\n"
424 " [--help]\n"
425 " [--version]\n"
426 " [--use-syslog]\n"
427 " [--debug-<type> <level>]\n"
428 " <type>: log context type (dmn|mgr|ike|chd|job|cfg|knl|net|enc|tnc|tls|lib)\n"
429 " <level>: log verbosity (-1 = silent, 0 = audit, 1 = control,\n"
430 " 2 = controlmore, 3 = raw, 4 = private)\n"
431 "\n"
432 );
433 }
434
435 /**
436 * Main function, starts the daemon.
437 */
438 int main(int argc, char *argv[])
439 {
440 struct sigaction action;
441 bool use_syslog = FALSE;
442 level_t levels[DBG_MAX];
443 int group, status = SS_RC_INITIALIZATION_FAILED;
444
445 /* logging for library during initialization, as we have no bus yet */
446 dbg = dbg_stderr;
447
448 /* initialize library */
449 if (!library_init(NULL))
450 {
451 library_deinit();
452 exit(SS_RC_LIBSTRONGSWAN_INTEGRITY);
453 }
454
455 if (lib->integrity &&
456 !lib->integrity->check_file(lib->integrity, "charon", argv[0]))
457 {
458 dbg_stderr(DBG_DMN, 1, "integrity check of charon failed");
459 library_deinit();
460 exit(SS_RC_DAEMON_INTEGRITY);
461 }
462
463 if (!libhydra_init("charon"))
464 {
465 dbg_stderr(DBG_DMN, 1, "initialization failed - aborting charon");
466 libhydra_deinit();
467 library_deinit();
468 exit(SS_RC_INITIALIZATION_FAILED);
469 }
470
471 if (!libcharon_init())
472 {
473 dbg_stderr(DBG_DMN, 1, "initialization failed - aborting charon");
474 goto deinit;
475 }
476
477 /* use CTRL loglevel for default */
478 for (group = 0; group < DBG_MAX; group++)
479 {
480 levels[group] = LEVEL_CTRL;
481 }
482
483 /* handle arguments */
484 for (;;)
485 {
486 struct option long_opts[] = {
487 { "help", no_argument, NULL, 'h' },
488 { "version", no_argument, NULL, 'v' },
489 { "use-syslog", no_argument, NULL, 'l' },
490 /* TODO: handle "debug-all" */
491 { "debug-dmn", required_argument, &group, DBG_DMN },
492 { "debug-mgr", required_argument, &group, DBG_MGR },
493 { "debug-ike", required_argument, &group, DBG_IKE },
494 { "debug-chd", required_argument, &group, DBG_CHD },
495 { "debug-job", required_argument, &group, DBG_JOB },
496 { "debug-cfg", required_argument, &group, DBG_CFG },
497 { "debug-knl", required_argument, &group, DBG_KNL },
498 { "debug-net", required_argument, &group, DBG_NET },
499 { "debug-enc", required_argument, &group, DBG_ENC },
500 { "debug-tnc", required_argument, &group, DBG_TNC },
501 { "debug-imc", required_argument, &group, DBG_IMC },
502 { "debug-imv", required_argument, &group, DBG_IMV },
503 { "debug-tls", required_argument, &group, DBG_TLS },
504 { "debug-lib", required_argument, &group, DBG_LIB },
505 { 0,0,0,0 }
506 };
507
508 int c = getopt_long(argc, argv, "", long_opts, NULL);
509 switch (c)
510 {
511 case EOF:
512 break;
513 case 'h':
514 usage(NULL);
515 status = 0;
516 goto deinit;
517 case 'v':
518 printf("Linux strongSwan %s\n", VERSION);
519 status = 0;
520 goto deinit;
521 case 'l':
522 use_syslog = TRUE;
523 continue;
524 case 0:
525 /* option is in group */
526 levels[group] = atoi(optarg);
527 continue;
528 default:
529 usage("");
530 status = 1;
531 goto deinit;
532 }
533 break;
534 }
535
536 if (!lookup_uid_gid())
537 {
538 dbg_stderr(DBG_DMN, 1, "invalid uid/gid - aborting charon");
539 goto deinit;
540 }
541
542 initialize_loggers(!use_syslog, levels);
543
544 /* initialize daemon */
545 if (!charon->initialize(charon))
546 {
547 DBG1(DBG_DMN, "initialization failed - aborting charon");
548 goto deinit;
549 }
550
551 if (check_pidfile())
552 {
553 DBG1(DBG_DMN, "charon already running (\""PID_FILE"\" exists)");
554 status = -1;
555 goto deinit;
556 }
557
558 if (!drop_capabilities())
559 {
560 DBG1(DBG_DMN, "capability dropping failed - aborting charon");
561 goto deinit;
562 }
563
564 /* add handler for SEGV and ILL,
565 * INT, TERM and HUP are handled by sigwait() in run() */
566 action.sa_handler = segv_handler;
567 action.sa_flags = 0;
568 sigemptyset(&action.sa_mask);
569 sigaddset(&action.sa_mask, SIGINT);
570 sigaddset(&action.sa_mask, SIGTERM);
571 sigaddset(&action.sa_mask, SIGHUP);
572 sigaction(SIGSEGV, &action, NULL);
573 sigaction(SIGILL, &action, NULL);
574 sigaction(SIGBUS, &action, NULL);
575 action.sa_handler = SIG_IGN;
576 sigaction(SIGPIPE, &action, NULL);
577
578 pthread_sigmask(SIG_SETMASK, &action.sa_mask, NULL);
579
580 /* start daemon (i.e. the threads in the thread-pool) */
581 charon->start(charon);
582
583 /* main thread goes to run loop */
584 run();
585
586 /* normal termination, cleanup and exit */
587 unlink_pidfile();
588 status = 0;
589
590 deinit:
591 libcharon_deinit();
592 libhydra_deinit();
593 library_deinit();
594 return status;
595 }
596