Re-apply "Cleanup; fix the way libraries are linked; Make-It-Simple(tm)"
[monitoring-plugins.git] / lib / parse_ini.c
blob1d64a5062512e098dcec5efc97b4b33e8afe99e6
1 /*****************************************************************************
2 *
3 * Nagios-plugins parse_ini library
4 *
5 * License: GPL
6 * Copyright (c) 2007 Nagios 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"
27 #include <ctype.h>
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <unistd.h>
33 /* TODO: die like N::P if config file is not found */
35 /* np_ini_info contains the result of parsing a "locator" in the format
36 * [stanza_name][@config_filename] (check_foo@/etc/foo.ini, for example)
38 typedef struct {
39 char *file;
40 char *stanza;
41 } np_ini_info;
43 /* eat all characters from a FILE pointer until n is encountered */
44 #define GOBBLE_TO(f, c, n) do { (c)=fgetc((f)); } while((c)!=EOF && (c)!=(n))
46 /* internal function that returns the constructed defaults options */
47 static int read_defaults(FILE *f, const char *stanza, np_arg_list **opts);
48 /* internal function that converts a single line into options format */
49 static int add_option(FILE *f, np_arg_list **optlst);
50 /* internal function to find default file */
51 static char* default_file(void);
52 /* internal function to stat() files */
53 static int test_file(const char* env, int len, const char* file, char* temp_file);
55 /* parse_locator decomposes a string of the form
56 * [stanza][@filename]
57 * into its seperate parts
59 static void parse_locator(const char *locator, const char *def_stanza, np_ini_info *i){
60 size_t locator_len=0, stanza_len=0;
62 /* if locator is NULL we'll use default values */
63 if(locator){
64 locator_len=strlen(locator);
65 stanza_len=strcspn(locator, "@");
67 /* if a non-default stanza is provided */
68 if(stanza_len>0){
69 i->stanza=(char*)malloc(sizeof(char)*(stanza_len+1));
70 strncpy(i->stanza, locator, stanza_len);
71 i->stanza[stanza_len]='\0';
72 } else { /* otherwise we use the default stanza */
73 i->stanza=strdup(def_stanza);
75 /* if there is no @file part */
76 if(stanza_len==locator_len){
77 i->file=default_file();
78 } else {
79 i->file=strdup(&(locator[stanza_len+1]));
82 if(i->file==NULL || i->stanza==NULL){
83 die(STATE_UNKNOWN, _("malloc() failed!\n"));
87 /* this is the externally visible function used by extra_opts */
88 np_arg_list* np_get_defaults(const char *locator, const char *default_section){
89 FILE *inifile=NULL;
90 np_arg_list *defaults=NULL;
91 np_ini_info i;
93 parse_locator(locator, default_section, &i);
94 /* if a file was specified or if we're using the default file */
95 if(i.file != NULL && strlen(i.file) > 0){
96 if(strcmp(i.file, "-")==0){
97 inifile=stdin;
98 } else {
99 inifile=fopen(i.file, "r");
101 if(inifile==NULL) die(STATE_UNKNOWN, _("Can't read config file"));
102 if(read_defaults(inifile, i.stanza, &defaults)==FALSE)
103 die(STATE_UNKNOWN, _("Invalid section '%s' in config file '%s'\n"), i.stanza, i.file);
105 free(i.file);
106 if(inifile!=stdin) fclose(inifile);
108 free(i.stanza);
109 return defaults;
112 /* read_defaults is where the meat of the parsing takes place.
114 * note that this may be called by a setuid binary, so we need to
115 * be extra careful about user-supplied input (i.e. avoiding possible
116 * format string vulnerabilities, etc)
118 static int read_defaults(FILE *f, const char *stanza, np_arg_list **opts){
119 int c, status=FALSE;
120 size_t i, stanza_len;
121 enum { NOSTANZA, WRONGSTANZA, RIGHTSTANZA } stanzastate=NOSTANZA;
123 stanza_len=strlen(stanza);
125 /* our little stanza-parsing state machine. */
126 while((c=fgetc(f))!=EOF){
127 /* gobble up leading whitespace */
128 if(isspace(c)) continue;
129 switch(c){
130 /* globble up coment lines */
131 case ';':
132 case '#':
133 GOBBLE_TO(f, c, '\n');
134 break;
135 /* start of a stanza. check to see if it matches */
136 case '[':
137 stanzastate=WRONGSTANZA;
138 for(i=0; i<stanza_len; i++){
139 c=fgetc(f);
140 /* Strip leading whitespace */
141 if(i==0) for(c; isspace(c); c=fgetc(f));
142 /* nope, read to the end of the line */
143 if(c!=stanza[i]) {
144 GOBBLE_TO(f, c, '\n');
145 break;
148 /* if it matched up to here and the next char is ']'... */
149 if(i==stanza_len){
150 c=fgetc(f);
151 /* Strip trailing whitespace */
152 for(c; isspace(c); c=fgetc(f));
153 if(c==']') stanzastate=RIGHTSTANZA;
155 break;
156 /* otherwise, we're in the body of a stanza or a parse error */
157 default:
158 switch(stanzastate){
159 /* we never found the start of the first stanza, so
160 * we're dealing with a config error
162 case NOSTANZA:
163 die(STATE_UNKNOWN, _("Config file error"));
164 break;
165 /* we're in a stanza, but for a different plugin */
166 case WRONGSTANZA:
167 GOBBLE_TO(f, c, '\n');
168 break;
169 /* okay, this is where we start taking the config */
170 case RIGHTSTANZA:
171 ungetc(c, f);
172 if(add_option(f, opts)){
173 die(STATE_UNKNOWN, _("Config file error"));
175 status=TRUE;
176 break;
178 break;
181 return status;
185 * read one line of input in the format
186 * ^option[[:space:]]*(=[[:space:]]*value)?
187 * and creates it as a cmdline argument
188 * --option[=value]
189 * appending it to the linked list optbuf.
191 static int add_option(FILE *f, np_arg_list **optlst){
192 np_arg_list *opttmp=*optlst, *optnew;
193 char *linebuf=NULL, *lineend=NULL, *optptr=NULL, *optend=NULL;
194 char *eqptr=NULL, *valptr=NULL, *spaceptr=NULL, *valend=NULL;
195 short done_reading=0, equals=0, value=0;
196 size_t cfg_len=0, read_sz=8, linebuf_sz=0, read_pos=0;
197 size_t opt_len=0, val_len=0;
199 /* read one line from the file */
200 while(!done_reading){
201 /* grow if necessary */
202 if(linebuf==NULL || read_pos+read_sz >= linebuf_sz){
203 linebuf_sz=(linebuf_sz>0)?linebuf_sz<<1:read_sz;
204 linebuf=realloc(linebuf, linebuf_sz);
205 if(linebuf==NULL) die(STATE_UNKNOWN, _("malloc() failed!\n"));
207 if(fgets(&linebuf[read_pos], read_sz, f)==NULL) done_reading=1;
208 else {
209 read_pos=strlen(linebuf);
210 if(linebuf[read_pos-1]=='\n') {
211 linebuf[--read_pos]='\0';
212 done_reading=1;
216 lineend=&linebuf[read_pos];
217 /* all that to read one line. isn't C fun? :) now comes the parsing :/ */
219 /* skip leading whitespace */
220 for(optptr=linebuf; optptr<lineend && isspace(*optptr); optptr++);
221 /* continue to '=' or EOL, watching for spaces that might precede it */
222 for(eqptr=optptr; eqptr<lineend && *eqptr!='='; eqptr++){
223 if(isspace(*eqptr) && optend==NULL) optend=eqptr;
224 else optend=NULL;
226 if(optend==NULL) optend=eqptr;
227 --optend;
228 /* ^[[:space:]]*=foo is a syntax error */
229 if(optptr==eqptr) die(STATE_UNKNOWN, _("Config file error\n"));
230 /* continue from '=' to start of value or EOL */
231 for(valptr=eqptr+1; valptr<lineend && isspace(*valptr); valptr++);
232 /* continue to the end of value */
233 for(valend=valptr; valend<lineend; valend++);
234 --valend;
235 /* Finally trim off trailing spaces */
236 for(valend; isspace(*valend); valend--);
237 /* calculate the length of "--foo" */
238 opt_len=1+optend-optptr;
239 /* 1-character params needs only one dash */
240 if(opt_len==1)
241 cfg_len=1+(opt_len);
242 else
243 cfg_len=2+(opt_len);
244 /* if valptr<lineend then we have to also allocate space for "=bar" */
245 if(valptr<lineend) {
246 equals=value=1;
247 val_len=1+valend-valptr;
248 cfg_len+=1+val_len;
250 /* if valptr==valend then we have "=" but no "bar" */
251 else if(valptr==lineend) {
252 equals=1;
253 cfg_len+=1;
255 /* A line with no equal sign isn't valid */
256 if(equals==0) die(STATE_UNKNOWN, _("Config file error\n"));
258 /* okay, now we have all the info we need, so we create a new np_arg_list
259 * element and set the argument...
261 optnew=(np_arg_list *)malloc(sizeof(np_arg_list));
262 optnew->next=NULL;
264 read_pos=0;
265 optnew->arg=(char *)malloc(cfg_len+1);
266 /* 1-character params needs only one dash */
267 if(opt_len==1) {
268 strncpy(&optnew->arg[read_pos], "-", 1);
269 read_pos+=1;
270 } else {
271 strncpy(&optnew->arg[read_pos], "--", 2);
272 read_pos+=2;
274 strncpy(&optnew->arg[read_pos], optptr, opt_len); read_pos+=opt_len;
275 if(value) {
276 optnew->arg[read_pos++]='=';
277 strncpy(&optnew->arg[read_pos], valptr, val_len); read_pos+=val_len;
279 optnew->arg[read_pos]='\0';
281 /* ...and put that to the end of the list */
282 if(*optlst==NULL) {
283 *optlst=optnew;
284 } else {
285 while(opttmp->next!=NULL) {
286 opttmp=opttmp->next;
288 opttmp->next = optnew;
291 free(linebuf);
292 return 0;
295 static char* default_file(void){
296 struct stat sb;
297 char *np_env=NULL, *default_file=NULL;
298 char temp_file[MAX_INPUT_BUFFER];
299 size_t len;
301 if((np_env=getenv("NAGIOS_CONFIG_PATH"))!=NULL) {
302 /* skip any starting colon... */
303 while(*np_env==':') np_env++;
304 /* Look for NP_DEFAULT_INI_FILENAME1 and NP_DEFAULT_INI_FILENAME2 in
305 * every PATHs defined (colon-separated).
307 while((len=strcspn(np_env,":"))>0){
308 /* Test NP_DEFAULT_INI_FILENAME[1-2] in current np_env token */
309 if(test_file(np_env,len,NP_DEFAULT_INI_FILENAME1,temp_file)==1 ||
310 test_file(np_env,len,NP_DEFAULT_INI_FILENAME2,temp_file)==1){
311 default_file=strdup(temp_file);
312 break;
315 /* Move on to the next token */
316 np_env+=len;
317 while(*np_env==':') np_env++;
318 } /* while(...) */
319 } /* if(getenv("NAGIOS_CONFIG_PATH")) */
321 /* Look for NP_DEFAULT_INI_FILENAME1 in NP_DEFAULT_INI_NAGIOS_PATH[1-4] */
322 if(!default_file){
323 if(test_file(NP_DEFAULT_INI_NAGIOS_PATH1,strlen(NP_DEFAULT_INI_NAGIOS_PATH1),NP_DEFAULT_INI_FILENAME1,temp_file)==1 ||
324 test_file(NP_DEFAULT_INI_NAGIOS_PATH2,strlen(NP_DEFAULT_INI_NAGIOS_PATH2),NP_DEFAULT_INI_FILENAME1,temp_file)==1 ||
325 test_file(NP_DEFAULT_INI_NAGIOS_PATH3,strlen(NP_DEFAULT_INI_NAGIOS_PATH3),NP_DEFAULT_INI_FILENAME1,temp_file)==1 ||
326 test_file(NP_DEFAULT_INI_NAGIOS_PATH4,strlen(NP_DEFAULT_INI_NAGIOS_PATH4),NP_DEFAULT_INI_FILENAME1,temp_file)==1)
327 default_file=strdup(temp_file);
330 /* Look for NP_DEFAULT_INI_FILENAME2 in NP_DEFAULT_INI_PATH[1-3] */
331 if(!default_file){
332 if(test_file(NP_DEFAULT_INI_PATH1,strlen(NP_DEFAULT_INI_PATH1),NP_DEFAULT_INI_FILENAME2,temp_file)==1 ||
333 test_file(NP_DEFAULT_INI_PATH2,strlen(NP_DEFAULT_INI_PATH2),NP_DEFAULT_INI_FILENAME2,temp_file)==1 ||
334 test_file(NP_DEFAULT_INI_PATH3,strlen(NP_DEFAULT_INI_PATH3),NP_DEFAULT_INI_FILENAME2,temp_file)==1)
335 default_file=strdup(temp_file);
338 /* Return default_file or empty string (should return NULL if we want plugins
339 * to die there)...
341 if(default_file)
342 return default_file;
343 return "";
346 /* put together len bytes from env and the filename and test for its
347 * existence. Returns 1 if found, 0 if not and -1 if test wasn't performed.
349 static int test_file(const char* env, int len, const char* file, char* temp_file){
350 struct stat sb;
352 /* test if len + filelen + '/' + '\0' fits in temp_file */
353 if((len+strlen(file)+2)>MAX_INPUT_BUFFER) return -1;
355 strncpy(temp_file,env,len);
356 temp_file[len]='\0';
357 strncat(temp_file,"/",len+1);
358 strncat(temp_file,file,len+strlen(file)+1);
360 if(stat(temp_file, &sb) != -1) return 1;
361 return 0;