charon-cmd: Handle simple command line arguments like --help before the others
[strongswan.git] / src / charon-cmd / charon-cmd.c
1 /*
2 * Copyright (C) 2006-2013 Tobias Brunner
3 * Copyright (C) 2005-2013 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 #define _POSIX_PTHREAD_SEMANTICS /* for two param sigwait on OpenSolaris */
21 #include <signal.h>
22 #undef _POSIX_PTHREAD_SEMANTICS
23 #include <pthread.h>
24 #include <sys/types.h>
25 #include <sys/utsname.h>
26 #include <unistd.h>
27 #include <getopt.h>
28
29 #include <library.h>
30 #include <hydra.h>
31 #include <daemon.h>
32 #include <utils/backtrace.h>
33 #include <threading/thread.h>
34
35 #include "cmd/cmd_options.h"
36 #include "cmd/cmd_connection.h"
37 #include "cmd/cmd_creds.h"
38
39 /**
40 * Loglevel configuration
41 */
42 static level_t levels[DBG_MAX];
43
44 /**
45 * Connection to initiate
46 */
47 static cmd_connection_t *conn;
48
49 /**
50 * Credential backend
51 */
52 static cmd_creds_t *creds;
53
54 /**
55 * hook in library for debugging messages
56 */
57 extern void (*dbg) (debug_t group, level_t level, char *fmt, ...);
58
59 /**
60 * Logging hook for library logs, using stderr output
61 */
62 static void dbg_stderr(debug_t group, level_t level, char *fmt, ...)
63 {
64 va_list args;
65
66 if (level <= 1)
67 {
68 va_start(args, fmt);
69 fprintf(stderr, "00[%N] ", debug_names, group);
70 vfprintf(stderr, fmt, args);
71 fprintf(stderr, "\n");
72 va_end(args);
73 }
74 }
75
76 /**
77 * Clean up connection definition atexit()
78 */
79 static void cleanup_conn()
80 {
81 DESTROY_IF(conn);
82 }
83
84 /**
85 * Clean up credentials atexit()
86 */
87 static void cleanup_creds()
88 {
89 DESTROY_IF(creds);
90 }
91
92 /**
93 * Run the daemon and handle unix signals
94 */
95 static int run()
96 {
97 sigset_t set;
98
99 /* handle SIGINT, SIGHUP and SIGTERM in this handler */
100 sigemptyset(&set);
101 sigaddset(&set, SIGINT);
102 sigaddset(&set, SIGHUP);
103 sigaddset(&set, SIGTERM);
104 sigaddset(&set, SIGUSR1);
105 sigprocmask(SIG_BLOCK, &set, NULL);
106
107 while (TRUE)
108 {
109 int sig;
110 int error;
111
112 error = sigwait(&set, &sig);
113 if (error)
114 {
115 DBG1(DBG_DMN, "error %d while waiting for a signal", error);
116 return 1;
117 }
118 switch (sig)
119 {
120 case SIGHUP:
121 {
122 DBG1(DBG_DMN, "signal of type SIGHUP received. Reloading "
123 "configuration");
124 if (lib->settings->load_files(lib->settings, NULL, FALSE))
125 {
126 charon->load_loggers(charon, levels, TRUE);
127 lib->plugins->reload(lib->plugins, NULL);
128 }
129 else
130 {
131 DBG1(DBG_DMN, "reloading config failed, keeping old");
132 }
133 break;
134 }
135 case SIGINT:
136 {
137 DBG1(DBG_DMN, "signal of type SIGINT received. Shutting down");
138 charon->bus->alert(charon->bus, ALERT_SHUTDOWN_SIGNAL, sig);
139 return 0;
140 }
141 case SIGTERM:
142 {
143 DBG1(DBG_DMN, "signal of type SIGTERM received. Shutting down");
144 charon->bus->alert(charon->bus, ALERT_SHUTDOWN_SIGNAL, sig);
145 return 0;
146 }
147 case SIGUSR1:
148 { /* an error occured */
149 charon->bus->alert(charon->bus, ALERT_SHUTDOWN_SIGNAL, sig);
150 return 1;
151 }
152 default:
153 {
154 DBG1(DBG_DMN, "unknown signal %d received. Ignored", sig);
155 break;
156 }
157 }
158 }
159 }
160
161 /**
162 * lookup UID and GID
163 */
164 static bool lookup_uid_gid()
165 {
166 #ifdef IPSEC_USER
167 if (!charon->caps->resolve_uid(charon->caps, IPSEC_USER))
168 {
169 return FALSE;
170 }
171 #endif
172 #ifdef IPSEC_GROUP
173 if (!charon->caps->resolve_gid(charon->caps, IPSEC_GROUP))
174 {
175 return FALSE;
176 }
177 #endif
178 return TRUE;
179 }
180
181 /**
182 * Handle SIGSEGV/SIGILL signals raised by threads
183 */
184 static void segv_handler(int signal)
185 {
186 backtrace_t *backtrace;
187
188 DBG1(DBG_DMN, "thread %u received %d", thread_current_id(), signal);
189 backtrace = backtrace_create(2);
190 backtrace->log(backtrace, stderr, TRUE);
191 backtrace->destroy(backtrace);
192
193 DBG1(DBG_DMN, "killing ourself, received critical signal");
194 abort();
195 }
196
197 /**
198 * Print command line usage and exit
199 */
200 static void usage(FILE *out, char *msg, char *binary)
201 {
202 char *pre, *post;
203 int i, line, padto = 0, spacing = 2;
204
205 for (i = 0; i < CMD_OPT_COUNT; i++)
206 {
207 padto = max(padto, strlen(cmd_options[i].name) +
208 strlen(cmd_options[i].arg));
209 }
210 padto += spacing;
211
212 if (msg)
213 {
214 fprintf(out, "%s\n", msg);
215 }
216 fprintf(out, "Usage: %s\n", binary);
217 for (i = 0; i < CMD_OPT_COUNT; i++)
218 {
219 switch (cmd_options[i].has_arg)
220 {
221 case required_argument:
222 pre = " <";
223 post = ">";
224 break;
225 case optional_argument:
226 pre = "[=";
227 post = "]";
228 break;
229 case no_argument:
230 default:
231 pre = " ";
232 post = " ";
233 break;
234 }
235 fprintf(out, " --%s%s%s%s %-*s%s\n",
236 cmd_options[i].name,
237 pre, cmd_options[i].arg, post,
238 padto - strlen(cmd_options[i].name) - strlen(cmd_options[i].arg), "",
239 cmd_options[i].desc);
240 for (line = 0; line < countof(cmd_options[i].lines); line++)
241 {
242 if (cmd_options[i].lines[line])
243 {
244 fprintf(out, "%-*s %s\n",
245 padto, "", cmd_options[i].lines[line]);
246 }
247 }
248 }
249 }
250
251 /**
252 * Handle command line options, if simple is TRUE only arguments like --help
253 * and --version are handled.
254 */
255 static void handle_arguments(int argc, char *argv[], bool simple)
256 {
257 struct option long_opts[CMD_OPT_COUNT + 1] = {};
258 int i, opt;
259
260 for (i = 0; i < CMD_OPT_COUNT; i++)
261 {
262 long_opts[i].name = cmd_options[i].name;
263 long_opts[i].val = cmd_options[i].id;
264 long_opts[i].has_arg = cmd_options[i].has_arg;
265 }
266 /* reset option parser */
267 optind = 1;
268 while (TRUE)
269 {
270 bool handled = FALSE;
271
272 opt = getopt_long(argc, argv, "", long_opts, NULL);
273 switch (opt)
274 {
275 case EOF:
276 break;
277 case CMD_OPT_HELP:
278 usage(stdout, NULL, argv[0]);
279 exit(0);
280 case CMD_OPT_VERSION:
281 printf("%s, strongSwan %s\n", "charon-cmd", VERSION);
282 exit(0);
283 default:
284 if (simple)
285 {
286 continue;
287 }
288 handled |= conn->handle(conn, opt, optarg);
289 handled |= creds->handle(creds, opt, optarg);
290 if (handled)
291 {
292 continue;
293 }
294 /* fall-through */
295 case '?':
296 /* missing argument, unrecognized option */
297 usage(stderr, NULL, argv[0]);
298 exit(1);
299 }
300 break;
301 }
302 }
303
304 /**
305 * Main function, starts the daemon.
306 */
307 int main(int argc, char *argv[])
308 {
309 struct sigaction action;
310 struct utsname utsname;
311 int group;
312
313 /* handle simple arguments */
314 handle_arguments(argc, argv, TRUE);
315
316 dbg = dbg_stderr;
317 atexit(library_deinit);
318 if (!library_init(NULL))
319 {
320 exit(SS_RC_LIBSTRONGSWAN_INTEGRITY);
321 }
322 if (lib->integrity)
323 {
324 if (!lib->integrity->check_file(lib->integrity, "charon-cmd", argv[0]))
325 {
326 exit(SS_RC_DAEMON_INTEGRITY);
327 }
328 }
329 atexit(libhydra_deinit);
330 if (!libhydra_init("charon-cmd"))
331 {
332 exit(SS_RC_INITIALIZATION_FAILED);
333 }
334 atexit(libcharon_deinit);
335 if (!libcharon_init("charon-cmd"))
336 {
337 exit(SS_RC_INITIALIZATION_FAILED);
338 }
339 for (group = 0; group < DBG_MAX; group++)
340 {
341 levels[group] = LEVEL_CTRL;
342 }
343 charon->load_loggers(charon, levels, TRUE);
344
345 if (!lookup_uid_gid())
346 {
347 exit(SS_RC_INITIALIZATION_FAILED);
348 }
349 lib->settings->set_default_str(lib->settings, "charon-cmd.port", "0");
350 lib->settings->set_default_str(lib->settings, "charon-cmd.port_nat_t", "0");
351 if (!charon->initialize(charon,
352 lib->settings->get_str(lib->settings, "charon-cmd.load", PLUGINS)))
353 {
354 exit(SS_RC_INITIALIZATION_FAILED);
355 }
356 if (!charon->caps->drop(charon->caps))
357 {
358 exit(SS_RC_INITIALIZATION_FAILED);
359 }
360
361 conn = cmd_connection_create();
362 atexit(cleanup_conn);
363 creds = cmd_creds_create();
364 atexit(cleanup_creds);
365
366 /* handle all arguments */
367 handle_arguments(argc, argv, FALSE);
368
369 if (uname(&utsname) != 0)
370 {
371 memset(&utsname, 0, sizeof(utsname));
372 }
373 DBG1(DBG_DMN, "Starting charon-cmd IKE client (strongSwan %s, %s %s, %s)",
374 VERSION, utsname.sysname, utsname.release, utsname.machine);
375 lib->plugins->status(lib->plugins, LEVEL_CTRL);
376
377 /* add handler for SEGV and ILL,
378 * INT, TERM and HUP are handled by sigwait() in run() */
379 action.sa_handler = segv_handler;
380 action.sa_flags = 0;
381 sigemptyset(&action.sa_mask);
382 sigaddset(&action.sa_mask, SIGINT);
383 sigaddset(&action.sa_mask, SIGTERM);
384 sigaddset(&action.sa_mask, SIGHUP);
385 sigaction(SIGSEGV, &action, NULL);
386 sigaction(SIGILL, &action, NULL);
387 sigaction(SIGBUS, &action, NULL);
388 action.sa_handler = SIG_IGN;
389 sigaction(SIGPIPE, &action, NULL);
390
391 pthread_sigmask(SIG_SETMASK, &action.sa_mask, NULL);
392
393 /* start daemon with thread-pool */
394 charon->start(charon);
395 /* wait for signal */
396 return run();
397 }