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