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