utils_base.c 17 KB

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