Code

Added state retention APIs. Implemented for check_snmp with --rate option.
[nagiosplug.git] / lib / utils_base.c
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;
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;
151 /* returns 0 if okay, otherwise 1 */
152 int
153 _set_thresholds(thresholds **my_thresholds, char *warn_string, char *critical_string)
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;
180 void
181 set_thresholds(thresholds **my_thresholds, char *warn_string, char *critical_string)
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         }
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");
213 /* Returns TRUE if alert should be raised based on the range */
214 int
215 check_range(double value, range *my_range)
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         }
248 /* Returns status */
249 int
250 get_status(double value, thresholds *my_thresholds)
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;
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;
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;
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;
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);
380         
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);
386         
387         for (i=0; i<20; ++i) {
388                 sprintf(&keyname[2*i], "%02x", result[i]);
389         }
390         keyname[40]='\0';
391         
392         p = strdup(keyname);
393         if(p==NULL) {
394                 die(STATE_UNKNOWN, _("Cannot execute strdup: %s"), strerror(errno));
395         }
396         return p;
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         }
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;
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;
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_key *my_state_key;
475         state_data *this_state_data=NULL;
476         FILE *statefile;
477         int c;
478         int rc = FALSE;
480         if(this_nagios_plugin==NULL)
481                 die(STATE_UNKNOWN, _("This requires np_init to be called"));
483         /* Open file. If this fails, no previous state found */
484         statefile = fopen( this_nagios_plugin->state->_filename, "r" );
485         if(statefile!=NULL) {
487                 this_state_data = (state_data *) malloc(sizeof(state_data));
488                 if(this_state_data==NULL)
489                         die(STATE_UNKNOWN, _("Cannot allocate memory: %s"),
490                             strerror(errno));
492                 this_state_data->data=NULL;
493                 this_nagios_plugin->state->state_data = this_state_data;
495                 rc = _np_state_read_file(statefile);
497                 fclose(statefile);
498         }
500         if(rc==FALSE) {
501                 _cleanup_state_data();
502         }
504         return this_nagios_plugin->state->state_data;
507 /* 
508  * Read the state file
509  */
510 int _np_state_read_file(FILE *f) {
511         int c, status=FALSE;
512         size_t pos;
513         char *line;
514         int i;
515         int failure=0;
516         time_t current_time, data_time;
517         enum { STATE_FILE_VERSION, STATE_DATA_VERSION, STATE_DATA_TIME, STATE_DATA_TEXT, STATE_DATA_END } expected=STATE_FILE_VERSION;
519         time(&current_time);
521         /* Note: This introduces a limit of 1024 bytes in the string data */
522         line = (char *) malloc(1024);
523         if(line==NULL)
524                 die(STATE_UNKNOWN, _("Cannot allocate memory: %s"),
525                     strerror(errno));
527         while(!failure && (fgets(line,1024,f))!=NULL){
528                 pos=strlen(line);
529                 if(line[pos-1]=='\n') {
530                         line[pos-1]='\0';
531                 }
533                 if(line[0] == '#') continue;
535                 switch(expected) {
536                         case STATE_FILE_VERSION:
537                                 i=atoi(line);
538                                 if(i!=NP_STATE_FORMAT_VERSION)
539                                         failure++;
540                                 else
541                                         expected=STATE_DATA_VERSION;
542                                 break;
543                         case STATE_DATA_VERSION:
544                                 i=atoi(line);
545                                 if(i != this_nagios_plugin->state->data_version)
546                                         failure++;
547                                 else
548                                         expected=STATE_DATA_TIME;
549                                 break;
550                         case STATE_DATA_TIME:
551                                 /* If time > now, error */
552                                 data_time=strtoul(line,NULL,10);
553                                 if(data_time > current_time)
554                                         failure++;
555                                 else {
556                                         this_nagios_plugin->state->state_data->time = data_time;
557                                         expected=STATE_DATA_TEXT;
558                                 }
559                                 break;
560                         case STATE_DATA_TEXT:
561                                 this_nagios_plugin->state->state_data->data = strdup(line);
562                                 if(this_nagios_plugin->state->state_data->data==NULL)
563                                         die(STATE_UNKNOWN, _("Cannot execute strdup: %s"), strerror(errno));
564                                 expected=STATE_DATA_END;
565                                 status=TRUE;
566                                 break;
567                         case STATE_DATA_END:
568                                 ;
569                 }
570         }
572         np_free(line);
573         return status;
576 /*
577  * If time=NULL, use current time. Create state file, with state format 
578  * version, default text. Writes version, time, and data. Avoid locking 
579  * problems - use mv to write and then swap. Possible loss of state data if 
580  * two things writing to same key at same time. 
581  * Will die with UNKNOWN if errors
582  */
583 void np_state_write_string(time_t data_time, char *data_string) {
584         FILE *fp;
585         char *temp_file=NULL;
586         int fd=0, result=0;
587         time_t current_time;
588         size_t len;
589         char *directories=NULL;
590         char *p=NULL;
592         if(data_time==0)
593                 time(&current_time);
594         else
595                 current_time=data_time;
596         
597         /* If file doesn't currently exist, create directories */
598         if(access(this_nagios_plugin->state->_filename,F_OK)!=0) {
599                 asprintf(&directories, "%s", this_nagios_plugin->state->_filename);
600                 if(directories==NULL)
601                         die(STATE_UNKNOWN, _("Cannot allocate memory: %s"),
602                             strerror(errno));
604                 for(p=directories+1; *p; p++) {
605                         if(*p=='/') {
606                                 *p='\0';
607                                 if((access(directories,F_OK)!=0) && (mkdir(directories, S_IRWXU)!=0)) {
608                                         /* Can't free this! Otherwise error message is wrong! */
609                                         /* np_free(directories); */ 
610                                         die(STATE_UNKNOWN, _("Cannot create directory: %s"), directories);
611                                 }
612                                 *p='/';
613                         }
614                 }
615                 np_free(directories);
616         }
618         asprintf(&temp_file,"%s.XXXXXX",this_nagios_plugin->state->_filename);
619         if(temp_file==NULL)
620                 die(STATE_UNKNOWN, _("Cannot allocate memory: %s"),
621                     strerror(errno));
623         if((fd=mkstemp(temp_file))==-1) {
624                 np_free(temp_file);
625                 die(STATE_UNKNOWN, _("Cannot create temporary filename"));
626         }
628         fp=(FILE *)fdopen(fd,"w");
629         if(fp==NULL) {
630                 close(fd);
631                 unlink(temp_file);
632                 np_free(temp_file);
633                 die(STATE_UNKNOWN, _("Unable to open temporary state file"));
634         }
635         
636         fprintf(fp,"# NP State file\n");
637         fprintf(fp,"%d\n",NP_STATE_FORMAT_VERSION);
638         fprintf(fp,"%d\n",this_nagios_plugin->state->data_version);
639         fprintf(fp,"%lu\n",current_time);
640         fprintf(fp,"%s\n",data_string);
641         
642         fchmod(fd, S_IRUSR | S_IWUSR | S_IRGRP);
643         
644         fflush(fp);
646         result=fclose(fp);
648         fsync(fd);
650         if(result!=0) {
651                 unlink(temp_file);
652                 np_free(temp_file);
653                 die(STATE_UNKNOWN, _("Error writing temp file"));
654         }
656         if(rename(temp_file, this_nagios_plugin->state->_filename)!=0) {
657                 unlink(temp_file);
658                 np_free(temp_file);
659                 die(STATE_UNKNOWN, _("Cannot rename state temp file"));
660         }
662         np_free(temp_file);