Back to index

nagios-plugins  1.4.16
parse_ini.c
Go to the documentation of this file.
00001 /*****************************************************************************
00002 * 
00003 * Nagios-plugins parse_ini library
00004 * 
00005 * License: GPL
00006 * Copyright (c) 2007 Nagios Plugins Development Team
00007 * 
00008 * This program is free software: you can redistribute it and/or modify
00009 * it under the terms of the GNU General Public License as published by
00010 * the Free Software Foundation, either version 3 of the License, or
00011 * (at your option) any later version.
00012 * 
00013 * This program is distributed in the hope that it will be useful,
00014 * but WITHOUT ANY WARRANTY; without even the implied warranty of
00015 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00016 * GNU General Public License for more details.
00017 * 
00018 * You should have received a copy of the GNU General Public License
00019 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
00020 * 
00021 * 
00022 *****************************************************************************/
00023 
00024 #include "common.h"
00025 #include "utils_base.h"
00026 #include "parse_ini.h"
00027 #include <ctype.h>
00028 
00029 #include <sys/types.h>
00030 #include <sys/stat.h>
00031 #include <unistd.h>
00032 
00033 /* TODO: die like N::P if config file is not found */
00034 
00035 /* np_ini_info contains the result of parsing a "locator" in the format
00036  * [stanza_name][@config_filename] (check_foo@/etc/foo.ini, for example)
00037  */
00038 typedef struct {
00039        char *file;
00040        char *stanza;
00041 } np_ini_info;
00042 
00043 /* eat all characters from a FILE pointer until n is encountered */
00044 #define GOBBLE_TO(f, c, n) do { (c)=fgetc((f)); } while((c)!=EOF && (c)!=(n))
00045 
00046 /* internal function that returns the constructed defaults options */
00047 static int read_defaults(FILE *f, const char *stanza, np_arg_list **opts);
00048 /* internal function that converts a single line into options format */
00049 static int add_option(FILE *f, np_arg_list **optlst);
00050 /* internal function to find default file */
00051 static char* default_file(void);
00052 /* internal function to stat() files */
00053 static int test_file(const char* env, int len, const char* file, char* temp_file);
00054 
00055 /* parse_locator decomposes a string of the form
00056  *     [stanza][@filename]
00057  * into its seperate parts
00058  */
00059 static void parse_locator(const char *locator, const char *def_stanza, np_ini_info *i){
00060        size_t locator_len=0, stanza_len=0;
00061 
00062        /* if locator is NULL we'll use default values */
00063        if(locator){
00064               locator_len=strlen(locator);
00065               stanza_len=strcspn(locator, "@");
00066        }
00067        /* if a non-default stanza is provided */
00068        if(stanza_len>0){
00069               i->stanza=(char*)malloc(sizeof(char)*(stanza_len+1));
00070               strncpy(i->stanza, locator, stanza_len);
00071               i->stanza[stanza_len]='\0';
00072        } else { /* otherwise we use the default stanza */
00073               i->stanza=strdup(def_stanza);
00074        }
00075        /* if there is no @file part */
00076        if(stanza_len==locator_len){
00077               i->file=default_file();
00078               if(strcmp(i->file, "") == 0){
00079                      die(STATE_UNKNOWN, _("Cannot find '%s' or '%s' in any standard location.\n"), NP_DEFAULT_INI_FILENAME1, NP_DEFAULT_INI_FILENAME2);
00080               }
00081        } else {
00082               i->file=strdup(&(locator[stanza_len+1]));
00083        }
00084 
00085        if(i->file==NULL || i->stanza==NULL){
00086               die(STATE_UNKNOWN, _("malloc() failed!\n"));
00087        }
00088 }
00089 
00090 /* this is the externally visible function used by extra_opts */
00091 np_arg_list* np_get_defaults(const char *locator, const char *default_section){
00092        FILE *inifile=NULL;
00093        np_arg_list *defaults=NULL;
00094        np_ini_info i;
00095 
00096        parse_locator(locator, default_section, &i);
00097        /* if a file was specified or if we're using the default file */
00098        if(i.file != NULL && strlen(i.file) > 0){
00099               if(strcmp(i.file, "-")==0){
00100                      inifile=stdin;
00101               } else {
00102                      inifile=fopen(i.file, "r");
00103               }
00104               if(inifile==NULL) die(STATE_UNKNOWN, _("Can't read config file"));
00105               if(read_defaults(inifile, i.stanza, &defaults)==FALSE)
00106                      die(STATE_UNKNOWN, _("Invalid section '%s' in config file '%s'\n"), i.stanza, i.file);
00107 
00108               free(i.file);
00109               if(inifile!=stdin) fclose(inifile);
00110        }
00111        free(i.stanza);
00112        return defaults;
00113 }
00114 
00115 /* read_defaults is where the meat of the parsing takes place.
00116  *
00117  * note that this may be called by a setuid binary, so we need to
00118  * be extra careful about user-supplied input (i.e. avoiding possible
00119  * format string vulnerabilities, etc)
00120  */
00121 static int read_defaults(FILE *f, const char *stanza, np_arg_list **opts){
00122        int c, status=FALSE;
00123        size_t i, stanza_len;
00124        enum { NOSTANZA, WRONGSTANZA, RIGHTSTANZA } stanzastate=NOSTANZA;
00125 
00126        stanza_len=strlen(stanza);
00127 
00128        /* our little stanza-parsing state machine.  */
00129        while((c=fgetc(f))!=EOF){
00130               /* gobble up leading whitespace */
00131               if(isspace(c)) continue;
00132               switch(c){
00133                      /* globble up coment lines */
00134                      case ';':
00135                      case '#':
00136                             GOBBLE_TO(f, c, '\n');
00137                             break;
00138                      /* start of a stanza.  check to see if it matches */
00139                      case '[':
00140                             stanzastate=WRONGSTANZA;
00141                             for(i=0; i<stanza_len; i++){
00142                                    c=fgetc(f);
00143                                    /* Strip leading whitespace */
00144                                    if(i==0) for(c; isspace(c); c=fgetc(f));
00145                                    /* nope, read to the end of the line */
00146                                    if(c!=stanza[i]) {
00147                                           GOBBLE_TO(f, c, '\n');
00148                                           break;
00149                                    }
00150                             }
00151                             /* if it matched up to here and the next char is ']'... */
00152                             if(i==stanza_len){
00153                                    c=fgetc(f);
00154                                    /* Strip trailing whitespace */
00155                                    for(c; isspace(c); c=fgetc(f));
00156                                    if(c==']') stanzastate=RIGHTSTANZA;
00157                             }
00158                             break;
00159                      /* otherwise, we're in the body of a stanza or a parse error */
00160                      default:
00161                             switch(stanzastate){
00162                                    /* we never found the start of the first stanza, so
00163                                     * we're dealing with a config error
00164                                     */
00165                                    case NOSTANZA:
00166                                           die(STATE_UNKNOWN, _("Config file error"));
00167                                           break;
00168                                    /* we're in a stanza, but for a different plugin */
00169                                    case WRONGSTANZA:
00170                                           GOBBLE_TO(f, c, '\n');
00171                                           break;
00172                                    /* okay, this is where we start taking the config */
00173                                    case RIGHTSTANZA:
00174                                           ungetc(c, f);
00175                                           if(add_option(f, opts)){
00176                                                  die(STATE_UNKNOWN, _("Config file error"));
00177                                           }
00178                                           status=TRUE;
00179                                           break;
00180                             }
00181                             break;
00182               }
00183        }
00184        return status;
00185 }
00186 
00187 /*
00188  * read one line of input in the format
00189  *     ^option[[:space:]]*(=[[:space:]]*value)?
00190  * and creates it as a cmdline argument
00191  *     --option[=value]
00192  * appending it to the linked list optbuf.
00193  */
00194 static int add_option(FILE *f, np_arg_list **optlst){
00195        np_arg_list *opttmp=*optlst, *optnew;
00196        char *linebuf=NULL, *lineend=NULL, *optptr=NULL, *optend=NULL;
00197        char *eqptr=NULL, *valptr=NULL, *spaceptr=NULL, *valend=NULL;
00198        short done_reading=0, equals=0, value=0;
00199        size_t cfg_len=0, read_sz=8, linebuf_sz=0, read_pos=0;
00200        size_t opt_len=0, val_len=0;
00201 
00202        /* read one line from the file */
00203        while(!done_reading){
00204               /* grow if necessary */
00205               if(linebuf==NULL || read_pos+read_sz >= linebuf_sz){
00206                      linebuf_sz=(linebuf_sz>0)?linebuf_sz<<1:read_sz;
00207                      linebuf=realloc(linebuf, linebuf_sz);
00208                      if(linebuf==NULL) die(STATE_UNKNOWN, _("malloc() failed!\n"));
00209               }
00210               if(fgets(&linebuf[read_pos], read_sz, f)==NULL) done_reading=1;
00211               else {
00212                      read_pos=strlen(linebuf);
00213                      if(linebuf[read_pos-1]=='\n') {
00214                             linebuf[--read_pos]='\0';
00215                             done_reading=1;
00216                      }
00217               }
00218        }
00219        lineend=&linebuf[read_pos];
00220        /* all that to read one line.  isn't C fun? :) now comes the parsing :/ */
00221 
00222        /* skip leading whitespace */
00223        for(optptr=linebuf; optptr<lineend && isspace(*optptr); optptr++);
00224        /* continue to '=' or EOL, watching for spaces that might precede it */
00225        for(eqptr=optptr; eqptr<lineend && *eqptr!='='; eqptr++){
00226               if(isspace(*eqptr) && optend==NULL) optend=eqptr;
00227               else optend=NULL;
00228        }
00229        if(optend==NULL) optend=eqptr;
00230        --optend;
00231        /* ^[[:space:]]*=foo is a syntax error */
00232        if(optptr==eqptr) die(STATE_UNKNOWN, _("Config file error\n"));
00233        /* continue from '=' to start of value or EOL */
00234        for(valptr=eqptr+1; valptr<lineend && isspace(*valptr); valptr++);
00235        /* continue to the end of value */
00236        for(valend=valptr; valend<lineend; valend++);
00237        --valend;
00238        /* Finally trim off trailing spaces */
00239        for(valend; isspace(*valend); valend--);
00240        /* calculate the length of "--foo" */
00241        opt_len=1+optend-optptr;
00242        /* 1-character params needs only one dash */
00243        if(opt_len==1)
00244               cfg_len=1+(opt_len);
00245        else
00246               cfg_len=2+(opt_len);
00247        /* if valptr<lineend then we have to also allocate space for "=bar" */
00248        if(valptr<lineend) {
00249               equals=value=1;
00250               val_len=1+valend-valptr;
00251               cfg_len+=1+val_len;
00252        }
00253        /* if valptr==valend then we have "=" but no "bar" */
00254        else if(valptr==lineend) {
00255               equals=1;
00256               cfg_len+=1;
00257        }
00258        /* A line with no equal sign isn't valid */
00259        if(equals==0) die(STATE_UNKNOWN, _("Config file error\n"));
00260 
00261        /* okay, now we have all the info we need, so we create a new np_arg_list
00262         * element and set the argument...
00263         */
00264        optnew=(np_arg_list *)malloc(sizeof(np_arg_list));
00265        optnew->next=NULL;
00266 
00267        read_pos=0;
00268        optnew->arg=(char *)malloc(cfg_len+1);
00269        /* 1-character params needs only one dash */
00270        if(opt_len==1) {
00271               strncpy(&optnew->arg[read_pos], "-", 1);
00272               read_pos+=1;
00273        } else {
00274               strncpy(&optnew->arg[read_pos], "--", 2);
00275               read_pos+=2;
00276        }
00277        strncpy(&optnew->arg[read_pos], optptr, opt_len); read_pos+=opt_len;
00278        if(value) {
00279               optnew->arg[read_pos++]='=';
00280               strncpy(&optnew->arg[read_pos], valptr, val_len); read_pos+=val_len;
00281        }
00282        optnew->arg[read_pos]='\0';
00283 
00284        /* ...and put that to the end of the list */
00285        if(*optlst==NULL) {
00286               *optlst=optnew;
00287        }      else {
00288               while(opttmp->next!=NULL) {
00289                      opttmp=opttmp->next;
00290               }
00291               opttmp->next = optnew;
00292        }
00293 
00294        free(linebuf);
00295        return 0;
00296 }
00297 
00298 static char* default_file(void){
00299        struct stat sb;
00300        char *np_env=NULL, *default_file=NULL;
00301        char temp_file[MAX_INPUT_BUFFER];
00302        size_t len;
00303 
00304        if((np_env=getenv("NAGIOS_CONFIG_PATH"))!=NULL) {
00305               /* skip any starting colon... */
00306               while(*np_env==':') np_env++;
00307               /* Look for NP_DEFAULT_INI_FILENAME1 and NP_DEFAULT_INI_FILENAME2 in
00308                * every PATHs defined (colon-separated).
00309                */
00310               while((len=strcspn(np_env,":"))>0){
00311                      /* Test NP_DEFAULT_INI_FILENAME[1-2] in current np_env token */
00312                      if(test_file(np_env,len,NP_DEFAULT_INI_FILENAME1,temp_file)==1 ||
00313                         test_file(np_env,len,NP_DEFAULT_INI_FILENAME2,temp_file)==1){
00314                             default_file=strdup(temp_file);
00315                             break;
00316                      }
00317 
00318                      /* Move on to the next token */
00319                      np_env+=len;
00320                      while(*np_env==':') np_env++;
00321               } /* while(...) */
00322        } /* if(getenv("NAGIOS_CONFIG_PATH")) */
00323 
00324        /* Look for NP_DEFAULT_INI_FILENAME1 in NP_DEFAULT_INI_NAGIOS_PATH[1-4] */
00325        if(!default_file){
00326               if(test_file(NP_DEFAULT_INI_NAGIOS_PATH1,strlen(NP_DEFAULT_INI_NAGIOS_PATH1),NP_DEFAULT_INI_FILENAME1,temp_file)==1 ||
00327                  test_file(NP_DEFAULT_INI_NAGIOS_PATH2,strlen(NP_DEFAULT_INI_NAGIOS_PATH2),NP_DEFAULT_INI_FILENAME1,temp_file)==1 ||
00328                  test_file(NP_DEFAULT_INI_NAGIOS_PATH3,strlen(NP_DEFAULT_INI_NAGIOS_PATH3),NP_DEFAULT_INI_FILENAME1,temp_file)==1 ||
00329                  test_file(NP_DEFAULT_INI_NAGIOS_PATH4,strlen(NP_DEFAULT_INI_NAGIOS_PATH4),NP_DEFAULT_INI_FILENAME1,temp_file)==1)
00330                      default_file=strdup(temp_file);
00331        }
00332 
00333        /* Look for NP_DEFAULT_INI_FILENAME2 in NP_DEFAULT_INI_PATH[1-3] */
00334        if(!default_file){
00335               if(test_file(NP_DEFAULT_INI_PATH1,strlen(NP_DEFAULT_INI_PATH1),NP_DEFAULT_INI_FILENAME2,temp_file)==1 ||
00336                  test_file(NP_DEFAULT_INI_PATH2,strlen(NP_DEFAULT_INI_PATH2),NP_DEFAULT_INI_FILENAME2,temp_file)==1 ||
00337                  test_file(NP_DEFAULT_INI_PATH3,strlen(NP_DEFAULT_INI_PATH3),NP_DEFAULT_INI_FILENAME2,temp_file)==1)
00338                      default_file=strdup(temp_file);
00339        }
00340 
00341        /* Return default_file or empty string (should return NULL if we want plugins
00342         * to die there)...
00343         */
00344        if(default_file)
00345               return default_file;
00346        return "";
00347 }
00348 
00349 /* put together len bytes from env and the filename and test for its
00350  * existence. Returns 1 if found, 0 if not and -1 if test wasn't performed.
00351  */
00352 static int test_file(const char* env, int len, const char* file, char* temp_file){
00353        struct stat sb;
00354 
00355        /* test if len + filelen + '/' + '\0' fits in temp_file */
00356        if((len+strlen(file)+2)>MAX_INPUT_BUFFER) return -1;
00357 
00358        strncpy(temp_file,env,len);
00359        temp_file[len]='\0';
00360        strncat(temp_file,"/",len+1);
00361        strncat(temp_file,file,len+strlen(file)+1);
00362 
00363        if(stat(temp_file, &sb) != -1) return 1;
00364        return 0;
00365 }
00366