4d86b0bac3158b2e593f52d119c6ea59b05ee402
[strongswan.git] / src / libimcv / imcv.c
1 /*
2 * Copyright (C) 2011 Andreas Steffen, HSR Hochschule fuer Technik Rapperswil
3 *
4 * This program is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License as published by the
6 * Free Software Foundation; either version 2 of the License, or (at your
7 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
8 *
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
11 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * for more details.
13 */
14
15 #include "imcv.h"
16
17 #include "utils.h"
18 #include <debug.h>
19
20 #include <syslog.h>
21
22 /**
23 * Reference count for IMC/IMV instances
24 */
25 refcount_t ref = 0;
26
27 /**
28 * Global configuration of libimcv dbg function
29 */
30 static int debug_level = 3;
31 static bool stderr_quiet = FALSE;
32
33 /**
34 * libimvc dbg function
35 */
36 static void libimcv_dbg(debug_t group, level_t level, char *fmt, ...)
37 {
38 int priority = LOG_INFO;
39 char buffer[8192];
40 char *current = buffer, *next;
41 va_list args;
42
43 if (level <= debug_level)
44 {
45 if (!stderr_quiet)
46 {
47 va_start(args, fmt);
48 vfprintf(stderr, fmt, args);
49 fprintf(stderr, "\n");
50 va_end(args);
51 }
52
53 /* write in memory buffer first */
54 va_start(args, fmt);
55 vsnprintf(buffer, sizeof(buffer), fmt, args);
56 va_end(args);
57
58 /* do a syslog with every line */
59 while (current)
60 {
61 next = strchr(current, '\n');
62 if (next)
63 {
64 *(next++) = '\0';
65 }
66 syslog(priority, "%s\n", current);
67 current = next;
68 }
69 }
70 }
71
72 /**
73 * Described in header.
74 */
75 bool libimcv_init(void)
76 {
77 /* initialize libstrongswan library only once */
78 if (lib)
79 {
80 /* did main program initialize libstrongswan? */
81 if (ref == 0)
82 {
83 ref_get(&ref);
84 }
85 }
86 else
87 {
88 /* we are the first to initialize libstrongswan */
89 if (!library_init(NULL))
90 {
91 return FALSE;
92 }
93
94 if (!lib->plugins->load(lib->plugins, NULL, "random"))
95 {
96 library_deinit();
97 return FALSE;
98 }
99
100 /* enable libimcv debugging hook */
101 dbg = libimcv_dbg;
102 openlog("imcv", 0, LOG_DAEMON);
103
104 DBG1(DBG_LIB, "libimcv initialized");
105 }
106 ref_get(&ref);
107
108 return TRUE;
109 }
110
111 /**
112 * Described in header.
113 */
114 void libimcv_deinit(void)
115 {
116 if (ref_put(&ref))
117 {
118 DBG1(DBG_LIB, "libimcv terminated");
119 library_deinit();
120 }
121 }
122
123