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