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