Merge pull request #1469 from sni/master
[monitoring-plugins.git] / lib / parse_ini.c
blob25abc89bd391e4cf52b87314d007c8d839fa301c
1 /*****************************************************************************
2 *
3 * Monitoring Plugins parse_ini library
4 *
5 * License: GPL
6 * Copyright (c) 2007 Monitoring Plugins Development Team
7 *
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
22 *****************************************************************************/
24 #include "common.h"
25 #include "idpriv.h"
26 #include "utils_base.h"
27 #include "parse_ini.h"
29 #include <ctype.h>
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <unistd.h>
34 /* np_ini_info contains the result of parsing a "locator" in the format
35 * [stanza_name][@config_filename] (check_foo@/etc/foo.ini, for example)
37 typedef struct {
38 char *file;
39 char *stanza;
40 } np_ini_info;
42 static char *default_ini_file_names[] = {
43 "monitoring-plugins.ini",
44 "plugins.ini",
45 "nagios-plugins.ini",
46 NULL
49 static char *default_ini_path_names[] = {
50 "/usr/local/etc/monitoring-plugins/monitoring-plugins.ini",
51 "/usr/local/etc/monitoring-plugins.ini",
52 "/etc/monitoring-plugins/monitoring-plugins.ini",
53 "/etc/monitoring-plugins.ini",
54 /* deprecated path names (for backward compatibility): */
55 "/etc/nagios/plugins.ini",
56 "/usr/local/nagios/etc/plugins.ini",
57 "/usr/local/etc/nagios/plugins.ini",
58 "/etc/opt/nagios/plugins.ini",
59 "/etc/nagios-plugins.ini",
60 "/usr/local/etc/nagios-plugins.ini",
61 "/etc/opt/nagios-plugins.ini",
62 NULL
65 /* eat all characters from a FILE pointer until n is encountered */
66 #define GOBBLE_TO(f, c, n) do { (c)=fgetc((f)); } while((c)!=EOF && (c)!=(n))
68 /* internal function that returns the constructed defaults options */
69 static int read_defaults(FILE *f, const char *stanza, np_arg_list **opts);
71 /* internal function that converts a single line into options format */
72 static int add_option(FILE *f, np_arg_list **optlst);
74 /* internal functions to find default file */
75 static char *default_file(void);
76 static char *default_file_in_path(void);
79 * Parse_locator decomposes a string of the form
80 * [stanza][@filename]
81 * into its seperate parts.
83 static void
84 parse_locator(const char *locator, const char *def_stanza, np_ini_info *i)
86 size_t locator_len = 0, stanza_len = 0;
88 /* if locator is NULL we'll use default values */
89 if (locator != NULL) {
90 locator_len = strlen(locator);
91 stanza_len = strcspn(locator, "@");
93 /* if a non-default stanza is provided */
94 if (stanza_len > 0) {
95 i->stanza = malloc(sizeof(char) * (stanza_len + 1));
96 strncpy(i->stanza, locator, stanza_len);
97 i->stanza[stanza_len] = '\0';
98 } else /* otherwise we use the default stanza */
99 i->stanza = strdup(def_stanza);
101 if (i->stanza == NULL)
102 die(STATE_UNKNOWN, _("malloc() failed!\n"));
104 /* check whether there's an @file part */
105 i->file = stanza_len == locator_len
106 ? default_file()
107 : strdup(&(locator[stanza_len + 1]));
108 if (i->file == NULL || i->file[0] == '\0')
109 die(STATE_UNKNOWN,
110 _("Cannot find config file in any standard location.\n"));
114 * This is the externally visible function used by extra_opts.
116 np_arg_list *
117 np_get_defaults(const char *locator, const char *default_section)
119 FILE *inifile = NULL;
120 np_arg_list *defaults = NULL;
121 np_ini_info i;
122 int is_suid_plugin = mp_suid();
124 if (is_suid_plugin && idpriv_temp_drop() == -1)
125 die(STATE_UNKNOWN, _("Cannot drop privileges: %s\n"),
126 strerror(errno));
128 parse_locator(locator, default_section, &i);
129 inifile = strcmp(i.file, "-") == 0 ? stdin : fopen(i.file, "r");
131 if (inifile == NULL)
132 die(STATE_UNKNOWN, _("Can't read config file: %s\n"),
133 strerror(errno));
134 if (read_defaults(inifile, i.stanza, &defaults) == FALSE)
135 die(STATE_UNKNOWN,
136 _("Invalid section '%s' in config file '%s'\n"), i.stanza,
137 i.file);
139 free(i.file);
140 if (inifile != stdin)
141 fclose(inifile);
142 free(i.stanza);
143 if (is_suid_plugin && idpriv_temp_restore() == -1)
144 die(STATE_UNKNOWN, _("Cannot restore privileges: %s\n"),
145 strerror(errno));
147 return defaults;
151 * The read_defaults() function is where the meat of the parsing takes place.
153 * Note that this may be called by a setuid binary, so we need to
154 * be extra careful about user-supplied input (i.e. avoiding possible
155 * format string vulnerabilities, etc).
157 static int
158 read_defaults(FILE *f, const char *stanza, np_arg_list **opts)
160 int c, status = FALSE;
161 size_t i, stanza_len;
162 enum { NOSTANZA, WRONGSTANZA, RIGHTSTANZA } stanzastate = NOSTANZA;
164 stanza_len = strlen(stanza);
166 /* our little stanza-parsing state machine */
167 while ((c = fgetc(f)) != EOF) {
168 /* gobble up leading whitespace */
169 if (isspace(c))
170 continue;
171 switch (c) {
172 /* globble up coment lines */
173 case ';':
174 case '#':
175 GOBBLE_TO(f, c, '\n');
176 break;
177 /* start of a stanza, check to see if it matches */
178 case '[':
179 stanzastate = WRONGSTANZA;
180 for (i = 0; i < stanza_len; i++) {
181 c = fgetc(f);
182 /* strip leading whitespace */
183 if (i == 0)
184 for (; isspace(c); c = fgetc(f))
185 continue;
186 /* nope, read to the end of the line */
187 if (c != stanza[i]) {
188 GOBBLE_TO(f, c, '\n');
189 break;
192 /* if it matched up to here and the next char is ']'... */
193 if (i == stanza_len) {
194 c = fgetc(f);
195 /* strip trailing whitespace */
196 for (; isspace(c); c = fgetc(f))
197 continue;
198 if (c == ']')
199 stanzastate = RIGHTSTANZA;
201 break;
202 /* otherwise, we're in the body of a stanza or a parse error */
203 default:
204 switch (stanzastate) {
205 /* we never found the start of the first stanza, so
206 * we're dealing with a config error
208 case NOSTANZA:
209 die(STATE_UNKNOWN, "%s\n",
210 _("Config file error"));
211 /* we're in a stanza, but for a different plugin */
212 case WRONGSTANZA:
213 GOBBLE_TO(f, c, '\n');
214 break;
215 /* okay, this is where we start taking the config */
216 case RIGHTSTANZA:
217 ungetc(c, f);
218 if (add_option(f, opts)) {
219 die(STATE_UNKNOWN, "%s\n",
220 _("Config file error"));
222 status = TRUE;
223 break;
225 break;
228 return status;
232 * Read one line of input in the format
233 * ^option[[:space:]]*(=[[:space:]]*value)?
234 * and create it as a cmdline argument
235 * --option[=value]
236 * appending it to the linked list optbuf.
238 static int
239 add_option(FILE *f, np_arg_list **optlst)
241 np_arg_list *opttmp = *optlst, *optnew;
242 char *linebuf = NULL, *lineend = NULL, *optptr = NULL, *optend = NULL;
243 char *eqptr = NULL, *valptr = NULL, *valend = NULL;
244 short done_reading = 0, equals = 0, value = 0;
245 size_t cfg_len = 0, read_sz = 8, linebuf_sz = 0, read_pos = 0;
246 size_t opt_len = 0, val_len = 0;
248 /* read one line from the file */
249 while (!done_reading) {
250 /* grow if necessary */
251 if (linebuf == NULL || read_pos + read_sz >= linebuf_sz) {
252 linebuf_sz = linebuf_sz > 0 ? linebuf_sz << 1 : read_sz;
253 linebuf = realloc(linebuf, linebuf_sz);
254 if (linebuf == NULL)
255 die(STATE_UNKNOWN, _("malloc() failed!\n"));
257 if (fgets(&linebuf[read_pos], (int)read_sz, f) == NULL)
258 done_reading = 1;
259 else {
260 read_pos = strlen(linebuf);
261 if (linebuf[read_pos - 1] == '\n') {
262 linebuf[--read_pos] = '\0';
263 done_reading = 1;
267 lineend = &linebuf[read_pos];
268 /* all that to read one line, isn't C fun? :) now comes the parsing :/ */
270 /* skip leading whitespace */
271 for (optptr = linebuf; optptr < lineend && isspace(*optptr); optptr++)
272 continue;
273 /* continue to '=' or EOL, watching for spaces that might precede it */
274 for (eqptr = optptr; eqptr < lineend && *eqptr != '='; eqptr++) {
275 if (isspace(*eqptr) && optend == NULL)
276 optend = eqptr;
277 else
278 optend = NULL;
280 if (optend == NULL)
281 optend = eqptr;
282 --optend;
283 /* ^[[:space:]]*=foo is a syntax error */
284 if (optptr == eqptr)
285 die(STATE_UNKNOWN, "%s\n", _("Config file error"));
286 /* continue from '=' to start of value or EOL */
287 for (valptr = eqptr + 1; valptr < lineend && isspace(*valptr);
288 valptr++)
289 continue;
290 /* continue to the end of value */
291 for (valend = valptr; valend < lineend; valend++)
292 continue;
293 --valend;
294 /* finally trim off trailing spaces */
295 for (; isspace(*valend); valend--)
296 continue;
297 /* calculate the length of "--foo" */
298 opt_len = (size_t)(1 + optend - optptr);
299 /* 1-character params needs only one dash */
300 if (opt_len == 1)
301 cfg_len = 1 + (opt_len);
302 else
303 cfg_len = 2 + (opt_len);
304 /* if valptr<lineend then we have to also allocate space for "=bar" */
305 if (valptr < lineend) {
306 equals = value = 1;
307 val_len = (size_t)(1 + valend - valptr);
308 cfg_len += 1 + val_len;
310 /* if valptr==valend then we have "=" but no "bar" */
311 else if (valptr == lineend) {
312 equals = 1;
313 cfg_len += 1;
315 /* a line with no equal sign isn't valid */
316 if (equals == 0)
317 die(STATE_UNKNOWN, "%s\n", _("Config file error"));
319 /* okay, now we have all the info we need, so we create a new np_arg_list
320 * element and set the argument...
322 optnew = malloc(sizeof(np_arg_list));
323 optnew->next = NULL;
325 read_pos = 0;
326 optnew->arg = malloc(cfg_len + 1);
327 /* 1-character params needs only one dash */
328 if (opt_len == 1) {
329 strncpy(&optnew->arg[read_pos], "-", 1);
330 read_pos += 1;
331 } else {
332 strncpy(&optnew->arg[read_pos], "--", 2);
333 read_pos += 2;
335 strncpy(&optnew->arg[read_pos], optptr, opt_len);
336 read_pos += opt_len;
337 if (value) {
338 optnew->arg[read_pos++] = '=';
339 strncpy(&optnew->arg[read_pos], valptr, val_len);
340 read_pos += val_len;
342 optnew->arg[read_pos] = '\0';
344 /* ...and put that to the end of the list */
345 if (*optlst == NULL)
346 *optlst = optnew;
347 else {
348 while (opttmp->next != NULL)
349 opttmp = opttmp->next;
350 opttmp->next = optnew;
353 free(linebuf);
354 return 0;
357 static char *
358 default_file(void)
360 char **p, *ini_file;
362 if ((ini_file = getenv("MP_CONFIG_FILE")) != NULL ||
363 (ini_file = default_file_in_path()) != NULL)
364 return ini_file;
365 for (p = default_ini_path_names; *p != NULL; p++)
366 if (access(*p, F_OK) == 0)
367 return *p;
368 return NULL;
371 static char *
372 default_file_in_path(void)
374 char *config_path, **file;
375 char *dir, *ini_file, *tokens;
377 if ((config_path = getenv("NAGIOS_CONFIG_PATH")) == NULL)
378 return NULL;
379 /* shall we spit out a warning that NAGIOS_CONFIG_PATH is deprecated? */
381 if ((tokens = strdup(config_path)) == NULL)
382 die(STATE_UNKNOWN, "%s\n", _("Insufficient Memory"));
383 for (dir = strtok(tokens, ":"); dir != NULL; dir = strtok(NULL, ":")) {
384 for (file = default_ini_file_names; *file != NULL; file++) {
385 if ((asprintf(&ini_file, "%s/%s", dir, *file)) < 0)
386 die(STATE_UNKNOWN, "%s\n", _("Insufficient Memory"));
387 if (access(ini_file, F_OK) == 0) {
388 free(tokens);
389 return ini_file;
393 free(tokens);
394 return NULL;