utils_base.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  1. /*****************************************************************************
  2. *
  3. * utils_base.c
  4. *
  5. * License: GPL
  6. * Copyright (c) 2006 Nagios Plugins Development Team
  7. *
  8. * Library of useful functions for plugins
  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. *
  25. *****************************************************************************/
  26. #include "common.h"
  27. #include <stdarg.h>
  28. #include "utils_base.h"
  29. #include <fcntl.h>
  30. #define np_free(ptr) { if(ptr) { free(ptr); ptr = NULL; } }
  31. nagios_plugin *this_nagios_plugin=NULL;
  32. void np_init( char *plugin_name, int argc, char **argv ) {
  33. if (this_nagios_plugin==NULL) {
  34. this_nagios_plugin = calloc(1, sizeof(nagios_plugin));
  35. if (this_nagios_plugin==NULL) {
  36. die(STATE_UNKNOWN, _("Cannot allocate memory: %s"),
  37. strerror(errno));
  38. }
  39. this_nagios_plugin->plugin_name = strdup(plugin_name);
  40. if (this_nagios_plugin->plugin_name==NULL)
  41. die(STATE_UNKNOWN, _("Cannot execute strdup: %s"), strerror(errno));
  42. this_nagios_plugin->argc = argc;
  43. this_nagios_plugin->argv = argv;
  44. }
  45. }
  46. void np_set_args( int argc, char **argv ) {
  47. if (this_nagios_plugin==NULL)
  48. die(STATE_UNKNOWN, _("This requires np_init to be called"));
  49. this_nagios_plugin->argc = argc;
  50. this_nagios_plugin->argv = argv;
  51. }
  52. void np_cleanup() {
  53. if (this_nagios_plugin!=NULL) {
  54. if(this_nagios_plugin->state!=NULL) {
  55. if(this_nagios_plugin->state->state_data) {
  56. np_free(this_nagios_plugin->state->state_data->data);
  57. np_free(this_nagios_plugin->state->state_data);
  58. }
  59. np_free(this_nagios_plugin->state->name);
  60. np_free(this_nagios_plugin->state);
  61. }
  62. np_free(this_nagios_plugin->plugin_name);
  63. np_free(this_nagios_plugin);
  64. }
  65. this_nagios_plugin=NULL;
  66. }
  67. /* Hidden function to get a pointer to this_nagios_plugin for testing */
  68. void _get_nagios_plugin( nagios_plugin **pointer ){
  69. *pointer = this_nagios_plugin;
  70. }
  71. void
  72. die (int result, const char *fmt, ...)
  73. {
  74. va_list ap;
  75. va_start (ap, fmt);
  76. vprintf (fmt, ap);
  77. va_end (ap);
  78. if(this_nagios_plugin!=NULL) {
  79. np_cleanup();
  80. }
  81. exit (result);
  82. }
  83. void set_range_start (range *this, double value) {
  84. this->start = value;
  85. this->start_infinity = FALSE;
  86. }
  87. void set_range_end (range *this, double value) {
  88. this->end = value;
  89. this->end_infinity = FALSE;
  90. }
  91. range
  92. *parse_range_string (char *str) {
  93. range *temp_range;
  94. double start;
  95. double end;
  96. char *end_str;
  97. temp_range = (range *) calloc(1, sizeof(range));
  98. /* Set defaults */
  99. temp_range->start = 0;
  100. temp_range->start_infinity = FALSE;
  101. temp_range->end = 0;
  102. temp_range->end_infinity = TRUE;
  103. temp_range->alert_on = OUTSIDE;
  104. if (str[0] == '@') {
  105. temp_range->alert_on = INSIDE;
  106. str++;
  107. }
  108. end_str = index(str, ':');
  109. if (end_str != NULL) {
  110. if (str[0] == '~') {
  111. temp_range->start_infinity = TRUE;
  112. } else {
  113. start = strtod(str, NULL); /* Will stop at the ':' */
  114. set_range_start(temp_range, start);
  115. }
  116. end_str++; /* Move past the ':' */
  117. } else {
  118. end_str = str;
  119. }
  120. end = strtod(end_str, NULL);
  121. if (strcmp(end_str, "") != 0) {
  122. set_range_end(temp_range, end);
  123. }
  124. if (temp_range->start_infinity == TRUE ||
  125. temp_range->end_infinity == TRUE ||
  126. temp_range->start <= temp_range->end) {
  127. return temp_range;
  128. }
  129. free(temp_range);
  130. return NULL;
  131. }
  132. /* returns 0 if okay, otherwise 1 */
  133. int
  134. _set_thresholds(thresholds **my_thresholds, char *warn_string, char *critical_string)
  135. {
  136. thresholds *temp_thresholds = NULL;
  137. if ((temp_thresholds = calloc(1, sizeof(thresholds))) == NULL)
  138. die(STATE_UNKNOWN, _("Cannot allocate memory: %s"),
  139. strerror(errno));
  140. temp_thresholds->warning = NULL;
  141. temp_thresholds->critical = NULL;
  142. if (warn_string != NULL) {
  143. if ((temp_thresholds->warning = parse_range_string(warn_string)) == NULL) {
  144. return NP_RANGE_UNPARSEABLE;
  145. }
  146. }
  147. if (critical_string != NULL) {
  148. if ((temp_thresholds->critical = parse_range_string(critical_string)) == NULL) {
  149. return NP_RANGE_UNPARSEABLE;
  150. }
  151. }
  152. *my_thresholds = temp_thresholds;
  153. return 0;
  154. }
  155. void
  156. set_thresholds(thresholds **my_thresholds, char *warn_string, char *critical_string)
  157. {
  158. switch (_set_thresholds(my_thresholds, warn_string, critical_string)) {
  159. case 0:
  160. return;
  161. case NP_RANGE_UNPARSEABLE:
  162. die(STATE_UNKNOWN, _("Range format incorrect"));
  163. case NP_WARN_WITHIN_CRIT:
  164. die(STATE_UNKNOWN, _("Warning level is a subset of critical and will not be alerted"));
  165. break;
  166. }
  167. }
  168. void print_thresholds(const char *threshold_name, thresholds *my_threshold) {
  169. printf("%s - ", threshold_name);
  170. if (! my_threshold) {
  171. printf("Threshold not set");
  172. } else {
  173. if (my_threshold->warning) {
  174. printf("Warning: start=%g end=%g; ", my_threshold->warning->start, my_threshold->warning->end);
  175. } else {
  176. printf("Warning not set; ");
  177. }
  178. if (my_threshold->critical) {
  179. printf("Critical: start=%g end=%g", my_threshold->critical->start, my_threshold->critical->end);
  180. } else {
  181. printf("Critical not set");
  182. }
  183. }
  184. printf("\n");
  185. }
  186. /* Returns TRUE if alert should be raised based on the range */
  187. int
  188. check_range(double value, range *my_range)
  189. {
  190. int no = FALSE;
  191. int yes = TRUE;
  192. if (my_range->alert_on == INSIDE) {
  193. no = TRUE;
  194. yes = FALSE;
  195. }
  196. if (my_range->end_infinity == FALSE && my_range->start_infinity == FALSE) {
  197. if ((my_range->start <= value) && (value <= my_range->end)) {
  198. return no;
  199. } else {
  200. return yes;
  201. }
  202. } else if (my_range->start_infinity == FALSE && my_range->end_infinity == TRUE) {
  203. if (my_range->start <= value) {
  204. return no;
  205. } else {
  206. return yes;
  207. }
  208. } else if (my_range->start_infinity == TRUE && my_range->end_infinity == FALSE) {
  209. if (value <= my_range->end) {
  210. return no;
  211. } else {
  212. return yes;
  213. }
  214. } else {
  215. return no;
  216. }
  217. }
  218. /* Returns status */
  219. int
  220. get_status(double value, thresholds *my_thresholds)
  221. {
  222. if (my_thresholds->critical != NULL) {
  223. if (check_range(value, my_thresholds->critical) == TRUE) {
  224. return STATE_CRITICAL;
  225. }
  226. }
  227. if (my_thresholds->warning != NULL) {
  228. if (check_range(value, my_thresholds->warning) == TRUE) {
  229. return STATE_WARNING;
  230. }
  231. }
  232. return STATE_OK;
  233. }
  234. char *np_escaped_string (const char *string) {
  235. char *data;
  236. int i, j=0;
  237. data = strdup(string);
  238. for (i=0; data[i]; i++) {
  239. if (data[i] == '\\') {
  240. switch(data[++i]) {
  241. case 'n':
  242. data[j++] = '\n';
  243. break;
  244. case 'r':
  245. data[j++] = '\r';
  246. break;
  247. case 't':
  248. data[j++] = '\t';
  249. break;
  250. case '\\':
  251. data[j++] = '\\';
  252. break;
  253. default:
  254. data[j++] = data[i];
  255. }
  256. } else {
  257. data[j++] = data[i];
  258. }
  259. }
  260. data[j] = '\0';
  261. return data;
  262. }
  263. int np_check_if_root(void) { return (geteuid() == 0); }
  264. int np_warn_if_not_root(void) {
  265. int status = np_check_if_root();
  266. if(!status) {
  267. printf(_("Warning: "));
  268. printf(_("This plugin must be either run as root or setuid root.\n"));
  269. printf(_("To run as root, you can use a tool like sudo.\n"));
  270. printf(_("To set the setuid permissions, use the command:\n"));
  271. /* XXX could we use something like progname? */
  272. printf("\tchmod u+s yourpluginfile\n");
  273. }
  274. return status;
  275. }
  276. /*
  277. * Extract the value from key/value pairs, or return NULL. The value returned
  278. * can be free()ed.
  279. * This function can be used to parse NTP control packet data and performance
  280. * data strings.
  281. */
  282. char *np_extract_value(const char *varlist, const char *name, char sep) {
  283. char *tmp=NULL, *value=NULL;
  284. int i;
  285. while (1) {
  286. /* Strip any leading space */
  287. for (varlist; isspace(varlist[0]); varlist++);
  288. if (strncmp(name, varlist, strlen(name)) == 0) {
  289. varlist += strlen(name);
  290. /* strip trailing spaces */
  291. for (varlist; isspace(varlist[0]); varlist++);
  292. if (varlist[0] == '=') {
  293. /* We matched the key, go past the = sign */
  294. varlist++;
  295. /* strip leading spaces */
  296. for (varlist; isspace(varlist[0]); varlist++);
  297. if (tmp = index(varlist, sep)) {
  298. /* Value is delimited by a comma */
  299. if (tmp-varlist == 0) continue;
  300. value = (char *)calloc(1, tmp-varlist+1);
  301. strncpy(value, varlist, tmp-varlist);
  302. value[tmp-varlist] = '\0';
  303. } else {
  304. /* Value is delimited by a \0 */
  305. if (strlen(varlist) == 0) continue;
  306. value = (char *)calloc(1, strlen(varlist) + 1);
  307. strncpy(value, varlist, strlen(varlist));
  308. value[strlen(varlist)] = '\0';
  309. }
  310. break;
  311. }
  312. }
  313. if (tmp = index(varlist, sep)) {
  314. /* More keys, keep going... */
  315. varlist = tmp + 1;
  316. } else {
  317. /* We're done */
  318. break;
  319. }
  320. }
  321. /* Clean-up trailing spaces/newlines */
  322. if (value) for (i=strlen(value)-1; isspace(value[i]); i--) value[i] = '\0';
  323. return value;
  324. }
  325. /*
  326. * Returns a string to use as a keyname, based on an md5 hash of argv, thus
  327. * hopefully a unique key per service/plugin invocation. Use the extra-opts
  328. * parse of argv, so that uniqueness in parameters are reflected there.
  329. */
  330. char *_np_state_generate_key() {
  331. struct sha1_ctx ctx;
  332. int i;
  333. char **argv = this_nagios_plugin->argv;
  334. unsigned char result[20];
  335. char keyname[41];
  336. char *p=NULL;
  337. sha1_init_ctx(&ctx);
  338. for(i=0; i<this_nagios_plugin->argc; i++) {
  339. sha1_process_bytes(argv[i], strlen(argv[i]), &ctx);
  340. }
  341. sha1_finish_ctx(&ctx, &result);
  342. for (i=0; i<20; ++i) {
  343. sprintf(&keyname[2*i], "%02x", result[i]);
  344. }
  345. keyname[40]='\0';
  346. p = strdup(keyname);
  347. if(p==NULL) {
  348. die(STATE_UNKNOWN, _("Cannot execute strdup: %s"), strerror(errno));
  349. }
  350. return p;
  351. }
  352. void _cleanup_state_data() {
  353. if (this_nagios_plugin->state->state_data!=NULL) {
  354. np_free(this_nagios_plugin->state->state_data->data);
  355. np_free(this_nagios_plugin->state->state_data);
  356. }
  357. }
  358. /*
  359. * Internal function. Returns either:
  360. * envvar NAGIOS_PLUGIN_STATE_DIRECTORY
  361. * statically compiled shared state directory
  362. */
  363. char* _np_state_calculate_location_prefix(){
  364. char *env_dir;
  365. env_dir = getenv("NAGIOS_PLUGIN_STATE_DIRECTORY");
  366. if(env_dir && env_dir[0] != '\0')
  367. return env_dir;
  368. return NP_STATE_DIR_PREFIX;
  369. }
  370. /*
  371. * Initiatializer for state routines.
  372. * Sets variables. Generates filename. Returns np_state_key. die with
  373. * UNKNOWN if exception
  374. */
  375. void np_enable_state(char *keyname, int expected_data_version) {
  376. state_key *this_state = NULL;
  377. char *temp_filename = NULL;
  378. char *temp_keyname = NULL;
  379. char *p=NULL;
  380. if(this_nagios_plugin==NULL)
  381. die(STATE_UNKNOWN, _("This requires np_init to be called"));
  382. this_state = (state_key *) calloc(1, sizeof(state_key));
  383. if(this_state==NULL)
  384. die(STATE_UNKNOWN, _("Cannot allocate memory: %s"),
  385. strerror(errno));
  386. if(keyname==NULL) {
  387. temp_keyname = _np_state_generate_key();
  388. } else {
  389. temp_keyname = strdup(keyname);
  390. if(temp_keyname==NULL)
  391. die(STATE_UNKNOWN, _("Cannot execute strdup: %s"), strerror(errno));
  392. }
  393. /* Die if invalid characters used for keyname */
  394. p = temp_keyname;
  395. while(*p!='\0') {
  396. if(! (isalnum(*p) || *p == '_')) {
  397. die(STATE_UNKNOWN, _("Invalid character for keyname - only alphanumerics or '_'"));
  398. }
  399. p++;
  400. }
  401. this_state->name=temp_keyname;
  402. this_state->plugin_name=this_nagios_plugin->plugin_name;
  403. this_state->data_version=expected_data_version;
  404. this_state->state_data=NULL;
  405. /* Calculate filename */
  406. asprintf(&temp_filename, "%s/%s/%s", _np_state_calculate_location_prefix(), this_nagios_plugin->plugin_name, this_state->name);
  407. this_state->_filename=temp_filename;
  408. this_nagios_plugin->state = this_state;
  409. }
  410. /*
  411. * Will return NULL if no data is available (first run). If key currently
  412. * exists, read data. If state file format version is not expected, return
  413. * as if no data. Get state data version number and compares to expected.
  414. * If numerically lower, then return as no previous state. die with UNKNOWN
  415. * if exceptional error.
  416. */
  417. state_data *np_state_read() {
  418. state_data *this_state_data=NULL;
  419. FILE *statefile;
  420. int rc = FALSE;
  421. if(this_nagios_plugin==NULL)
  422. die(STATE_UNKNOWN, _("This requires np_init to be called"));
  423. /* Open file. If this fails, no previous state found */
  424. statefile = fopen( this_nagios_plugin->state->_filename, "r" );
  425. if(statefile!=NULL) {
  426. this_state_data = (state_data *) calloc(1, sizeof(state_data));
  427. if(this_state_data==NULL)
  428. die(STATE_UNKNOWN, _("Cannot allocate memory: %s"),
  429. strerror(errno));
  430. this_state_data->data=NULL;
  431. this_nagios_plugin->state->state_data = this_state_data;
  432. rc = _np_state_read_file(statefile);
  433. fclose(statefile);
  434. }
  435. if(rc==FALSE) {
  436. _cleanup_state_data();
  437. }
  438. return this_nagios_plugin->state->state_data;
  439. }
  440. /*
  441. * Read the state file
  442. */
  443. int _np_state_read_file(FILE *f) {
  444. int status=FALSE;
  445. size_t pos;
  446. char *line;
  447. int i;
  448. int failure=0;
  449. time_t current_time, data_time;
  450. enum { STATE_FILE_VERSION, STATE_DATA_VERSION, STATE_DATA_TIME, STATE_DATA_TEXT, STATE_DATA_END } expected=STATE_FILE_VERSION;
  451. time(&current_time);
  452. /* Note: This introduces a limit of 1024 bytes in the string data */
  453. line = (char *) calloc(1, 1024);
  454. if(line==NULL)
  455. die(STATE_UNKNOWN, _("Cannot allocate memory: %s"),
  456. strerror(errno));
  457. while(!failure && (fgets(line,1024,f))!=NULL){
  458. pos=strlen(line);
  459. if(line[pos-1]=='\n') {
  460. line[pos-1]='\0';
  461. }
  462. if(line[0] == '#') continue;
  463. switch(expected) {
  464. case STATE_FILE_VERSION:
  465. i=atoi(line);
  466. if(i!=NP_STATE_FORMAT_VERSION)
  467. failure++;
  468. else
  469. expected=STATE_DATA_VERSION;
  470. break;
  471. case STATE_DATA_VERSION:
  472. i=atoi(line);
  473. if(i != this_nagios_plugin->state->data_version)
  474. failure++;
  475. else
  476. expected=STATE_DATA_TIME;
  477. break;
  478. case STATE_DATA_TIME:
  479. /* If time > now, error */
  480. data_time=strtoul(line,NULL,10);
  481. if(data_time > current_time)
  482. failure++;
  483. else {
  484. this_nagios_plugin->state->state_data->time = data_time;
  485. expected=STATE_DATA_TEXT;
  486. }
  487. break;
  488. case STATE_DATA_TEXT:
  489. this_nagios_plugin->state->state_data->data = strdup(line);
  490. if(this_nagios_plugin->state->state_data->data==NULL)
  491. die(STATE_UNKNOWN, _("Cannot execute strdup: %s"), strerror(errno));
  492. expected=STATE_DATA_END;
  493. status=TRUE;
  494. break;
  495. case STATE_DATA_END:
  496. ;
  497. }
  498. }
  499. np_free(line);
  500. return status;
  501. }
  502. /*
  503. * If time=NULL, use current time. Create state file, with state format
  504. * version, default text. Writes version, time, and data. Avoid locking
  505. * problems - use mv to write and then swap. Possible loss of state data if
  506. * two things writing to same key at same time.
  507. * Will die with UNKNOWN if errors
  508. */
  509. void np_state_write_string(time_t data_time, char *data_string) {
  510. FILE *fp;
  511. char *temp_file=NULL;
  512. int fd=0, result=0;
  513. time_t current_time;
  514. char *directories=NULL;
  515. char *p=NULL;
  516. if(data_time==0)
  517. time(&current_time);
  518. else
  519. current_time=data_time;
  520. /* If file doesn't currently exist, create directories */
  521. if(access(this_nagios_plugin->state->_filename,F_OK)!=0) {
  522. asprintf(&directories, "%s", this_nagios_plugin->state->_filename);
  523. if(directories==NULL)
  524. die(STATE_UNKNOWN, _("Cannot allocate memory: %s"),
  525. strerror(errno));
  526. for(p=directories+1; *p; p++) {
  527. if(*p=='/') {
  528. *p='\0';
  529. if((access(directories,F_OK)!=0) && (mkdir(directories, S_IRWXU)!=0)) {
  530. /* Can't free this! Otherwise error message is wrong! */
  531. /* np_free(directories); */
  532. die(STATE_UNKNOWN, _("Cannot create directory: %s"), directories);
  533. }
  534. *p='/';
  535. }
  536. }
  537. np_free(directories);
  538. }
  539. asprintf(&temp_file,"%s.XXXXXX",this_nagios_plugin->state->_filename);
  540. if(temp_file==NULL)
  541. die(STATE_UNKNOWN, _("Cannot allocate memory: %s"),
  542. strerror(errno));
  543. if((fd=mkstemp(temp_file))==-1) {
  544. np_free(temp_file);
  545. die(STATE_UNKNOWN, _("Cannot create temporary filename"));
  546. }
  547. fp=(FILE *)fdopen(fd,"w");
  548. if(fp==NULL) {
  549. close(fd);
  550. unlink(temp_file);
  551. np_free(temp_file);
  552. die(STATE_UNKNOWN, _("Unable to open temporary state file"));
  553. }
  554. fprintf(fp,"# NP State file\n");
  555. fprintf(fp,"%d\n",NP_STATE_FORMAT_VERSION);
  556. fprintf(fp,"%d\n",this_nagios_plugin->state->data_version);
  557. fprintf(fp,"%lu\n",current_time);
  558. fprintf(fp,"%s\n",data_string);
  559. fchmod(fd, S_IRUSR | S_IWUSR | S_IRGRP);
  560. fflush(fp);
  561. result=fclose(fp);
  562. fsync(fd);
  563. if(result!=0) {
  564. unlink(temp_file);
  565. np_free(temp_file);
  566. die(STATE_UNKNOWN, _("Error writing temp file"));
  567. }
  568. if(rename(temp_file, this_nagios_plugin->state->_filename)!=0) {
  569. unlink(temp_file);
  570. np_free(temp_file);
  571. die(STATE_UNKNOWN, _("Cannot rename state temp file"));
  572. }
  573. np_free(temp_file);
  574. }