Code

the last round of pedantic compiler warnings
[nagiosplug.git] / plugins / check_nt.c
1 /******************************************************************************
2  *
3  * CHECK_NT.C
4  *
5  * Program: Windows NT plugin for NetSaint
6  * License: GPL
7  * Copyright (c) 2000-2002 Yves Rubin (rubiyz@yahoo.com)
8  *
9  * Description:
10  * 
11  * This requires NSClient software to run on NT (http://nsclient.ready2run.nl/)
12  *
13  * License Information:
14  *
15  * This program is free software; you can redistribute it and/or modify
16  * it under the terms of the GNU General Public License as published by
17  * the Free Software Foundation; either version 2 of the License, or
18  * (at your option) any later version.
19  *
20  * This program is distributed in the hope that it will be useful,
21  * but WITHOUT ANY WARRANTY; without even the implied warranty of
22  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23  * GNU General Public License for more details.
24  *
25  * You should have received a copy of the GNU General Public License
26  * along with this program; if not, write to the Free Software
27  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28  *
29  *****************************************************************************/
31 #include "common.h"
32 #include "netutils.h"
33 #include "utils.h"
35 enum checkvars {
36         CHECK_NONE,
37         CHECK_CLIENTVERSION,
38         CHECK_CPULOAD,
39         CHECK_UPTIME,
40         CHECK_USEDDISKSPACE,
41         CHECK_SERVICESTATE,
42         CHECK_PROCSTATE,
43         CHECK_MEMUSE,
44         CHECK_COUNTER,
45         CHECK_FILEAGE
46 };
48 enum {
49         MAX_VALUE_LIST = 30,
50         PORT = 1248
51 };
53 char *server_address=NULL;
54 char *volume_name=NULL;
55 int server_port=PORT;
56 char *value_list=NULL;
57 char *req_password=NULL;
58 unsigned long lvalue_list[MAX_VALUE_LIST];
59 unsigned long warning_value=0L;
60 unsigned long critical_value=0L;
61 int check_value_list=FALSE;
62 int check_warning_value=FALSE;
63 int check_critical_value=FALSE;
64 enum checkvars vars_to_check = CHECK_NONE;
65 int show_all=FALSE;
67 const char *progname = "check_nt";
69 char recv_buffer[MAX_INPUT_BUFFER];
71 void fetch_data (const char* address, int port, const char* sendb);
72 int process_arguments(int, char **);
73 void preparelist(char *string);
74 int strtoularray(unsigned long *array, char *string, const char *delim);
75 void print_help(void);
76 void print_usage(void);
78 int main(int argc, char **argv){
79         int return_code = STATE_UNKNOWN;
80         char *send_buffer=NULL;
81         char *output_message=NULL;
82         char *temp_string=NULL;
83         char *description=NULL;
85         double total_disk_space=0;
86         double free_disk_space=0;
87         double percent_used_space=0;
88         double mem_commitLimit=0;
89         double mem_commitByte=0;
90         unsigned long utilization;
91         unsigned long uptime;
92         unsigned long age_in_minutes;
93         double counter_value;
94         int offset=0;
95         int updays=0;
96         int uphours=0;
97         int upminutes=0;
99         if(process_arguments(argc,argv)==ERROR)
100                 usage(_("Could not parse arguments\n"));
102         /* initialize alarm signal handling */
103         signal(SIGALRM,socket_timeout_alarm_handler);
105         /* set socket timeout */
106         alarm(socket_timeout);
108         switch (vars_to_check) {
110         case CHECK_CLIENTVERSION:
112                 asprintf(&send_buffer, "%s&1", req_password);
113                 fetch_data (server_address, server_port, send_buffer);
114                 output_message = strdup (recv_buffer);
115                 return_code=STATE_OK;
116                 break;
118         case CHECK_CPULOAD:
120                 if (value_list==NULL)
121                         output_message = strdup (_("missing -l parameters"));
122                 else if (strtoularray(lvalue_list,value_list,",")==FALSE)
123                         output_message = strdup (_("wrong -l parameter."));
124                 else {
125                         /* -l parameters is present with only integers */
126                         return_code=STATE_OK;
127                         temp_string = strdup (_("CPU Load"));
128                         /* loop until one of the parameters is wrong or not present */
129                         while (lvalue_list[0+offset]> (unsigned long)0 &&
130                                                  lvalue_list[0+offset]<=(unsigned long)17280 && 
131                                                  lvalue_list[1+offset]> (unsigned long)0 &&
132                                                  lvalue_list[1+offset]<=(unsigned long)100 && 
133                                                  lvalue_list[2+offset]> (unsigned long)0 &&
134                                                  lvalue_list[2+offset]<=(unsigned long)100) {
136                                 /* Send request and retrieve data */
137                                 asprintf(&send_buffer,"%s&2&%lu",req_password,lvalue_list[0+offset]);
138                                 fetch_data (server_address, server_port, send_buffer);
140                                 utilization=strtoul(recv_buffer,NULL,10);
141                                 
142                                 /* Check if any of the request is in a warning or critical state */
143                                 if(utilization >= lvalue_list[2+offset])
144                                         return_code=STATE_CRITICAL;
145                                 else if(utilization >= lvalue_list[1+offset] && return_code<STATE_WARNING)
146                                         return_code=STATE_WARNING;
148                                 asprintf(&output_message,_(" %lu%% (%lu min average)"), utilization, lvalue_list[0+offset]);
149                                 asprintf(&temp_string,"%s%s",temp_string,output_message);
150                                 offset+=3;      /* move across the array */
151                         }
152                         if (strlen(temp_string)>10)  /* we had at least one loop */
153                                 output_message = strdup (temp_string);
154                         else
155                                 output_message = strdup (_("not enough values for -l parameters"));
156                 }       
157                 break;
159         case CHECK_UPTIME:
161                 asprintf(&send_buffer, "%s&3", req_password);
162                 fetch_data (server_address, server_port, send_buffer);
163                 uptime=strtoul(recv_buffer,NULL,10);
164                 updays = uptime / 86400;                        
165                 uphours = (uptime % 86400) / 3600;
166                 upminutes = ((uptime % 86400) % 3600) / 60;
167                 asprintf(&output_message,_("System Uptime : %u day(s) %u hour(s) %u minute(s)"),updays,uphours, upminutes);
168                 return_code=STATE_OK;
169                 break;
171         case CHECK_USEDDISKSPACE:
173                 if (value_list==NULL)
174                         output_message = strdup (_("missing -l parameters"));
175                 else if (strlen(value_list)==1)
176                         output_message = strdup (_("wrong -l argument"));
177                 else {
178                         asprintf(&send_buffer,"%s&4&%s", req_password, value_list);
179                         fetch_data (server_address, server_port, send_buffer);
180                         free_disk_space=atof(strtok(recv_buffer,"&"));
181                         total_disk_space=atof(strtok(NULL,"&"));
182                         percent_used_space = ((total_disk_space - free_disk_space) / total_disk_space) * 100;
184                         if (free_disk_space>=0) {
185                                 asprintf(&temp_string,_("%s:\\ - total: %.2f Gb - used: %.2f Gb (%.0f%%) - free %.2f Gb (%.0f%%)"),
186                                                                  value_list, total_disk_space / 1073741824, (total_disk_space - free_disk_space) / 1073741824, percent_used_space,
187                                                                  free_disk_space / 1073741824, (free_disk_space / total_disk_space)*100); 
190                                 if(check_critical_value==TRUE && percent_used_space >= critical_value)
191                                         return_code=STATE_CRITICAL;
192                                 else if (check_warning_value==TRUE && percent_used_space >= warning_value)
193                                         return_code=STATE_WARNING;      
194                                 else
195                                         return_code=STATE_OK;   
197                                 output_message = strdup (temp_string);
198                         }
199                         else {
200                                 output_message = strdup (_("Free disk space : Invalid drive "));
201                                 return_code=STATE_UNKNOWN;
202                         }
203                 }
204                 break;
206         case CHECK_SERVICESTATE:
207         case CHECK_PROCSTATE:
209                 if (value_list==NULL)
210                         output_message = strdup (_("No service/process specified"));
211                 else {
212                         preparelist(value_list);                /* replace , between services with & to send the request */
213                         asprintf(&send_buffer,"%s&%u&%s&%s", req_password,(vars_to_check==CHECK_SERVICESTATE)?5:6,
214                                                          (show_all==TRUE)?_("ShowAll"):_("ShowFail"),value_list);
215                         fetch_data (server_address, server_port, send_buffer);
216                         return_code=atoi(strtok(recv_buffer,"&"));
217                         temp_string=strtok(NULL,"&");
218                         output_message = strdup (temp_string);
219                 }
220                 break;
222         case CHECK_MEMUSE:
223                 
224                 asprintf(&send_buffer,"%s&7", req_password);
225                 fetch_data (server_address, server_port, send_buffer);
226                 mem_commitLimit=atof(strtok(recv_buffer,"&"));
227                 mem_commitByte=atof(strtok(NULL,"&"));
228                 percent_used_space = (mem_commitByte / mem_commitLimit) * 100;
229                 asprintf(&output_message,_("Memory usage: total:%.2f Mb - used: %.2f Mb (%.0f%%) - free: %.2f Mb (%.0f%%)"), 
230                         mem_commitLimit / 1048576, mem_commitByte / 1048567, percent_used_space,  
231                         (mem_commitLimit - mem_commitByte) / 1048576, (mem_commitLimit - mem_commitByte) / mem_commitLimit * 100);
232         
233                 if(check_critical_value==TRUE && percent_used_space >= critical_value)
234                         return_code=STATE_CRITICAL;
235                 else if (check_warning_value==TRUE && percent_used_space >= warning_value)
236                         return_code=STATE_WARNING;      
237                 else
238                         return_code=STATE_OK;   
240                 break;
242         case CHECK_COUNTER:
244                 if (value_list==NULL)
245                         output_message = strdup (_("No counter specified"));
246                 else {
247                         preparelist(value_list);                /* replace , between services with & to send the request */
248                         asprintf(&send_buffer,"%s&8&%s", req_password,value_list);
249                         fetch_data (server_address, server_port, send_buffer);
250                         strtok(value_list,"&");                 /* burn the first parameters */
251                         description = strtok(NULL,"&");
252                         counter_value = atof(recv_buffer);
254                         if (description == NULL) 
255                                 asprintf(&output_message, "%.f", counter_value);
256                         else
257                                 asprintf(&output_message,"%s = %.f",  description, counter_value);
258         
259                         if (critical_value > warning_value) {        /* Normal thresholds */
260                                 if(check_critical_value==TRUE && counter_value >= critical_value)
261                                         return_code=STATE_CRITICAL;
262                                 else if (check_warning_value==TRUE && counter_value >= warning_value)
263                                         return_code=STATE_WARNING;      
264                                 else
265                                         return_code=STATE_OK;   
266                         } 
267                         else {                                       /* inverse thresholds */
268                                 if(check_critical_value==TRUE && counter_value <= critical_value)
269                                         return_code=STATE_CRITICAL;
270                                 else if (check_warning_value==TRUE && counter_value <= warning_value)
271                                         return_code=STATE_WARNING;      
272                                 else
273                                         return_code=STATE_OK;   
274                         }       
275                 }
276                 break;
278         case CHECK_FILEAGE:
280                 if (value_list==NULL)
281                         output_message = strdup (_("No counter specified"));
282                 else {
283                         preparelist(value_list);                /* replace , between services with & to send the request */
284                         asprintf(&send_buffer,"%s&9&%s", req_password,value_list);
285                         fetch_data (server_address, server_port, send_buffer);
286                         age_in_minutes = atoi(strtok(recv_buffer,"&"));
287                         description = strtok(NULL,"&");
288                         output_message = strdup (description);
289         
290                         if (critical_value > warning_value) {        /* Normal thresholds */
291                                 if(check_critical_value==TRUE && age_in_minutes >= critical_value)
292                                         return_code=STATE_CRITICAL;
293                                 else if (check_warning_value==TRUE && age_in_minutes >= warning_value)
294                                         return_code=STATE_WARNING;      
295                                 else
296                                         return_code=STATE_OK;   
297                         } 
298                         else {                                       /* inverse thresholds */
299                                 if(check_critical_value==TRUE && age_in_minutes <= critical_value)
300                                         return_code=STATE_CRITICAL;
301                                 else if (check_warning_value==TRUE && age_in_minutes <= warning_value)
302                                         return_code=STATE_WARNING;      
303                                 else
304                                         return_code=STATE_OK;   
305                         }
306                 }
307                 break;
309         case CHECK_NONE:
310         default:
311                 usage (_(""));
312                 break;
314         }
316         /* reset timeout */
317         alarm(0);
319         printf("%s\n",output_message);
321         return return_code;
328 \f
329 /* process command-line arguments */
330 int process_arguments(int argc, char **argv){
331         int c;
333         int option = 0;
334         static struct option longopts[] =
335         { 
336                 {"port",     required_argument,0,'p'},
337                 {"timeout",  required_argument,0,'t'},
338                 {"critical", required_argument,0,'c'},
339                 {"warning",  required_argument,0,'w'},
340                 {"variable", required_argument,0,'v'},
341                 {"hostname", required_argument,0,'H'},
342                 {"version",  no_argument,      0,'V'},
343                 {"help",     no_argument,      0,'h'},
344                 {0,0,0,0}
345         };
347         /* no options were supplied */
348         if(argc<2) return ERROR;
350         /* backwards compatibility */
351         if (! is_option(argv[1])) {
352                 server_address = strdup(argv[1]);
353                 argv[1]=argv[0];
354                 argv=&argv[1];
355                 argc--;
356         }
358   for (c=1;c<argc;c++) {
359     if(strcmp("-to",argv[c])==0)
360       strcpy(argv[c],"-t");
361     else if (strcmp("-wv",argv[c])==0)
362       strcpy(argv[c],"-w");
363     else if (strcmp("-cv",argv[c])==0)
364       strcpy(argv[c],"-c");
365         }
367         while (1){
368                 c = getopt_long(argc,argv,"+hVH:t:c:w:p:v:l:s:d:",longopts,&option);
370                 if (c==-1||c==EOF||c==1)
371                         break;
373                 switch (c)
374                         {
375                         case '?': /* print short usage statement if args not parsable */
376                                 printf("%s: Unknown argument: %s\n\n",progname,optarg);
377                                 print_usage();
378                                 exit(STATE_UNKNOWN);
379                         case 'h': /* help */
380                                 print_help();
381                                 exit(STATE_OK);
382                         case 'V': /* version */
383                                 print_revision(progname,"$Revision$");
384                                 exit(STATE_OK);
385                         case 'H': /* hostname */
386                                 if (server_address)     free(server_address);
387                                 server_address = optarg;
388                                 break;
389                         case 's': /* password */
390                                 req_password = optarg;
391                                 break;
392                         case 'p': /* port */
393                                 if (is_intnonneg(optarg))
394                                         server_port=atoi(optarg);
395                                 else
396                                         die(STATE_UNKNOWN,_("Server port an integer (seconds)\nType '%s -h' for additional help\n"),progname);
397                                 break;
398                         case 'v':
399                                 if(strlen(optarg)<4)
400                                         return ERROR;
401                                 if(!strcmp(optarg,"CLIENTVERSION"))
402                                         vars_to_check=CHECK_CLIENTVERSION;
403                                 else if(!strcmp(optarg,"CPULOAD"))
404                                         vars_to_check=CHECK_CPULOAD;
405                                 else if(!strcmp(optarg,"UPTIME"))
406                                         vars_to_check=CHECK_UPTIME;
407                                 else if(!strcmp(optarg,"USEDDISKSPACE"))
408                                         vars_to_check=CHECK_USEDDISKSPACE;
409                                 else if(!strcmp(optarg,"SERVICESTATE"))
410                                         vars_to_check=CHECK_SERVICESTATE;
411                                 else if(!strcmp(optarg,"PROCSTATE"))
412                                         vars_to_check=CHECK_PROCSTATE;
413                                 else if(!strcmp(optarg,"MEMUSE"))
414                                         vars_to_check=CHECK_MEMUSE;
415                                 else if(!strcmp(optarg,"COUNTER"))
416                                         vars_to_check=CHECK_COUNTER;
417                                 else if(!strcmp(optarg,"FILEAGE"))
418                                         vars_to_check=CHECK_FILEAGE;
419                                 else
420                                         return ERROR;
421                                 break;
422                         case 'l': /* value list */
423                                 value_list = optarg;
424                                 break;
425                         case 'w': /* warning threshold */
426                                 warning_value=strtoul(optarg,NULL,10);
427                                 check_warning_value=TRUE;
428                                 break;
429                         case 'c': /* critical threshold */
430                                 critical_value=strtoul(optarg,NULL,10);
431                                 check_critical_value=TRUE;
432                                 break;
433                         case 'd': /* Display select for services */
434                                 if (!strcmp(optarg,"SHOWALL"))
435                                         show_all = TRUE;
436                                 break;
437                         case 't': /* timeout */
438                                 socket_timeout=atoi(optarg);
439                                 if(socket_timeout<=0)
440                                         return ERROR;
441                         }
443         }
445         if (vars_to_check==CHECK_NONE)
446                 return ERROR;
448         if (req_password == NULL)
449                 req_password = strdup (_("None"));
451         return OK;
458 \f
459 void fetch_data (const char *address, int port, const char *sendb) {
460         int result;
462         result=process_tcp_request(address, port, sendb, recv_buffer,sizeof(recv_buffer));
464         if(result!=STATE_OK)
465                 die (result, "could not fetch information from server\n");
466                 
467         if (!strncmp(recv_buffer,"ERROR",5))
468                 die (STATE_UNKNOWN, "NSClient - %s\n",recv_buffer);
471 int strtoularray(unsigned long *array, char *string, const char *delim) {
472         /* split a <delim> delimited string into a long array */
473         int idx=0;
474         char *t1;
476         for (idx=0;idx<MAX_VALUE_LIST;idx++)
477                 array[idx]=0;
478         
479         idx=0;
480         for(t1 = strtok(string,delim);t1 != NULL; t1 = strtok(NULL, delim)) {
481                 if (is_numeric(t1) && idx<MAX_VALUE_LIST) {
482                         array[idx]=strtoul(t1,NULL,10);
483                         idx++;
484                 } else  
485                         return FALSE;
486         }               
487         return TRUE;
490 void preparelist(char *string) {
491         /* Replace all , with & which is the delimiter for the request */
492         int i;
494         for (i = 0; (size_t)i < strlen(string); i++)
495                 if (string[i] == ',') {
496                         string[i]='&';
497                 }
504 \f
505 void print_help(void)
507         print_revision(progname,"$Revision$");
508         printf (_("\
509 Copyright (c) 2000 Yves Rubin (rubiyz@yahoo.com)\n\n\
510 This plugin collects data from the NSClient service running on a\n\
511 Windows NT/2000/XP server.\n\n"));
512         print_usage();
513   printf (_("\nOptions:\n\
514 -H, --hostname=HOST\n\
515   Name of the host to check\n\
516 -p, --port=INTEGER\n\
517   Optional port number (default: %d)\n\
518 -s <password>\n\
519   Password needed for the request\n\
520 -w, --warning=INTEGER\n\
521   Threshold which will result in a warning status\n\
522 -c, --critical=INTEGER\n\
523   Threshold which will result in a critical status\n\
524 -t, --timeout=INTEGER\n\
525   Seconds before connection attempt times out (default: %d)\n\
526 -h, --help\n\
527   Print this help screen\n\
528 -V, --version\n\
529   Print version information\n"),
530                 PORT, DEFAULT_SOCKET_TIMEOUT);
531   printf (_("\
532 -v, --variable=STRING\n\
533   Variable to check.  Valid variables are:\n"));
534   printf (_("\
535    CLIENTVERSION = Get the NSClient version\n"));
536   printf (_("\
537    CPULOAD = Average CPU load on last x minutes.\n\
538      Request a -l parameter with the following syntax:\n\
539      -l <minutes range>,<warning threshold>,<critical threshold>.\n\
540      <minute range> should be less than 24*60.\n\
541      Thresholds are percentage and up to 10 requests can be done in one shot.\n\
542      ie: -l 60,90,95,120,90,95\n"));
543   printf (_("\
544    UPTIME = Get the uptime of the machine.\n\
545      No specific parameters. No warning or critical threshold\n"));
546   printf (_("\
547    USEDDISKSPACE = Size and percentage of disk use.\n\
548      Request a -l parameter containing the drive letter only.\n\
549      Warning and critical thresholds can be specified with -w and -c.\n"));
550   printf (_("\
551    MEMUSE = Memory use.\n\
552      Warning and critical thresholds can be specified with -w and -c.\n"));
553   printf (_("\
554    SERVICESTATE = Check the state of one or several services.\n\
555      Request a -l parameters with the following syntax:\n\
556      -l <service1>,<service2>,<service3>,...\n\
557      You can specify -d SHOWALL in case you want to see working services\n\
558                  in the returned string.\n"));
559   printf (_("\
560    PROCSTATE = Check if one or several process are running.\n\
561      Same syntax as SERVICESTATE.\n"));
562   printf (_("\
563    COUNTER = Check any performance counter of Windows NT/2000.\n\
564      Request a -l parameters with the following syntax:\n\
565                  -l \"\\\\<performance object>\\\\counter\",\"<description>\n\
566      The <description> parameter is optional and \n\
567      is given to a printf output command which require a float parameters.\n\
568      Some examples:\n\
569        \"Paging file usage is %%.2f %%%%\"\n\
570        \"%%.f %%%% paging file used.\"\n"));
571         printf (_("Notes:\n\
572  - The NSClient service should be running on the server to get any information\n\
573    (http://nsclient.ready2run.nl).\n\
574  - Critical thresholds should be lower than warning thresholds\n"));
580 void print_usage(void)
582         printf(_("\
583 Usage: %s -H host -v variable [-p port] [-w warning] [-c critical]\n\
584   [-l params] [-d SHOWALL] [-t timeout]\n"), progname);
585         printf (_(UT_HLP_VRS), progname, progname);