sigwaitinfo() may fail with EINTR if interrupted by an unblocked signal not in the set
[strongswan.git] / src / charon-systemd / charon-systemd.c
1 /*
2 * Copyright (C) 2006-2012 Tobias Brunner
3 * Copyright (C) 2005-2014 Martin Willi
4 * Copyright (C) 2006 Daniel Roethlisberger
5 * Copyright (C) 2005 Jan Hutter
6 * Hochschule fuer Technik Rapperswil
7 * Copyright (C) 2014 revosec AG
8 *
9 * This program is free software; you can redistribute it and/or modify it
10 * under the terms of the GNU General Public License as published by the
11 * Free Software Foundation; either version 2 of the License, or (at your
12 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
13 *
14 * This program is distributed in the hope that it will be useful, but
15 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
16 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
17 * for more details.
18 */
19
20 #include <signal.h>
21 #include <stdio.h>
22 #include <pthread.h>
23 #include <sys/stat.h>
24 #include <sys/types.h>
25 #include <sys/utsname.h>
26 #include <unistd.h>
27 #include <errno.h>
28
29 /* won't make sense from our logging hook */
30 #define SD_JOURNAL_SUPPRESS_LOCATION
31 #include <systemd/sd-daemon.h>
32 #include <systemd/sd-journal.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 #include <threading/rwlock.h>
41
42 /**
43 * Default user and group
44 */
45 #ifndef IPSEC_USER
46 #define IPSEC_USER NULL
47 #endif
48
49 #ifndef IPSEC_GROUP
50 #define IPSEC_GROUP NULL
51 #endif
52
53 /**
54 * hook in library for debugging messages
55 */
56 extern void (*dbg) (debug_t group, level_t level, char *fmt, ...);
57
58 /**
59 * Logging hook for library logs, using stderr output
60 */
61 static void dbg_stderr(debug_t group, level_t level, char *fmt, ...)
62 {
63 va_list args;
64
65 if (level <= 1)
66 {
67 va_start(args, fmt);
68 fprintf(stderr, "00[%N] ", debug_names, group);
69 vfprintf(stderr, fmt, args);
70 fprintf(stderr, "\n");
71 va_end(args);
72 }
73 }
74
75 typedef struct journal_logger_t journal_logger_t;
76
77 /**
78 * Logger implementation using systemd-journal
79 */
80 struct journal_logger_t {
81
82 /**
83 * Implements logger_t
84 */
85 logger_t logger;
86
87 /**
88 * Configured loglevels
89 */
90 level_t levels[DBG_MAX];
91
92 /**
93 * Lock for levels
94 */
95 rwlock_t *lock;
96 };
97
98 METHOD(logger_t, vlog, void,
99 journal_logger_t *this, debug_t group, level_t level, int thread,
100 ike_sa_t *ike_sa, const char *fmt, va_list args)
101 {
102 char buf[4096], *msg = buf;
103 ssize_t len;
104 va_list copy;
105
106 va_copy(copy, args);
107 len = vsnprintf(msg, sizeof(buf), fmt, copy);
108 va_end(copy);
109
110 if (len >= sizeof(buf))
111 {
112 len++;
113 msg = malloc(len);
114 va_copy(copy, args);
115 len = vsnprintf(msg, len, fmt, copy);
116 va_end(copy);
117 }
118 if (len > 0)
119 {
120 char unique[64] = "", name[256] = "";
121 int priority;
122
123 if (ike_sa)
124 {
125 snprintf(unique, sizeof(unique), "IKE_SA_UNIQUE_ID=%u",
126 ike_sa->get_unique_id(ike_sa));
127 if (ike_sa->get_peer_cfg(ike_sa))
128 {
129 snprintf(name, sizeof(name), "IKE_SA_NAME=%s",
130 ike_sa->get_name(ike_sa));
131 }
132 }
133 switch (level)
134 {
135 case LEVEL_AUDIT:
136 priority = LOG_NOTICE;
137 break;
138 case LEVEL_CTRL:
139 priority = LOG_INFO;
140 break;
141 default:
142 priority = LOG_DEBUG;
143 break;
144 }
145 sd_journal_send(
146 "MESSAGE=%s", msg,
147 "MESSAGE_ID=57d2708c-d607-43bd-8c39-66bf%.8x",
148 chunk_hash_static(chunk_from_str((char*)fmt)),
149 "PRIORITY=%d", priority,
150 "GROUP=%N", debug_names, group,
151 "LEVEL=%d", level,
152 "THREAD=%d", thread,
153 unique[0] ? unique : NULL,
154 name[0] ? name : NULL,
155 NULL);
156 }
157 if (msg != buf)
158 {
159 free(msg);
160 }
161 }
162
163 METHOD(logger_t, get_level, level_t,
164 journal_logger_t *this, debug_t group)
165 {
166 level_t level;
167
168 this->lock->read_lock(this->lock);
169 level = this->levels[group];
170 this->lock->unlock(this->lock);
171
172 return level;
173 }
174
175 /**
176 * Reload journal logger configuration
177 */
178 CALLBACK(journal_reload, bool,
179 journal_logger_t **journal)
180 {
181 journal_logger_t *this = *journal;
182 debug_t group;
183 level_t def;
184
185 def = lib->settings->get_int(lib->settings, "%s.journal.default", 1, lib->ns);
186
187 this->lock->write_lock(this->lock);
188 for (group = 0; group < DBG_MAX; group++)
189 {
190 this->levels[group] =
191 lib->settings->get_int(lib->settings,
192 "%s.journal.%N", def, lib->ns, debug_lower_names, group);
193 }
194 this->lock->unlock(this->lock);
195
196 charon->bus->add_logger(charon->bus, &this->logger);
197
198 return TRUE;
199 }
200
201 /**
202 * Initialize/deinitialize journal logger
203 */
204 static bool journal_register(void *plugin, plugin_feature_t *feature,
205 bool reg, journal_logger_t **logger)
206 {
207 journal_logger_t *this;
208
209 if (reg)
210 {
211 INIT(this,
212 .logger = {
213 .vlog = _vlog,
214 .get_level = _get_level,
215 },
216 .lock = rwlock_create(RWLOCK_TYPE_DEFAULT),
217 );
218
219 journal_reload(&this);
220
221 *logger = this;
222 return TRUE;
223 }
224 else
225 {
226 this = *logger;
227
228 charon->bus->remove_logger(charon->bus, &this->logger);
229
230 this->lock->destroy(this->lock);
231 free(this);
232
233 return TRUE;
234 }
235 }
236
237 /**
238 * Run the daemon and handle unix signals
239 */
240 static int run()
241 {
242 sigset_t set;
243
244 sigemptyset(&set);
245 sigaddset(&set, SIGTERM);
246 sigprocmask(SIG_BLOCK, &set, NULL);
247
248 sd_notify(0, "READY=1\n");
249
250 while (TRUE)
251 {
252 int sig;
253
254 sig = sigwaitinfo(&set, NULL);
255 if (sig == -1)
256 {
257 if (errno == EINTR)
258 { /* ignore signals we didn't wait for */
259 continue;
260 }
261 DBG1(DBG_DMN, "waiting for signal failed: %s", strerror(errno));
262 return SS_RC_INITIALIZATION_FAILED;
263 }
264 switch (sig)
265 {
266 case SIGTERM:
267 {
268 DBG1(DBG_DMN, "SIGTERM received, shutting down");
269 charon->bus->alert(charon->bus, ALERT_SHUTDOWN_SIGNAL, sig);
270 return 0;
271 }
272 }
273 }
274 }
275
276 /**
277 * lookup UID and GID
278 */
279 static bool lookup_uid_gid()
280 {
281 char *name;
282
283 name = lib->settings->get_str(lib->settings, "%s.user", IPSEC_USER,
284 lib->ns);
285 if (name && !lib->caps->resolve_uid(lib->caps, name))
286 {
287 return FALSE;
288 }
289 name = lib->settings->get_str(lib->settings, "%s.group", IPSEC_GROUP,
290 lib->ns);
291 if (name && !lib->caps->resolve_gid(lib->caps, name))
292 {
293 return FALSE;
294 }
295 return TRUE;
296 }
297
298 /**
299 * Handle SIGSEGV/SIGILL signals raised by threads
300 */
301 static void segv_handler(int signal)
302 {
303 backtrace_t *backtrace;
304
305 DBG1(DBG_DMN, "thread %u received %d", thread_current_id(), signal);
306 backtrace = backtrace_create(2);
307 backtrace->log(backtrace, NULL, TRUE);
308 backtrace->log(backtrace, stderr, TRUE);
309 backtrace->destroy(backtrace);
310
311 DBG1(DBG_DMN, "killing ourself, received critical signal");
312 abort();
313 }
314
315 /**
316 * The journal logger instance
317 */
318 static journal_logger_t *journal;
319
320 /**
321 * Journal static features
322 */
323 static plugin_feature_t features[] = {
324 PLUGIN_CALLBACK((plugin_feature_callback_t)journal_register, &journal),
325 PLUGIN_PROVIDE(CUSTOM, "systemd-journal"),
326 };
327
328 /**
329 * Main function, starts the daemon.
330 */
331 int main(int argc, char *argv[])
332 {
333 struct sigaction action;
334 struct utsname utsname;
335
336 dbg = dbg_stderr;
337
338 if (uname(&utsname) != 0)
339 {
340 memset(&utsname, 0, sizeof(utsname));
341 }
342
343 sd_notifyf(0, "STATUS=Starting charon-systemd, strongSwan %s, %s %s, %s",
344 VERSION, utsname.sysname, utsname.release, utsname.machine);
345
346 atexit(library_deinit);
347 if (!library_init(NULL, "charon-systemd"))
348 {
349 sd_notifyf(0, "STATUS=libstrongswan initialization failed");
350 return SS_RC_INITIALIZATION_FAILED;
351 }
352 if (lib->integrity &&
353 !lib->integrity->check_file(lib->integrity, "charon-systemd", argv[0]))
354 {
355 sd_notifyf(0, "STATUS=integrity check of charon-systemd failed");
356 return SS_RC_INITIALIZATION_FAILED;
357 }
358 atexit(libhydra_deinit);
359 if (!libhydra_init())
360 {
361 sd_notifyf(0, "STATUS=libhydra initialization failed");
362 return SS_RC_INITIALIZATION_FAILED;
363 }
364 atexit(libcharon_deinit);
365 if (!libcharon_init())
366 {
367 sd_notifyf(0, "STATUS=libcharon initialization failed");
368 return SS_RC_INITIALIZATION_FAILED;
369 }
370 if (!lookup_uid_gid())
371 {
372 sd_notifyf(0, "STATUS=unknown uid/gid");
373 return SS_RC_INITIALIZATION_FAILED;
374 }
375 charon->load_loggers(charon, NULL, FALSE);
376
377 lib->plugins->add_static_features(lib->plugins, lib->ns, features,
378 countof(features), TRUE, journal_reload, &journal);
379
380 if (!charon->initialize(charon,
381 lib->settings->get_str(lib->settings, "%s.load", PLUGINS, lib->ns)))
382 {
383 sd_notifyf(0, "STATUS=charon initialization failed");
384 return SS_RC_INITIALIZATION_FAILED;
385 }
386 lib->plugins->status(lib->plugins, LEVEL_CTRL);
387
388 if (!lib->caps->drop(lib->caps))
389 {
390 sd_notifyf(0, "STATUS=dropping capabilities failed");
391 return SS_RC_INITIALIZATION_FAILED;
392 }
393
394 /* add handler for SEGV and ILL,
395 * INT, TERM and HUP are handled by sigwaitinfo() in run() */
396 action.sa_handler = segv_handler;
397 action.sa_flags = 0;
398 sigemptyset(&action.sa_mask);
399 sigaddset(&action.sa_mask, SIGINT);
400 sigaddset(&action.sa_mask, SIGTERM);
401 sigaddset(&action.sa_mask, SIGHUP);
402 sigaction(SIGSEGV, &action, NULL);
403 sigaction(SIGILL, &action, NULL);
404 sigaction(SIGBUS, &action, NULL);
405 action.sa_handler = SIG_IGN;
406 sigaction(SIGPIPE, &action, NULL);
407
408 pthread_sigmask(SIG_SETMASK, &action.sa_mask, NULL);
409
410 charon->start(charon);
411
412 sd_notifyf(0, "STATUS=charon-systemd running, strongSwan %s, %s %s, %s",
413 VERSION, utsname.sysname, utsname.release, utsname.machine);
414
415 return run();
416 }