Truncate the PID file so that even if we fail to unlink it, the daemon can be restart...
[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 * Global reference to PID file (required to truncate, if undeletable)
48 */
49 static FILE *pidfile = NULL;
50
51 /**
52 * hook in library for debugging messages
53 */
54 extern void (*dbg) (debug_t group, level_t level, char *fmt, ...);
55
56 /**
57 * Logging hook for library logs, using stderr output
58 */
59 static void dbg_stderr(debug_t group, level_t level, char *fmt, ...)
60 {
61 va_list args;
62
63 if (level <= 1)
64 {
65 va_start(args, fmt);
66 fprintf(stderr, "00[%N] ", debug_names, group);
67 vfprintf(stderr, fmt, args);
68 fprintf(stderr, "\n");
69 va_end(args);
70 }
71 }
72
73 /**
74 * Run the daemon and handle unix signals
75 */
76 static void run()
77 {
78 sigset_t set;
79
80 /* handle SIGINT, SIGHUP ans SIGTERM in this handler */
81 sigemptyset(&set);
82 sigaddset(&set, SIGINT);
83 sigaddset(&set, SIGHUP);
84 sigaddset(&set, SIGTERM);
85 sigprocmask(SIG_BLOCK, &set, NULL);
86
87 while (TRUE)
88 {
89 int sig;
90 int error;
91
92 error = sigwait(&set, &sig);
93 if (error)
94 {
95 DBG1(DBG_DMN, "error %d while waiting for a signal", error);
96 return;
97 }
98 switch (sig)
99 {
100 case SIGHUP:
101 {
102 DBG1(DBG_DMN, "signal of type SIGHUP received. Ignored");
103 break;
104 }
105 case SIGINT:
106 {
107 DBG1(DBG_DMN, "signal of type SIGINT received. Shutting down");
108 charon->bus->alert(charon->bus, ALERT_SHUTDOWN_SIGNAL, sig);
109 return;
110 }
111 case SIGTERM:
112 {
113 DBG1(DBG_DMN, "signal of type SIGTERM received. Shutting down");
114 charon->bus->alert(charon->bus, ALERT_SHUTDOWN_SIGNAL, sig);
115 return;
116 }
117 default:
118 {
119 DBG1(DBG_DMN, "unknown signal %d received. Ignored", sig);
120 break;
121 }
122 }
123 }
124 }
125
126 /**
127 * drop daemon capabilities
128 */
129 static bool drop_capabilities()
130 {
131 #ifdef HAVE_PRCTL
132 prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
133 #endif
134
135 if (setgid(charon->gid) != 0)
136 {
137 DBG1(DBG_DMN, "change to unprivileged group failed");
138 return FALSE;
139 }
140 if (setuid(charon->uid) != 0)
141 {
142 DBG1(DBG_DMN, "change to unprivileged user failed");
143 return FALSE;
144 }
145 if (!charon->drop_capabilities(charon))
146 {
147 DBG1(DBG_DMN, "unable to drop daemon capabilities");
148 return FALSE;
149 }
150 return TRUE;
151 }
152
153 /**
154 * lookup UID and GID
155 */
156 static bool lookup_uid_gid()
157 {
158 #ifdef IPSEC_USER
159 {
160 char buf[1024];
161 struct passwd passwd, *pwp;
162
163 if (getpwnam_r(IPSEC_USER, &passwd, buf, sizeof(buf), &pwp) != 0 ||
164 pwp == NULL)
165 {
166 DBG1(DBG_DMN, "resolving user '"IPSEC_USER"' failed");
167 return FALSE;
168 }
169 charon->uid = pwp->pw_uid;
170 }
171 #endif
172 #ifdef IPSEC_GROUP
173 {
174 char buf[1024];
175 struct group group, *grp;
176
177 if (getgrnam_r(IPSEC_GROUP, &group, buf, sizeof(buf), &grp) != 0 ||
178 grp == NULL)
179 {
180 DBG1(DBG_DMN, "resolving group '"IPSEC_GROUP"' failed");
181 return FALSE;
182 }
183 charon->gid = grp->gr_gid;
184 }
185 #endif
186 return TRUE;
187 }
188
189 /**
190 * Handle SIGSEGV/SIGILL signals raised by threads
191 */
192 static void segv_handler(int signal)
193 {
194 backtrace_t *backtrace;
195
196 DBG1(DBG_DMN, "thread %u received %d", thread_current_id(), signal);
197 backtrace = backtrace_create(2);
198 backtrace->log(backtrace, stderr, TRUE);
199 backtrace->destroy(backtrace);
200
201 DBG1(DBG_DMN, "killing ourself, received critical signal");
202 abort();
203 }
204
205 /**
206 * Check/create PID file, return TRUE if already running
207 */
208 static bool check_pidfile()
209 {
210 struct stat stb;
211
212 if (stat(PID_FILE, &stb) == 0)
213 {
214 pidfile = fopen(PID_FILE, "r");
215 if (pidfile)
216 {
217 char buf[64];
218 pid_t pid = 0;
219
220 memset(buf, 0, sizeof(buf));
221 if (fread(buf, 1, sizeof(buf), pidfile))
222 {
223 pid = atoi(buf);
224 }
225 fclose(pidfile);
226 if (pid && kill(pid, 0) == 0)
227 { /* such a process is running */
228 return TRUE;
229 }
230 }
231 DBG1(DBG_DMN, "removing pidfile '"PID_FILE"', process not running");
232 unlink(PID_FILE);
233 }
234
235 /* create new pidfile */
236 pidfile = fopen(PID_FILE, "w");
237 if (pidfile)
238 {
239 ignore_result(fchown(fileno(pidfile), charon->uid, charon->gid));
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 ftruncate(fileno(pidfile), 0);
258 fclose(pidfile);
259 }
260 unlink(PID_FILE);
261 }
262
263
264 /**
265 * print command line usage and exit
266 */
267 static void usage(const char *msg)
268 {
269 if (msg != NULL && *msg != '\0')
270 {
271 fprintf(stderr, "%s\n", msg);
272 }
273 fprintf(stderr, "Usage: charon\n"
274 " [--help]\n"
275 " [--version]\n"
276 " [--use-syslog]\n"
277 " [--debug-<type> <level>]\n"
278 " <type>: log context type (dmn|mgr|ike|chd|job|cfg|knl|net|enc|lib)\n"
279 " <level>: log verbosity (-1 = silent, 0 = audit, 1 = control,\n"
280 " 2 = controlmore, 3 = raw, 4 = private)\n"
281 "\n"
282 );
283 }
284
285 /**
286 * Main function, starts the daemon.
287 */
288 int main(int argc, char *argv[])
289 {
290 struct sigaction action;
291 bool use_syslog = FALSE;
292 level_t levels[DBG_MAX];
293 int group, status = SS_RC_INITIALIZATION_FAILED;
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))
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("charon"))
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-enc", required_argument, &group, DBG_ENC },
350 { "debug-lib", required_argument, &group, DBG_LIB },
351 { 0,0,0,0 }
352 };
353
354 int c = getopt_long(argc, argv, "", long_opts, NULL);
355 switch (c)
356 {
357 case EOF:
358 break;
359 case 'h':
360 usage(NULL);
361 status = 0;
362 goto deinit;
363 case 'v':
364 printf("Linux strongSwan %s\n", VERSION);
365 status = 0;
366 goto deinit;
367 case 'l':
368 use_syslog = TRUE;
369 continue;
370 case 0:
371 /* option is in group */
372 levels[group] = atoi(optarg);
373 continue;
374 default:
375 usage("");
376 status = 1;
377 goto deinit;
378 }
379 break;
380 }
381
382 if (!lookup_uid_gid())
383 {
384 dbg_stderr(DBG_DMN, 1, "invalid uid/gid - aborting charon");
385 goto deinit;
386 }
387
388 /* initialize daemon */
389 if (!charon->initialize(charon, use_syslog, levels))
390 {
391 DBG1(DBG_DMN, "initialization failed - aborting charon");
392 goto deinit;
393 }
394
395 if (check_pidfile())
396 {
397 DBG1(DBG_DMN, "charon already running (\""PID_FILE"\" exists)");
398 status = -1;
399 goto deinit;
400 }
401
402 if (!drop_capabilities())
403 {
404 DBG1(DBG_DMN, "capability dropping failed - aborting charon");
405 goto deinit;
406 }
407
408 /* add handler for SEGV and ILL,
409 * INT, TERM and HUP are handled by sigwait() in run() */
410 action.sa_handler = segv_handler;
411 action.sa_flags = 0;
412 sigemptyset(&action.sa_mask);
413 sigaddset(&action.sa_mask, SIGINT);
414 sigaddset(&action.sa_mask, SIGTERM);
415 sigaddset(&action.sa_mask, SIGHUP);
416 sigaction(SIGSEGV, &action, NULL);
417 sigaction(SIGILL, &action, NULL);
418 sigaction(SIGBUS, &action, NULL);
419 action.sa_handler = SIG_IGN;
420 sigaction(SIGPIPE, &action, NULL);
421
422 pthread_sigmask(SIG_SETMASK, &action.sa_mask, NULL);
423
424 /* start daemon (i.e. the threads in the thread-pool) */
425 charon->start(charon);
426
427 /* main thread goes to run loop */
428 run();
429
430 /* normal termination, cleanup and exit */
431 unlink_pidfile();
432 status = 0;
433
434 deinit:
435 libcharon_deinit();
436 libhydra_deinit();
437 library_deinit();
438 return status;
439 }
440