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