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