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