Code

check_disk: rerpopulate the mount list after doing a stat() on paths specified with...
[nagiosplug.git] / lib / parse_ini.c
1 /*****************************************************************************
2
3 * Nagios-plugins parse_ini library
4
5 * License: GPL
6 * Copyright (c) 2007 Nagios Plugins Development Team
7
8 * Last Modified: $Date$
9
10
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
15
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 * GNU General Public License for more details.
20
21 * You should have received a copy of the GNU General Public License
22 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
23
24 * $Id$
25
26 *****************************************************************************/
28 #include "common.h"
29 #include "utils_base.h"
30 #include "parse_ini.h"
31 #include <ctype.h>
33 #include <sys/types.h>
34 #include <sys/stat.h>
35 #include <unistd.h>
37 /* TODO: die like N::P if config file is not found */
39 /* np_ini_info contains the result of parsing a "locator" in the format
40  * [stanza_name][@config_filename] (check_foo@/etc/foo.ini, for example)
41  */
42 typedef struct {
43         char *file;
44         char *stanza;
45 } np_ini_info;
47 /* eat all characters from a FILE pointer until n is encountered */
48 #define GOBBLE_TO(f, c, n) do { (c)=fgetc((f)); } while((c)!=EOF && (c)!=(n))
50 /* internal function that returns the constructed defaults options */
51 static int read_defaults(FILE *f, const char *stanza, np_arg_list **opts);
52 /* internal function that converts a single line into options format */
53 static int add_option(FILE *f, np_arg_list **optlst);
54 /* internal function to find default file */
55 static char* default_file(void);
56 /* internal function to stat() files */
57 static int test_file(const char* env, int len, const char* file, char* temp_file);
59 /* parse_locator decomposes a string of the form
60  *      [stanza][@filename]
61  * into its seperate parts
62  */
63 static void parse_locator(const char *locator, const char *def_stanza, np_ini_info *i){
64         size_t locator_len=0, stanza_len=0;
66         /* if locator is NULL we'll use default values */
67         if(locator){
68                 locator_len=strlen(locator);
69                 stanza_len=strcspn(locator, "@");
70         }
71         /* if a non-default stanza is provided */
72         if(stanza_len>0){
73                 i->stanza=(char*)malloc(sizeof(char)*(stanza_len+1));
74                 strncpy(i->stanza, locator, stanza_len);
75                 i->stanza[stanza_len]='\0';
76         } else { /* otherwise we use the default stanza */
77                 i->stanza=strdup(def_stanza);
78         }
79         /* if there is no @file part */
80         if(stanza_len==locator_len){
81                 i->file=default_file();
82         } else {
83                 i->file=strdup(&(locator[stanza_len+1]));
84         }
85         
86         if(i->file==NULL || i->stanza==NULL){
87                 die(STATE_UNKNOWN, _("malloc() failed!\n"));
88         }
89 }
91 /* this is the externally visible function used by extra_opts */
92 np_arg_list* np_get_defaults(const char *locator, const char *default_section){
93         FILE *inifile=NULL;
94         np_arg_list *defaults=NULL;
95         np_ini_info i;
97         parse_locator(locator, default_section, &i);
98         /* if a file was specified or if we're using the default file */
99         if(i.file != NULL && strlen(i.file) > 0){
100                 if(strcmp(i.file, "-")==0){
101                         inifile=stdin;
102                 } else {
103                         inifile=fopen(i.file, "r");
104                 }
105                 if(inifile==NULL) die(STATE_UNKNOWN, _("Can't read config file"));
106                 if(read_defaults(inifile, i.stanza, &defaults)==FALSE)
107                         die(STATE_UNKNOWN, _("Invalid section '%s' in config file '%s'\n"), i.stanza, i.file);
109                 free(i.file);
110                 if(inifile!=stdin) fclose(inifile);
111         }
112         free(i.stanza);
113         return defaults;        
116 /* read_defaults is where the meat of the parsing takes place.
117  *
118  * note that this may be called by a setuid binary, so we need to
119  * be extra careful about user-supplied input (i.e. avoiding possible
120  * format string vulnerabilities, etc)
121  */
122 static int read_defaults(FILE *f, const char *stanza, np_arg_list **opts){
123         int c, status=FALSE;
124         size_t i, stanza_len;
125         enum { NOSTANZA, WRONGSTANZA, RIGHTSTANZA } stanzastate=NOSTANZA;
127         stanza_len=strlen(stanza);
129         /* our little stanza-parsing state machine.  */
130         while((c=fgetc(f))!=EOF){
131                 /* gobble up leading whitespace */
132                 if(isspace(c)) continue;
133                 switch(c){
134                         /* globble up coment lines */
135                         case ';':
136                         case '#':
137                                 GOBBLE_TO(f, c, '\n');
138                                 break;
139                         /* start of a stanza.  check to see if it matches */
140                         case '[':
141                                 stanzastate=WRONGSTANZA;
142                                 for(i=0; i<stanza_len; i++){
143                                         c=fgetc(f);
144                                         /* Strip leading whitespace */
145                                         if(i==0) for(c; isspace(c); c=fgetc(f));
146                                         /* nope, read to the end of the line */
147                                         if(c!=stanza[i]) {
148                                                 GOBBLE_TO(f, c, '\n');
149                                                 break;
150                                         }
151                                 }
152                                 /* if it matched up to here and the next char is ']'... */
153                                 if(i==stanza_len){
154                                         c=fgetc(f);
155                                         /* Strip trailing whitespace */
156                                         for(c; isspace(c); c=fgetc(f));
157                                         if(c==']') stanzastate=RIGHTSTANZA;
158                                 }
159                                 break;
160                         /* otherwise, we're in the body of a stanza or a parse error */
161                         default:
162                                 switch(stanzastate){
163                                         /* we never found the start of the first stanza, so
164                                          * we're dealing with a config error 
165                                          */
166                                         case NOSTANZA:
167                                                 die(STATE_UNKNOWN, _("Config file error"));
168                                                 break;
169                                         /* we're in a stanza, but for a different plugin */
170                                         case WRONGSTANZA:
171                                                 GOBBLE_TO(f, c, '\n');
172                                                 break;
173                                         /* okay, this is where we start taking the config */
174                                         case RIGHTSTANZA:
175                                                 ungetc(c, f);
176                                                 if(add_option(f, opts)){
177                                                         die(STATE_UNKNOWN, _("Config file error"));
178                                                 }
179                                                 status=TRUE;
180                                                 break;
181                                 }
182                                 break;
183                 }
184         }
185         return status;
188 /*
189  * read one line of input in the format
190  *      ^option[[:space:]]*(=[[:space:]]*value)?
191  * and creates it as a cmdline argument
192  *      --option[=value]
193  * appending it to the linked list optbuf.
194  */
195 static int add_option(FILE *f, np_arg_list **optlst){
196         np_arg_list *opttmp=*optlst, *optnew;
197         char *linebuf=NULL, *lineend=NULL, *optptr=NULL, *optend=NULL;
198         char *eqptr=NULL, *valptr=NULL, *spaceptr=NULL, *valend=NULL;
199         short done_reading=0, equals=0, value=0;
200         size_t cfg_len=0, read_sz=8, linebuf_sz=0, read_pos=0;
201         size_t opt_len=0, val_len=0;
203         /* read one line from the file */
204         while(!done_reading){
205                 /* grow if necessary */
206                 if(linebuf==NULL || read_pos+read_sz >= linebuf_sz){
207                         linebuf_sz=(linebuf_sz>0)?linebuf_sz<<1:read_sz;
208                         linebuf=realloc(linebuf, linebuf_sz);
209                         if(linebuf==NULL) die(STATE_UNKNOWN, _("malloc() failed!\n"));
210                 }
211                 if(fgets(&linebuf[read_pos], read_sz, f)==NULL) done_reading=1;
212                 else {
213                         read_pos=strlen(linebuf);
214                         if(linebuf[read_pos-1]=='\n') {
215                                 linebuf[--read_pos]='\0';
216                                 done_reading=1;
217                         }
218                 }
219         }
220         lineend=&linebuf[read_pos];
221         /* all that to read one line.  isn't C fun? :) now comes the parsing :/ */
223         /* skip leading whitespace */
224         for(optptr=linebuf; optptr<lineend && isspace(*optptr); optptr++);
225         /* continue to '=' or EOL, watching for spaces that might precede it */
226         for(eqptr=optptr; eqptr<lineend && *eqptr!='='; eqptr++){
227                 if(isspace(*eqptr) && optend==NULL) optend=eqptr;
228                 else optend=NULL;
229         }
230         if(optend==NULL) optend=eqptr;
231         --optend;
232         /* ^[[:space:]]*=foo is a syntax error */
233         if(optptr==eqptr) die(STATE_UNKNOWN, _("Config file error\n"));
234         /* continue from '=' to start of value or EOL */
235         for(valptr=eqptr+1; valptr<lineend && isspace(*valptr); valptr++);
236         /* continue to the end of value */
237         for(valend=valptr; valend<lineend; valend++);
238         --valend;
239         /* Finally trim off trailing spaces */
240         for(valend; isspace(*valend); valend--);
241         /* calculate the length of "--foo" */
242         opt_len=1+optend-optptr;
243         /* 1-character params needs only one dash */
244         if(opt_len==1)
245                 cfg_len=1+(opt_len);
246         else
247                 cfg_len=2+(opt_len);
248         /* if valptr<lineend then we have to also allocate space for "=bar" */
249         if(valptr<lineend) {
250                 equals=value=1;
251                 val_len=1+valend-valptr;
252                 cfg_len+=1+val_len;
253         }
254         /* if valptr==valend then we have "=" but no "bar" */
255         else if(valptr==lineend) {
256                 equals=1;
257                 cfg_len+=1;
258         }
259         /* A line with no equal sign isn't valid */
260         if(equals==0) die(STATE_UNKNOWN, _("Config file error\n"));
262         /* okay, now we have all the info we need, so we create a new np_arg_list
263          * element and set the argument...
264          */
265         optnew=(np_arg_list *)malloc(sizeof(np_arg_list));
266         optnew->next=NULL;
268         read_pos=0;
269         optnew->arg=(char *)malloc(cfg_len+1);
270         /* 1-character params needs only one dash */
271         if(opt_len==1) {
272                 strncpy(&optnew->arg[read_pos], "-", 1);
273                 read_pos+=1;
274         } else {
275                 strncpy(&optnew->arg[read_pos], "--", 2);
276                 read_pos+=2;
277         }
278         strncpy(&optnew->arg[read_pos], optptr, opt_len); read_pos+=opt_len;
279         if(value) {
280                 optnew->arg[read_pos++]='=';
281                 strncpy(&optnew->arg[read_pos], valptr, val_len); read_pos+=val_len;
282         }
283         optnew->arg[read_pos]='\0';
285         /* ...and put that to the end of the list */
286         if(*optlst==NULL) {
287                 *optlst=optnew;
288         }       else {
289                 while(opttmp->next!=NULL) {
290                         opttmp=opttmp->next;
291                 }
292                 opttmp->next = optnew;
293         }
295         free(linebuf);
296         return 0;
299 static char* default_file(void){
300         struct stat sb;
301         char *np_env=NULL, *default_file=NULL;
302         char temp_file[MAX_INPUT_BUFFER];
303         size_t len;
305         if((np_env=getenv("NAGIOS_CONFIG_PATH"))!=NULL) {
306                 /* skip any starting colon... */
307                 while(*np_env==':') np_env++;
308                 /* Look for NP_DEFAULT_INI_FILENAME1 and NP_DEFAULT_INI_FILENAME2 in
309                  * every PATHs defined (colon-separated).
310                  */
311                 while((len=strcspn(np_env,":"))>0){
312                         /* Test NP_DEFAULT_INI_FILENAME[1-2] in current np_env token */
313                         if(test_file(np_env,len,NP_DEFAULT_INI_FILENAME1,temp_file)==1 ||
314                            test_file(np_env,len,NP_DEFAULT_INI_FILENAME2,temp_file)==1){
315                                 default_file=strdup(temp_file);
316                                 break;
317                         }
319                         /* Move on to the next token */
320                         np_env+=len;
321                         while(*np_env==':') np_env++;
322                 } /* while(...) */
323         } /* if(getenv("NAGIOS_CONFIG_PATH")) */
325         /* Look for NP_DEFAULT_INI_FILENAME1 in NP_DEFAULT_INI_NAGIOS_PATH[1-4] */
326         if(!default_file){
327                 if(test_file(NP_DEFAULT_INI_NAGIOS_PATH1,strlen(NP_DEFAULT_INI_NAGIOS_PATH1),NP_DEFAULT_INI_FILENAME1,temp_file)==1 ||
328                    test_file(NP_DEFAULT_INI_NAGIOS_PATH2,strlen(NP_DEFAULT_INI_NAGIOS_PATH2),NP_DEFAULT_INI_FILENAME1,temp_file)==1 ||
329                    test_file(NP_DEFAULT_INI_NAGIOS_PATH3,strlen(NP_DEFAULT_INI_NAGIOS_PATH3),NP_DEFAULT_INI_FILENAME1,temp_file)==1 ||
330                    test_file(NP_DEFAULT_INI_NAGIOS_PATH4,strlen(NP_DEFAULT_INI_NAGIOS_PATH4),NP_DEFAULT_INI_FILENAME1,temp_file)==1)
331                         default_file=strdup(temp_file);
332         }
334         /* Look for NP_DEFAULT_INI_FILENAME2 in NP_DEFAULT_INI_PATH[1-3] */
335         if(!default_file){
336                 if(test_file(NP_DEFAULT_INI_PATH1,strlen(NP_DEFAULT_INI_PATH1),NP_DEFAULT_INI_FILENAME2,temp_file)==1 ||
337                    test_file(NP_DEFAULT_INI_PATH2,strlen(NP_DEFAULT_INI_PATH2),NP_DEFAULT_INI_FILENAME2,temp_file)==1 ||
338                    test_file(NP_DEFAULT_INI_PATH3,strlen(NP_DEFAULT_INI_PATH3),NP_DEFAULT_INI_FILENAME2,temp_file)==1)
339                         default_file=strdup(temp_file);
340         }
342         /* Return default_file or empty string (should return NULL if we want plugins
343          * to die there)...
344          */
345         if(default_file)
346                 return default_file;
347         return "";
350 /* put together len bytes from env and the filename and test for its
351  * existence. Returns 1 if found, 0 if not and -1 if test wasn't performed.
352  */
353 static int test_file(const char* env, int len, const char* file, char* temp_file){
354         struct stat sb;
356         /* test if len + filelen + '/' + '\0' fits in temp_file */
357         if((len+strlen(file)+2)>MAX_INPUT_BUFFER)       return -1;
359         strncpy(temp_file,env,len);
360         temp_file[len]='\0';
361         strncat(temp_file,"/",len+1);
362         strncat(temp_file,file,len+strlen(file)+1);
364         if(stat(temp_file, &sb) != -1) return 1;
365         return 0;