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