handle zero size Base64 conversions
[strongswan.git] / src / charon / charon.c
1 /*
2 * Copyright (C) 2006-2010 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 #ifdef HAVE_PRCTL
21 #include <sys/prctl.h>
22 #endif
23 #define _POSIX_PTHREAD_SEMANTICS /* for two param sigwait on OpenSolaris */
24 #include <signal.h>
25 #undef _POSIX_PTHREAD_SEMANTICS
26 #include <pthread.h>
27 #include <sys/stat.h>
28 #include <sys/types.h>
29 #include <syslog.h>
30 #include <errno.h>
31 #include <unistd.h>
32 #include <getopt.h>
33 #include <pwd.h>
34 #include <grp.h>
35
36 #include <hydra.h>
37 #include <daemon.h>
38
39 #include <library.h>
40 #include <utils/backtrace.h>
41 #include <threading/thread.h>
42
43 #ifdef ANDROID
44 #include <private/android_filesystem_config.h>
45 #endif
46
47 #ifndef LOG_AUTHPRIV /* not defined on OpenSolaris */
48 #define LOG_AUTHPRIV LOG_AUTH
49 #endif
50
51 /**
52 * PID file, in which charon stores its process id
53 */
54 #define PID_FILE IPSEC_PIDDIR "/charon.pid"
55
56 /**
57 * Global reference to PID file (required to truncate, if undeletable)
58 */
59 static FILE *pidfile = NULL;
60
61 /**
62 * hook in library for debugging messages
63 */
64 extern void (*dbg) (debug_t group, level_t level, char *fmt, ...);
65
66 /**
67 * Logging hook for library logs, using stderr output
68 */
69 static void dbg_stderr(debug_t group, level_t level, char *fmt, ...)
70 {
71 va_list args;
72
73 if (level <= 1)
74 {
75 va_start(args, fmt);
76 fprintf(stderr, "00[%N] ", debug_names, group);
77 vfprintf(stderr, fmt, args);
78 fprintf(stderr, "\n");
79 va_end(args);
80 }
81 }
82
83 /**
84 * Run the daemon and handle unix signals
85 */
86 static void run()
87 {
88 sigset_t set;
89
90 /* handle SIGINT, SIGHUP ans SIGTERM in this handler */
91 sigemptyset(&set);
92 sigaddset(&set, SIGINT);
93 sigaddset(&set, SIGHUP);
94 sigaddset(&set, SIGTERM);
95 sigprocmask(SIG_BLOCK, &set, NULL);
96
97 while (TRUE)
98 {
99 int sig;
100 int error;
101
102 error = sigwait(&set, &sig);
103 if (error)
104 {
105 DBG1(DBG_DMN, "error %d while waiting for a signal", error);
106 return;
107 }
108 switch (sig)
109 {
110 case SIGHUP:
111 {
112 DBG1(DBG_DMN, "signal of type SIGHUP received. Ignored");
113 break;
114 }
115 case SIGINT:
116 {
117 DBG1(DBG_DMN, "signal of type SIGINT received. Shutting down");
118 charon->bus->alert(charon->bus, ALERT_SHUTDOWN_SIGNAL, sig);
119 return;
120 }
121 case SIGTERM:
122 {
123 DBG1(DBG_DMN, "signal of type SIGTERM received. Shutting down");
124 charon->bus->alert(charon->bus, ALERT_SHUTDOWN_SIGNAL, sig);
125 return;
126 }
127 default:
128 {
129 DBG1(DBG_DMN, "unknown signal %d received. Ignored", sig);
130 break;
131 }
132 }
133 }
134 }
135
136 /**
137 * drop daemon capabilities
138 */
139 static bool drop_capabilities()
140 {
141 #ifdef HAVE_PRCTL
142 prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
143 #endif
144
145 if (setgid(charon->gid) != 0)
146 {
147 DBG1(DBG_DMN, "change to unprivileged group failed");
148 return FALSE;
149 }
150 if (setuid(charon->uid) != 0)
151 {
152 DBG1(DBG_DMN, "change to unprivileged user failed");
153 return FALSE;
154 }
155 if (!charon->drop_capabilities(charon))
156 {
157 DBG1(DBG_DMN, "unable to drop daemon capabilities");
158 return FALSE;
159 }
160 return TRUE;
161 }
162
163 /**
164 * lookup UID and GID
165 */
166 static bool lookup_uid_gid()
167 {
168 #ifdef IPSEC_USER
169 {
170 char buf[1024];
171 struct passwd passwd, *pwp;
172
173 if (getpwnam_r(IPSEC_USER, &passwd, buf, sizeof(buf), &pwp) != 0 ||
174 pwp == NULL)
175 {
176 DBG1(DBG_DMN, "resolving user '"IPSEC_USER"' failed");
177 return FALSE;
178 }
179 charon->uid = pwp->pw_uid;
180 }
181 #endif
182 #ifdef IPSEC_GROUP
183 {
184 char buf[1024];
185 struct group group, *grp;
186
187 if (getgrnam_r(IPSEC_GROUP, &group, buf, sizeof(buf), &grp) != 0 ||
188 grp == NULL)
189 {
190 DBG1(DBG_DMN, "resolving group '"IPSEC_GROUP"' failed");
191 return FALSE;
192 }
193 charon->gid = grp->gr_gid;
194 }
195 #endif
196 #ifdef ANDROID
197 charon->uid = AID_VPN;
198 #endif
199 return TRUE;
200 }
201
202 /**
203 * Handle SIGSEGV/SIGILL signals raised by threads
204 */
205 static void segv_handler(int signal)
206 {
207 backtrace_t *backtrace;
208
209 DBG1(DBG_DMN, "thread %u received %d", thread_current_id(), signal);
210 backtrace = backtrace_create(2);
211 backtrace->log(backtrace, stderr, TRUE);
212 backtrace->destroy(backtrace);
213
214 DBG1(DBG_DMN, "killing ourself, received critical signal");
215 abort();
216 }
217
218 /**
219 * Check/create PID file, return TRUE if already running
220 */
221 static bool check_pidfile()
222 {
223 struct stat stb;
224
225 if (stat(PID_FILE, &stb) == 0)
226 {
227 pidfile = fopen(PID_FILE, "r");
228 if (pidfile)
229 {
230 char buf[64];
231 pid_t pid = 0;
232
233 memset(buf, 0, sizeof(buf));
234 if (fread(buf, 1, sizeof(buf), pidfile))
235 {
236 pid = atoi(buf);
237 }
238 fclose(pidfile);
239 if (pid && kill(pid, 0) == 0)
240 { /* such a process is running */
241 return TRUE;
242 }
243 }
244 DBG1(DBG_DMN, "removing pidfile '"PID_FILE"', process not running");
245 unlink(PID_FILE);
246 }
247
248 /* create new pidfile */
249 pidfile = fopen(PID_FILE, "w");
250 if (pidfile)
251 {
252 ignore_result(fchown(fileno(pidfile), charon->uid, charon->gid));
253 fprintf(pidfile, "%d\n", getpid());
254 fflush(pidfile);
255 }
256 return FALSE;
257 }
258
259 /**
260 * Delete/truncate the PID file
261 */
262 static void unlink_pidfile()
263 {
264 /* because unlinking the PID file may fail, we truncate it to ensure the
265 * daemon can be properly restarted. one probable cause for this is the
266 * combination of not running as root and the effective user lacking
267 * permissions on the parent dir(s) of the PID file */
268 if (pidfile)
269 {
270 ignore_result(ftruncate(fileno(pidfile), 0));
271 fclose(pidfile);
272 }
273 unlink(PID_FILE);
274 }
275
276 /**
277 * Initialize logging
278 */
279 static void initialize_loggers(bool use_stderr, level_t levels[])
280 {
281 sys_logger_t *sys_logger;
282 file_logger_t *file_logger;
283 enumerator_t *enumerator;
284 char *facility, *filename;
285 int loggers_defined = 0;
286 debug_t group;
287 level_t def;
288 bool append, ike_name;
289 FILE *file;
290
291 /* setup sysloggers */
292 enumerator = lib->settings->create_section_enumerator(lib->settings,
293 "charon.syslog");
294 while (enumerator->enumerate(enumerator, &facility))
295 {
296 loggers_defined++;
297
298 ike_name = lib->settings->get_bool(lib->settings,
299 "charon.syslog.%s.ike_name", FALSE, facility);
300 if (streq(facility, "daemon"))
301 {
302 sys_logger = sys_logger_create(LOG_DAEMON, ike_name);
303 }
304 else if (streq(facility, "auth"))
305 {
306 sys_logger = sys_logger_create(LOG_AUTHPRIV, ike_name);
307 }
308 else
309 {
310 continue;
311 }
312 def = lib->settings->get_int(lib->settings,
313 "charon.syslog.%s.default", 1, facility);
314 for (group = 0; group < DBG_MAX; group++)
315 {
316 sys_logger->set_level(sys_logger, group,
317 lib->settings->get_int(lib->settings,
318 "charon.syslog.%s.%N", def,
319 facility, debug_lower_names, group));
320 }
321 charon->sys_loggers->insert_last(charon->sys_loggers, sys_logger);
322 charon->bus->add_listener(charon->bus, &sys_logger->listener);
323 }
324 enumerator->destroy(enumerator);
325
326 /* and file loggers */
327 enumerator = lib->settings->create_section_enumerator(lib->settings,
328 "charon.filelog");
329 while (enumerator->enumerate(enumerator, &filename))
330 {
331 loggers_defined++;
332 if (streq(filename, "stderr"))
333 {
334 file = stderr;
335 }
336 else if (streq(filename, "stdout"))
337 {
338 file = stdout;
339 }
340 else
341 {
342 append = lib->settings->get_bool(lib->settings,
343 "charon.filelog.%s.append", TRUE, filename);
344 file = fopen(filename, append ? "a" : "w");
345 if (file == NULL)
346 {
347 DBG1(DBG_DMN, "opening file %s for logging failed: %s",
348 filename, strerror(errno));
349 continue;
350 }
351 if (lib->settings->get_bool(lib->settings,
352 "charon.filelog.%s.flush_line", FALSE, filename))
353 {
354 setlinebuf(file);
355 }
356 }
357 file_logger = file_logger_create(file,
358 lib->settings->get_str(lib->settings,
359 "charon.filelog.%s.time_format", NULL, filename),
360 lib->settings->get_bool(lib->settings,
361 "charon.filelog.%s.ike_name", FALSE, filename));
362 def = lib->settings->get_int(lib->settings,
363 "charon.filelog.%s.default", 1, filename);
364 for (group = 0; group < DBG_MAX; group++)
365 {
366 file_logger->set_level(file_logger, group,
367 lib->settings->get_int(lib->settings,
368 "charon.filelog.%s.%N", def,
369 filename, debug_lower_names, group));
370 }
371 charon->file_loggers->insert_last(charon->file_loggers, file_logger);
372 charon->bus->add_listener(charon->bus, &file_logger->listener);
373
374 }
375 enumerator->destroy(enumerator);
376
377 /* set up legacy style default loggers provided via command-line */
378 if (!loggers_defined)
379 {
380 /* set up default stdout file_logger */
381 file_logger = file_logger_create(stdout, NULL, FALSE);
382 charon->bus->add_listener(charon->bus, &file_logger->listener);
383 charon->file_loggers->insert_last(charon->file_loggers, file_logger);
384 /* set up default daemon sys_logger */
385 sys_logger = sys_logger_create(LOG_DAEMON, FALSE);
386 charon->bus->add_listener(charon->bus, &sys_logger->listener);
387 charon->sys_loggers->insert_last(charon->sys_loggers, sys_logger);
388 for (group = 0; group < DBG_MAX; group++)
389 {
390 sys_logger->set_level(sys_logger, group, levels[group]);
391 if (use_stderr)
392 {
393 file_logger->set_level(file_logger, group, levels[group]);
394 }
395 }
396
397 /* set up default auth sys_logger */
398 sys_logger = sys_logger_create(LOG_AUTHPRIV, FALSE);
399 charon->bus->add_listener(charon->bus, &sys_logger->listener);
400 charon->sys_loggers->insert_last(charon->sys_loggers, sys_logger);
401 sys_logger->set_level(sys_logger, DBG_ANY, LEVEL_AUDIT);
402 }
403 }
404
405 /**
406 * print command line usage and exit
407 */
408 static void usage(const char *msg)
409 {
410 if (msg != NULL && *msg != '\0')
411 {
412 fprintf(stderr, "%s\n", msg);
413 }
414 fprintf(stderr, "Usage: charon\n"
415 " [--help]\n"
416 " [--version]\n"
417 " [--use-syslog]\n"
418 " [--debug-<type> <level>]\n"
419 " <type>: log context type (dmn|mgr|ike|chd|job|cfg|knl|net|enc|tnc|tls|lib)\n"
420 " <level>: log verbosity (-1 = silent, 0 = audit, 1 = control,\n"
421 " 2 = controlmore, 3 = raw, 4 = private)\n"
422 "\n"
423 );
424 }
425
426 /**
427 * Main function, starts the daemon.
428 */
429 int main(int argc, char *argv[])
430 {
431 struct sigaction action;
432 bool use_syslog = FALSE;
433 level_t levels[DBG_MAX];
434 int group, status = SS_RC_INITIALIZATION_FAILED;
435
436 /* logging for library during initialization, as we have no bus yet */
437 dbg = dbg_stderr;
438
439 /* initialize library */
440 if (!library_init(NULL))
441 {
442 library_deinit();
443 exit(SS_RC_LIBSTRONGSWAN_INTEGRITY);
444 }
445
446 if (lib->integrity &&
447 !lib->integrity->check_file(lib->integrity, "charon", argv[0]))
448 {
449 dbg_stderr(DBG_DMN, 1, "integrity check of charon failed");
450 library_deinit();
451 exit(SS_RC_DAEMON_INTEGRITY);
452 }
453
454 if (!libhydra_init("charon"))
455 {
456 dbg_stderr(DBG_DMN, 1, "initialization failed - aborting charon");
457 libhydra_deinit();
458 library_deinit();
459 exit(SS_RC_INITIALIZATION_FAILED);
460 }
461
462 if (!libcharon_init())
463 {
464 dbg_stderr(DBG_DMN, 1, "initialization failed - aborting charon");
465 goto deinit;
466 }
467
468 /* use CTRL loglevel for default */
469 for (group = 0; group < DBG_MAX; group++)
470 {
471 levels[group] = LEVEL_CTRL;
472 }
473
474 /* handle arguments */
475 for (;;)
476 {
477 struct option long_opts[] = {
478 { "help", no_argument, NULL, 'h' },
479 { "version", no_argument, NULL, 'v' },
480 { "use-syslog", no_argument, NULL, 'l' },
481 /* TODO: handle "debug-all" */
482 { "debug-dmn", required_argument, &group, DBG_DMN },
483 { "debug-mgr", required_argument, &group, DBG_MGR },
484 { "debug-ike", required_argument, &group, DBG_IKE },
485 { "debug-chd", required_argument, &group, DBG_CHD },
486 { "debug-job", required_argument, &group, DBG_JOB },
487 { "debug-cfg", required_argument, &group, DBG_CFG },
488 { "debug-knl", required_argument, &group, DBG_KNL },
489 { "debug-net", required_argument, &group, DBG_NET },
490 { "debug-enc", required_argument, &group, DBG_ENC },
491 { "debug-tnc", required_argument, &group, DBG_TNC },
492 { "debug-tls", required_argument, &group, DBG_TLS },
493 { "debug-lib", required_argument, &group, DBG_LIB },
494 { 0,0,0,0 }
495 };
496
497 int c = getopt_long(argc, argv, "", long_opts, NULL);
498 switch (c)
499 {
500 case EOF:
501 break;
502 case 'h':
503 usage(NULL);
504 status = 0;
505 goto deinit;
506 case 'v':
507 printf("Linux strongSwan %s\n", VERSION);
508 status = 0;
509 goto deinit;
510 case 'l':
511 use_syslog = TRUE;
512 continue;
513 case 0:
514 /* option is in group */
515 levels[group] = atoi(optarg);
516 continue;
517 default:
518 usage("");
519 status = 1;
520 goto deinit;
521 }
522 break;
523 }
524
525 if (!lookup_uid_gid())
526 {
527 dbg_stderr(DBG_DMN, 1, "invalid uid/gid - aborting charon");
528 goto deinit;
529 }
530
531 initialize_loggers(!use_syslog, levels);
532
533 /* initialize daemon */
534 if (!charon->initialize(charon))
535 {
536 DBG1(DBG_DMN, "initialization failed - aborting charon");
537 goto deinit;
538 }
539
540 if (check_pidfile())
541 {
542 DBG1(DBG_DMN, "charon already running (\""PID_FILE"\" exists)");
543 status = -1;
544 goto deinit;
545 }
546
547 if (!drop_capabilities())
548 {
549 DBG1(DBG_DMN, "capability dropping failed - aborting charon");
550 goto deinit;
551 }
552
553 /* add handler for SEGV and ILL,
554 * INT, TERM and HUP are handled by sigwait() in run() */
555 action.sa_handler = segv_handler;
556 action.sa_flags = 0;
557 sigemptyset(&action.sa_mask);
558 sigaddset(&action.sa_mask, SIGINT);
559 sigaddset(&action.sa_mask, SIGTERM);
560 sigaddset(&action.sa_mask, SIGHUP);
561 sigaction(SIGSEGV, &action, NULL);
562 sigaction(SIGILL, &action, NULL);
563 sigaction(SIGBUS, &action, NULL);
564 action.sa_handler = SIG_IGN;
565 sigaction(SIGPIPE, &action, NULL);
566
567 pthread_sigmask(SIG_SETMASK, &action.sa_mask, NULL);
568
569 /* start daemon (i.e. the threads in the thread-pool) */
570 charon->start(charon);
571
572 /* main thread goes to run loop */
573 run();
574
575 /* normal termination, cleanup and exit */
576 unlink_pidfile();
577 status = 0;
578
579 deinit:
580 libcharon_deinit();
581 libhydra_deinit();
582 library_deinit();
583 return status;
584 }
585