utils_base.c 16 KB

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