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