lib/parse_ini.[ch]: Change code formatting
[monitoring-plugins.git] / lib / parse_ini.c
bloba5b3d3065550b5c4fcd2bc9ec6de495d8b57f99b
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 "utils_base.h"
26 #include "parse_ini.h"
28 #include <ctype.h>
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <unistd.h>
33 /* np_ini_info contains the result of parsing a "locator" in the format
34 * [stanza_name][@config_filename] (check_foo@/etc/foo.ini, for example)
36 typedef struct {
37 char *file;
38 char *stanza;
39 } np_ini_info;
41 static char *default_ini_file_names[] = {
42 "monitoring-plugins.ini",
43 "plugins.ini",
44 "nagios-plugins.ini",
45 NULL
48 static char *default_ini_path_names[] = {
49 "/usr/local/etc/monitoring-plugins.ini",
50 "/etc/monitoring-plugins.ini",
51 /* Deprecated path names (for backward compatibility): */
52 "/etc/nagios/plugins.ini",
53 "/usr/local/nagios/etc/plugins.ini",
54 "/usr/local/etc/nagios/plugins.ini",
55 "/etc/opt/nagios/plugins.ini",
56 "/etc/nagios-plugins.ini",
57 "/usr/local/etc/nagios-plugins.ini",
58 "/etc/opt/nagios-plugins.ini",
59 NULL
62 /* eat all characters from a FILE pointer until n is encountered */
63 #define GOBBLE_TO(f, c, n) do { (c)=fgetc((f)); } while((c)!=EOF && (c)!=(n))
65 /* internal function that returns the constructed defaults options */
66 static int read_defaults(FILE *f, const char *stanza, np_arg_list **opts);
68 /* internal function that converts a single line into options format */
69 static int add_option(FILE *f, np_arg_list **optlst);
71 /* internal function to find default file */
72 static char *default_file(void);
74 /* parse_locator decomposes a string of the form
75 * [stanza][@filename]
76 * into its seperate parts
78 static void
79 parse_locator(const char *locator, const char *def_stanza, np_ini_info *i)
81 size_t locator_len = 0, stanza_len = 0;
83 /* if locator is NULL we'll use default values */
84 if (locator != NULL) {
85 locator_len = strlen(locator);
86 stanza_len = strcspn(locator, "@");
88 /* if a non-default stanza is provided */
89 if (stanza_len > 0) {
90 i->stanza = malloc(sizeof(char) * (stanza_len + 1));
91 strncpy(i->stanza, locator, stanza_len);
92 i->stanza[stanza_len] = '\0';
93 } else /* otherwise we use the default stanza */
94 i->stanza = strdup(def_stanza);
96 if (i->stanza == NULL)
97 die(STATE_UNKNOWN, _("malloc() failed!\n"));
99 /* check whether there's an @file part */
100 i->file = stanza_len == locator_len
101 ? default_file()
102 : strdup(&(locator[stanza_len + 1]));
103 if (i->file == NULL || i->file[0] == '\0')
104 die(STATE_UNKNOWN,
105 _("Cannot find config file in any standard location.\n"));
108 /* this is the externally visible function used by extra_opts */
109 np_arg_list *
110 np_get_defaults(const char *locator, const char *default_section)
112 FILE *inifile = NULL;
113 np_arg_list *defaults = NULL;
114 np_ini_info i;
116 parse_locator(locator, default_section, &i);
117 if (strcmp(i.file, "-") == 0)
118 inifile = stdin;
119 else
120 inifile = fopen(i.file, "r");
122 if (inifile == NULL)
123 die(STATE_UNKNOWN, "%s\n", _("Can't read config file"));
124 if (read_defaults(inifile, i.stanza, &defaults) == FALSE)
125 die(STATE_UNKNOWN,
126 _("Invalid section '%s' in config file '%s'\n"), i.stanza,
127 i.file);
129 free(i.file);
130 if (inifile != stdin)
131 fclose(inifile);
132 free(i.stanza);
133 return defaults;
136 /* read_defaults is where the meat of the parsing takes place.
138 * note that this may be called by a setuid binary, so we need to
139 * be extra careful about user-supplied input (i.e. avoiding possible
140 * format string vulnerabilities, etc)
142 static int
143 read_defaults(FILE *f, const char *stanza, np_arg_list **opts)
145 int c, status = FALSE;
146 size_t i, stanza_len;
147 enum { NOSTANZA, WRONGSTANZA, RIGHTSTANZA } stanzastate = NOSTANZA;
149 stanza_len = strlen(stanza);
151 /* our little stanza-parsing state machine. */
152 while ((c = fgetc(f)) != EOF) {
153 /* gobble up leading whitespace */
154 if (isspace(c))
155 continue;
156 switch (c) {
157 /* globble up coment lines */
158 case ';':
159 case '#':
160 GOBBLE_TO(f, c, '\n');
161 break;
162 /* start of a stanza. check to see if it matches */
163 case '[':
164 stanzastate = WRONGSTANZA;
165 for (i = 0; i < stanza_len; i++) {
166 c = fgetc(f);
167 /* Strip leading whitespace */
168 if (i == 0)
169 for (c; isspace(c); c = fgetc(f))
170 continue;
171 /* nope, read to the end of the line */
172 if (c != stanza[i]) {
173 GOBBLE_TO(f, c, '\n');
174 break;
177 /* if it matched up to here and the next char is ']'... */
178 if (i == stanza_len) {
179 c = fgetc(f);
180 /* Strip trailing whitespace */
181 for (c; isspace(c); c = fgetc(f))
182 continue;
183 if (c == ']')
184 stanzastate = RIGHTSTANZA;
186 break;
187 /* otherwise, we're in the body of a stanza or a parse error */
188 default:
189 switch (stanzastate) {
190 /* we never found the start of the first stanza, so
191 * we're dealing with a config error
193 case NOSTANZA:
194 die(STATE_UNKNOWN, "%s\n",
195 _("Config file error"));
196 break;
197 /* we're in a stanza, but for a different plugin */
198 case WRONGSTANZA:
199 GOBBLE_TO(f, c, '\n');
200 break;
201 /* okay, this is where we start taking the config */
202 case RIGHTSTANZA:
203 ungetc(c, f);
204 if (add_option(f, opts)) {
205 die(STATE_UNKNOWN, "%s\n",
206 _("Config file error"));
208 status = TRUE;
209 break;
211 break;
214 return status;
218 * read one line of input in the format
219 * ^option[[:space:]]*(=[[:space:]]*value)?
220 * and creates it as a cmdline argument
221 * --option[=value]
222 * appending it to the linked list optbuf.
224 static int
225 add_option(FILE *f, np_arg_list **optlst)
227 np_arg_list *opttmp = *optlst, *optnew;
228 char *linebuf = NULL, *lineend = NULL, *optptr = NULL, *optend = NULL;
229 char *eqptr = NULL, *valptr = NULL, *spaceptr = NULL, *valend = NULL;
230 short done_reading = 0, equals = 0, value = 0;
231 size_t cfg_len = 0, read_sz = 8, linebuf_sz = 0, read_pos = 0;
232 size_t opt_len = 0, val_len = 0;
234 /* read one line from the file */
235 while (!done_reading) {
236 /* grow if necessary */
237 if (linebuf == NULL || read_pos + read_sz >= linebuf_sz) {
238 linebuf_sz = linebuf_sz > 0 ? linebuf_sz << 1 : read_sz;
239 linebuf = realloc(linebuf, linebuf_sz);
240 if (linebuf == NULL)
241 die(STATE_UNKNOWN, _("malloc() failed!\n"));
243 if (fgets(&linebuf[read_pos], read_sz, f) == NULL)
244 done_reading = 1;
245 else {
246 read_pos = strlen(linebuf);
247 if (linebuf[read_pos - 1] == '\n') {
248 linebuf[--read_pos] = '\0';
249 done_reading = 1;
253 lineend = &linebuf[read_pos];
254 /* all that to read one line. isn't C fun? :) now comes the parsing :/ */
256 /* skip leading whitespace */
257 for (optptr = linebuf; optptr < lineend && isspace(*optptr); optptr++)
258 continue;
259 /* continue to '=' or EOL, watching for spaces that might precede it */
260 for (eqptr = optptr; eqptr < lineend && *eqptr != '='; eqptr++) {
261 if (isspace(*eqptr) && optend == NULL)
262 optend = eqptr;
263 else
264 optend = NULL;
266 if (optend == NULL)
267 optend = eqptr;
268 --optend;
269 /* ^[[:space:]]*=foo is a syntax error */
270 if (optptr == eqptr)
271 die(STATE_UNKNOWN, "%s\n", _("Config file error"));
272 /* continue from '=' to start of value or EOL */
273 for (valptr = eqptr + 1; valptr < lineend && isspace(*valptr);
274 valptr++)
275 continue;
276 /* continue to the end of value */
277 for (valend = valptr; valend < lineend; valend++)
278 continue;
279 --valend;
280 /* Finally trim off trailing spaces */
281 for (valend; isspace(*valend); valend--)
282 continue;
283 /* calculate the length of "--foo" */
284 opt_len = 1 + optend - optptr;
285 /* 1-character params needs only one dash */
286 if (opt_len == 1)
287 cfg_len = 1 + (opt_len);
288 else
289 cfg_len = 2 + (opt_len);
290 /* if valptr<lineend then we have to also allocate space for "=bar" */
291 if (valptr < lineend) {
292 equals = value = 1;
293 val_len = 1 + valend - valptr;
294 cfg_len += 1 + val_len;
296 /* if valptr==valend then we have "=" but no "bar" */
297 else if (valptr == lineend) {
298 equals = 1;
299 cfg_len += 1;
301 /* A line with no equal sign isn't valid */
302 if (equals == 0)
303 die(STATE_UNKNOWN, "%s\n", _("Config file error"));
305 /* okay, now we have all the info we need, so we create a new np_arg_list
306 * element and set the argument...
308 optnew = malloc(sizeof(np_arg_list));
309 optnew->next = NULL;
311 read_pos = 0;
312 optnew->arg = malloc(cfg_len + 1);
313 /* 1-character params needs only one dash */
314 if (opt_len == 1) {
315 strncpy(&optnew->arg[read_pos], "-", 1);
316 read_pos += 1;
317 } else {
318 strncpy(&optnew->arg[read_pos], "--", 2);
319 read_pos += 2;
321 strncpy(&optnew->arg[read_pos], optptr, opt_len);
322 read_pos += opt_len;
323 if (value) {
324 optnew->arg[read_pos++] = '=';
325 strncpy(&optnew->arg[read_pos], valptr, val_len);
326 read_pos += val_len;
328 optnew->arg[read_pos] = '\0';
330 /* ...and put that to the end of the list */
331 if (*optlst == NULL)
332 *optlst = optnew;
333 else {
334 while (opttmp->next != NULL)
335 opttmp = opttmp->next;
336 opttmp->next = optnew;
339 free(linebuf);
340 return 0;
343 static char *
344 default_file_in_path(void)
346 char *config_path, **file;
347 char *dir, *ini_file, *tokens;
349 if ((config_path = getenv("NAGIOS_CONFIG_PATH")) == NULL)
350 return NULL;
352 if ((tokens = strdup(config_path)) == NULL)
353 die(STATE_UNKNOWN, _("Insufficient Memory"));
354 for (dir = strtok(tokens, ":"); dir != NULL; dir = strtok(NULL, ":")) {
355 for (file = default_ini_file_names; *file != NULL; file++) {
356 if ((asprintf(&ini_file, "%s/%s", dir, *file)) < 0)
357 die(STATE_UNKNOWN, _("Insufficient Memory"));
358 if (access(ini_file, F_OK) == 0) {
359 free(tokens);
360 return ini_file;
364 free(tokens);
365 return NULL;
368 static char *
369 default_file(void)
371 char **p, *ini_file;
373 if ((ini_file = getenv("MP_CONFIG_FILE")) != NULL ||
374 (ini_file = default_file_in_path()) != NULL)
375 return ini_file;
376 for (p = default_ini_path_names; *p != NULL; p++)
377 if (access(*p, F_OK) == 0)
378 return *p;
379 return NULL;