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