parse_ini.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. /*****************************************************************************
  2. *
  3. * Nagios-plugins parse_ini library
  4. *
  5. * License: GPL
  6. * Copyright (c) 2007-2014 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.
  12. *
  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.
  17. *
  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/>.
  20. *
  21. *
  22. *****************************************************************************/
  23. #include "common.h"
  24. #include "utils_base.h"
  25. #include "parse_ini.h"
  26. #include <ctype.h>
  27. #include <sys/types.h>
  28. #include <sys/stat.h>
  29. #include <unistd.h>
  30. /* TODO: die like N::P if config file is not found */
  31. /* np_ini_info contains the result of parsing a "locator" in the format
  32. * [stanza_name][@config_filename] (check_foo@/etc/foo.ini, for example)
  33. */
  34. typedef struct {
  35. char *file;
  36. char *stanza;
  37. } np_ini_info;
  38. /* eat all characters from a FILE pointer until n is encountered */
  39. #define GOBBLE_TO(f, c, n) do { (c)=fgetc((f)); } while((c)!=EOF && (c)!=(n))
  40. /* internal function that returns the constructed defaults options */
  41. static int read_defaults(FILE *f, const char *stanza, np_arg_list **opts);
  42. /* internal function that converts a single line into options format */
  43. static int add_option(FILE *f, np_arg_list **optlst);
  44. /* internal function to find default file */
  45. static char* default_file(void);
  46. /* internal function to test files access */
  47. static int test_file(const char* env, int len, const char* file, char* temp_file);
  48. /* parse_locator decomposes a string of the form
  49. * [stanza][@filename]
  50. * into its seperate parts
  51. */
  52. static void parse_locator(const char *locator, const char *def_stanza, np_ini_info *i){
  53. size_t locator_len=0, stanza_len=0;
  54. /* if locator is NULL we'll use default values */
  55. if(locator){
  56. locator_len=strlen(locator);
  57. stanza_len=strcspn(locator, "@");
  58. }
  59. /* if a non-default stanza is provided */
  60. if(stanza_len>0){
  61. i->stanza=(char*)malloc(sizeof(char)*(stanza_len+1));
  62. strncpy(i->stanza, locator, stanza_len);
  63. i->stanza[stanza_len]='\0';
  64. } else { /* otherwise we use the default stanza */
  65. i->stanza=strdup(def_stanza);
  66. }
  67. /* if there is no @file part */
  68. if(stanza_len==locator_len){
  69. i->file=default_file();
  70. if(strcmp(i->file, "") == 0){
  71. die(STATE_UNKNOWN, _("Cannot find '%s' or '%s' in any standard location.\n"), NP_DEFAULT_INI_FILENAME1, NP_DEFAULT_INI_FILENAME2);
  72. }
  73. } else {
  74. i->file=strdup(&(locator[stanza_len+1]));
  75. }
  76. if(i->file==NULL || i->stanza==NULL){
  77. die(STATE_UNKNOWN, _("malloc() failed!\n"));
  78. }
  79. }
  80. /* this is the externally visible function used by extra_opts */
  81. np_arg_list* np_get_defaults(const char *locator, const char *default_section){
  82. FILE *inifile=NULL;
  83. np_arg_list *defaults=NULL;
  84. np_ini_info i;
  85. struct stat fstat;
  86. bool is_suid_set = np_suid();
  87. if (is_suid_set && idpriv_temp_drop() == -1)
  88. die(STATE_UNKNOWN, "%s %s\n", _("Can't drop user permissions."), strerror(errno));
  89. parse_locator(locator, default_section, &i);
  90. /* If a file was specified or if we're using the default file. */
  91. if (i.file != NULL && strlen(i.file) > 0) {
  92. if (strcmp(i.file, "-") == 0) {
  93. inifile = stdin;
  94. } else {
  95. /* We must be able to stat() the thing. */
  96. if (lstat(i.file, &fstat) != 0)
  97. die(STATE_UNKNOWN, "%s %s\n", _("Can't read config file."), strerror(errno));
  98. /* The requested file must be a regular file. */
  99. if (!S_ISREG(fstat.st_mode))
  100. die(STATE_UNKNOWN, "%s\n", _("Can't read config file. Requested path is not a regular file."));
  101. /* We must be able to read the requested file. */
  102. if (access(i.file, R_OK|F_OK) != 0)
  103. die(STATE_UNKNOWN, "%s %s\n", _("Can't read config file."), strerror(errno));
  104. /* We need to successfully open the file for reading... */
  105. if ((inifile=fopen(i.file, "r")) == NULL)
  106. die(STATE_UNKNOWN, "%s %s\n", _("Can't read config file."), strerror(errno));
  107. }
  108. /* inifile points to an open FILE our ruid/rgid can access, parse its contents. */
  109. if (read_defaults(inifile, i.stanza, &defaults) == FALSE)
  110. die(STATE_UNKNOWN, _("Invalid section '%s' in config file '%s'\n"), i.stanza, i.file);
  111. if (inifile != stdin) fclose(inifile);
  112. }
  113. if (i.file != NULL) free(i.file);
  114. free(i.stanza);
  115. if (is_suid_set && idpriv_temp_restore() == -1)
  116. die(STATE_UNKNOWN, "%s %s\n", _("Can't restore user permissions."), strerror(errno));
  117. return defaults;
  118. }
  119. /* read_defaults is where the meat of the parsing takes place.
  120. *
  121. * note that this may be called by a setuid binary, so we need to
  122. * be extra careful about user-supplied input (i.e. avoiding possible
  123. * format string vulnerabilities, etc)
  124. */
  125. static int read_defaults(FILE *f, const char *stanza, np_arg_list **opts){
  126. int c, status=FALSE;
  127. size_t i, stanza_len;
  128. enum { NOSTANZA, WRONGSTANZA, RIGHTSTANZA } stanzastate=NOSTANZA;
  129. stanza_len=strlen(stanza);
  130. /* our little stanza-parsing state machine. */
  131. while((c=fgetc(f))!=EOF){
  132. /* gobble up leading whitespace */
  133. if(isspace(c)) continue;
  134. switch(c){
  135. /* globble up coment lines */
  136. case ';':
  137. case '#':
  138. GOBBLE_TO(f, c, '\n');
  139. break;
  140. /* start of a stanza. check to see if it matches */
  141. case '[':
  142. stanzastate=WRONGSTANZA;
  143. for(i=0; i<stanza_len; i++){
  144. c=fgetc(f);
  145. /* Strip leading whitespace */
  146. if(i==0) for(c; isspace(c); c=fgetc(f));
  147. /* nope, read to the end of the line */
  148. if(c!=stanza[i]) {
  149. GOBBLE_TO(f, c, '\n');
  150. break;
  151. }
  152. }
  153. /* if it matched up to here and the next char is ']'... */
  154. if(i==stanza_len){
  155. c=fgetc(f);
  156. /* Strip trailing whitespace */
  157. for(c; isspace(c); c=fgetc(f));
  158. if(c==']') stanzastate=RIGHTSTANZA;
  159. }
  160. break;
  161. /* otherwise, we're in the body of a stanza or a parse error */
  162. default:
  163. switch(stanzastate){
  164. /* we never found the start of the first stanza, so
  165. * we're dealing with a config error
  166. */
  167. case NOSTANZA:
  168. die(STATE_UNKNOWN, "%s\n", _("Config file error"));
  169. break;
  170. /* we're in a stanza, but for a different plugin */
  171. case WRONGSTANZA:
  172. GOBBLE_TO(f, c, '\n');
  173. break;
  174. /* okay, this is where we start taking the config */
  175. case RIGHTSTANZA:
  176. ungetc(c, f);
  177. if(add_option(f, opts)){
  178. die(STATE_UNKNOWN, "%s\n", _("Config file error"));
  179. }
  180. status=TRUE;
  181. break;
  182. }
  183. break;
  184. }
  185. }
  186. return status;
  187. }
  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;
  202. /* read one line from the file */
  203. while(!done_reading){
  204. /* grow if necessary */
  205. if(linebuf==NULL || read_pos+read_sz >= linebuf_sz){
  206. linebuf_sz=(linebuf_sz>0)?linebuf_sz<<1:read_sz;
  207. linebuf=realloc(linebuf, linebuf_sz);
  208. if(linebuf==NULL) die(STATE_UNKNOWN, _("malloc() failed!\n"));
  209. }
  210. if(fgets(&linebuf[read_pos], read_sz, f)==NULL) done_reading=1;
  211. else {
  212. read_pos=strlen(linebuf);
  213. if(linebuf[read_pos-1]=='\n') {
  214. linebuf[--read_pos]='\0';
  215. done_reading=1;
  216. }
  217. }
  218. }
  219. lineend=&linebuf[read_pos];
  220. /* all that to read one line. isn't C fun? :) now comes the parsing :/ */
  221. /* skip leading whitespace */
  222. for(optptr=linebuf; optptr<lineend && isspace(*optptr); optptr++);
  223. /* continue to '=' or EOL, watching for spaces that might precede it */
  224. for(eqptr=optptr; eqptr<lineend && *eqptr!='='; eqptr++){
  225. if(isspace(*eqptr) && optend==NULL) optend=eqptr;
  226. else optend=NULL;
  227. }
  228. if(optend==NULL) optend=eqptr;
  229. --optend;
  230. /* ^[[:space:]]*=foo is a syntax error */
  231. if(optptr==eqptr) die(STATE_UNKNOWN, "%s\n", _("Config file error"));
  232. /* continue from '=' to start of value or EOL */
  233. for(valptr=eqptr+1; valptr<lineend && isspace(*valptr); valptr++);
  234. /* continue to the end of value */
  235. for(valend=valptr; valend<lineend; valend++);
  236. --valend;
  237. /* Finally trim off trailing spaces */
  238. for(valend; isspace(*valend); valend--);
  239. /* calculate the length of "--foo" */
  240. opt_len=1+optend-optptr;
  241. /* 1-character params needs only one dash */
  242. if(opt_len==1)
  243. cfg_len=1+(opt_len);
  244. else
  245. cfg_len=2+(opt_len);
  246. /* if valptr<lineend then we have to also allocate space for "=bar" */
  247. if(valptr<lineend) {
  248. equals=value=1;
  249. val_len=1+valend-valptr;
  250. cfg_len+=1+val_len;
  251. }
  252. /* if valptr==valend then we have "=" but no "bar" */
  253. else if(valptr==lineend) {
  254. equals=1;
  255. cfg_len+=1;
  256. }
  257. /* A line with no equal sign isn't valid */
  258. if(equals==0) die(STATE_UNKNOWN, "%s\n", _("Config file error"));
  259. /* okay, now we have all the info we need, so we create a new np_arg_list
  260. * element and set the argument...
  261. */
  262. optnew=(np_arg_list *)malloc(sizeof(np_arg_list));
  263. 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;
  273. }
  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;
  278. }
  279. optnew->arg[read_pos]='\0';
  280. /* ...and put that to the end of the list */
  281. if(*optlst==NULL) {
  282. *optlst=optnew;
  283. } else {
  284. while(opttmp->next!=NULL) {
  285. opttmp=opttmp->next;
  286. }
  287. opttmp->next = optnew;
  288. }
  289. free(linebuf);
  290. return 0;
  291. }
  292. static char* default_file(void){
  293. struct stat sb;
  294. char *np_env=NULL, *default_file=NULL;
  295. char temp_file[MAX_INPUT_BUFFER];
  296. size_t len;
  297. if((np_env=getenv("NAGIOS_CONFIG_PATH"))!=NULL) {
  298. /* skip any starting colon... */
  299. while(*np_env==':') np_env++;
  300. /* Look for NP_DEFAULT_INI_FILENAME1 and NP_DEFAULT_INI_FILENAME2 in
  301. * every PATHs defined (colon-separated).
  302. */
  303. while((len=strcspn(np_env,":"))>0){
  304. /* Test NP_DEFAULT_INI_FILENAME[1-2] in current np_env token */
  305. if(test_file(np_env,len,NP_DEFAULT_INI_FILENAME1,temp_file)==1 ||
  306. test_file(np_env,len,NP_DEFAULT_INI_FILENAME2,temp_file)==1){
  307. default_file=strdup(temp_file);
  308. break;
  309. }
  310. /* Move on to the next token */
  311. np_env+=len;
  312. while(*np_env==':') np_env++;
  313. } /* while(...) */
  314. } /* if(getenv("NAGIOS_CONFIG_PATH")) */
  315. /* Look for NP_DEFAULT_INI_FILENAME1 in NP_DEFAULT_INI_NAGIOS_PATH[1-4] */
  316. if(!default_file){
  317. if(test_file(NP_DEFAULT_INI_NAGIOS_PATH1,strlen(NP_DEFAULT_INI_NAGIOS_PATH1),NP_DEFAULT_INI_FILENAME1,temp_file)==1 ||
  318. test_file(NP_DEFAULT_INI_NAGIOS_PATH2,strlen(NP_DEFAULT_INI_NAGIOS_PATH2),NP_DEFAULT_INI_FILENAME1,temp_file)==1 ||
  319. test_file(NP_DEFAULT_INI_NAGIOS_PATH3,strlen(NP_DEFAULT_INI_NAGIOS_PATH3),NP_DEFAULT_INI_FILENAME1,temp_file)==1 ||
  320. test_file(NP_DEFAULT_INI_NAGIOS_PATH4,strlen(NP_DEFAULT_INI_NAGIOS_PATH4),NP_DEFAULT_INI_FILENAME1,temp_file)==1)
  321. default_file=strdup(temp_file);
  322. }
  323. /* Look for NP_DEFAULT_INI_FILENAME2 in NP_DEFAULT_INI_PATH[1-3] */
  324. if(!default_file){
  325. if(test_file(NP_DEFAULT_INI_PATH1,strlen(NP_DEFAULT_INI_PATH1),NP_DEFAULT_INI_FILENAME2,temp_file)==1 ||
  326. test_file(NP_DEFAULT_INI_PATH2,strlen(NP_DEFAULT_INI_PATH2),NP_DEFAULT_INI_FILENAME2,temp_file)==1 ||
  327. test_file(NP_DEFAULT_INI_PATH3,strlen(NP_DEFAULT_INI_PATH3),NP_DEFAULT_INI_FILENAME2,temp_file)==1)
  328. default_file=strdup(temp_file);
  329. }
  330. /* Return default_file or empty string (should return NULL if we want plugins
  331. * to die there)...
  332. */
  333. if(default_file)
  334. return default_file;
  335. return "";
  336. }
  337. /* put together len bytes from env and the filename and test for its
  338. * existence. Returns 1 if found, 0 if not and -1 if test wasn't performed.
  339. */
  340. static int test_file(const char* env, int len, const char* file, char* temp_file){
  341. /* test if len + filelen + '/' + '\0' fits in temp_file */
  342. if((len+strlen(file)+2)>MAX_INPUT_BUFFER) return -1;
  343. strncpy(temp_file,env,len);
  344. temp_file[len]='\0';
  345. strncat(temp_file,"/",len+1);
  346. strncat(temp_file,file,len+strlen(file)+1);
  347. if(access(temp_file, F_OK) == 0) return 1;
  348. return 0;
  349. }