swanctl: Stop logging with Ctrl+C on Windows as well
[strongswan.git] / src / swanctl / commands / log.c
1 /*
2 * Copyright (C) 2014 Martin Willi
3 * Copyright (C) 2014 revosec AG
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * for more details.
14 */
15
16 #include "command.h"
17
18 #include <errno.h>
19 #include <unistd.h>
20
21 CALLBACK(log_cb, void,
22 bool *raw, char *name, vici_res_t *msg)
23 {
24 if (*raw)
25 {
26 vici_dump(msg, "log", stdout);
27 }
28 else
29 {
30 char *current, *next;
31
32 current = vici_find_str(msg, NULL, "msg");
33 while (current)
34 {
35 next = strchr(current, '\n');
36 printf("%.2d[%s] ", vici_find_int(msg, 0, "thread"),
37 vici_find_str(msg, " ", "group"));
38 if (next == NULL)
39 {
40 printf("%s\n", current);
41 break;
42 }
43 printf("%.*s\n", (int)(next - current), current);
44 current = next + 1;
45 }
46 }
47 }
48
49 static int logcmd(vici_conn_t *conn)
50 {
51 bool raw = FALSE;
52 char *arg;
53
54 while (TRUE)
55 {
56 switch (command_getopt(&arg))
57 {
58 case 'h':
59 return command_usage(NULL);
60 case 'r':
61 raw = TRUE;
62 continue;
63 case EOF:
64 break;
65 default:
66 return command_usage("invalid --log option");
67 }
68 break;
69 }
70
71 if (vici_register(conn, "log", log_cb, &raw) != 0)
72 {
73 fprintf(stderr, "registering for log failed: %s\n", strerror(errno));
74 return errno;
75 }
76
77 wait_sigint();
78
79 fprintf(stderr, "disconnecting...\n");
80
81 return 0;
82 }
83
84 /**
85 * Register the command.
86 */
87 static void __attribute__ ((constructor))reg()
88 {
89 command_register((command_t) {
90 logcmd, 'T', "log", "trace logging output",
91 {"[--raw]"},
92 {
93 {"help", 'h', 0, "show usage information"},
94 {"raw", 'r', 0, "dump raw response message"},
95 }
96 });
97 }