Code

Command line argument bug (Howard Wilkinson)
[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_warning_value=FALSE;
62 int check_critical_value=FALSE;
63 enum checkvars vars_to_check = CHECK_NONE;
64 int show_all=FALSE;
66 const char *progname = "check_nt";
68 char recv_buffer[MAX_INPUT_BUFFER];
70 void fetch_data (const char* address, int port, const char* sendb);
71 int process_arguments(int, char **);
72 void preparelist(char *string);
73 int strtoularray(unsigned long *array, char *string, const char *delim);
74 void print_help(void);
75 void print_usage(void);
77 int main(int argc, char **argv){
78         int return_code = STATE_UNKNOWN;
79         char *send_buffer=NULL;
80         char *output_message=NULL;
81         char *temp_string=NULL;
82         char *description=NULL;
84         double total_disk_space=0;
85         double free_disk_space=0;
86         double percent_used_space=0;
87         double mem_commitLimit=0;
88         double mem_commitByte=0;
89         unsigned long utilization;
90         unsigned long uptime;
91         unsigned long age_in_minutes;
92         double counter_value;
93         int offset=0;
94         int updays=0;
95         int uphours=0;
96         int upminutes=0;
98         setlocale (LC_ALL, "");
99         bindtextdomain (PACKAGE, LOCALEDIR);
100         textdomain (PACKAGE);
102         if(process_arguments(argc,argv)==ERROR)
103                 usage(_("Could not parse arguments\n"));
105         /* initialize alarm signal handling */
106         signal(SIGALRM,socket_timeout_alarm_handler);
108         /* set socket timeout */
109         alarm(socket_timeout);
111         switch (vars_to_check) {
113         case CHECK_CLIENTVERSION:
115                 asprintf(&send_buffer, "%s&1", req_password);
116                 fetch_data (server_address, server_port, send_buffer);
117                 if (value_list != NULL && strcmp(recv_buffer, value_list) != 0) {
118                         asprintf (&output_message, _("Wrong client version - running: %s, required: %s"), recv_buffer, value_list);
119                         return_code = STATE_WARNING;
120                 } else {
121                         asprintf (&output_message, "%s", recv_buffer);
122                         return_code = STATE_OK;
123                 }
124                 break;
126         case CHECK_CPULOAD:
128                 if (value_list==NULL)
129                         output_message = strdup (_("missing -l parameters"));
130                 else if (strtoularray(lvalue_list,value_list,",")==FALSE)
131                         output_message = strdup (_("wrong -l parameter."));
132                 else {
133                         /* -l parameters is present with only integers */
134                         return_code=STATE_OK;
135                         temp_string = strdup (_("CPU Load"));
136                         /* loop until one of the parameters is wrong or not present */
137                         while (lvalue_list[0+offset]> (unsigned long)0 &&
138                                                  lvalue_list[0+offset]<=(unsigned long)17280 && 
139                                                  lvalue_list[1+offset]> (unsigned long)0 &&
140                                                  lvalue_list[1+offset]<=(unsigned long)100 && 
141                                                  lvalue_list[2+offset]> (unsigned long)0 &&
142                                                  lvalue_list[2+offset]<=(unsigned long)100) {
144                                 /* Send request and retrieve data */
145                                 asprintf(&send_buffer,"%s&2&%lu",req_password,lvalue_list[0+offset]);
146                                 fetch_data (server_address, server_port, send_buffer);
148                                 utilization=strtoul(recv_buffer,NULL,10);
149                                 
150                                 /* Check if any of the request is in a warning or critical state */
151                                 if(utilization >= lvalue_list[2+offset])
152                                         return_code=STATE_CRITICAL;
153                                 else if(utilization >= lvalue_list[1+offset] && return_code<STATE_WARNING)
154                                         return_code=STATE_WARNING;
156                                 asprintf(&output_message,_(" %lu%% (%lu min average)"), utilization, lvalue_list[0+offset]);
157                                 asprintf(&temp_string,"%s%s",temp_string,output_message);
158                                 offset+=3;      /* move across the array */
159                         }
160                         if (strlen(temp_string)>10)  /* we had at least one loop */
161                                 output_message = strdup (temp_string);
162                         else
163                                 output_message = strdup (_("not enough values for -l parameters"));
164                 }       
165                 break;
167         case CHECK_UPTIME:
169                 asprintf(&send_buffer, "%s&3", req_password);
170                 fetch_data (server_address, server_port, send_buffer);
171                 uptime=strtoul(recv_buffer,NULL,10);
172                 updays = uptime / 86400;                        
173                 uphours = (uptime % 86400) / 3600;
174                 upminutes = ((uptime % 86400) % 3600) / 60;
175                 asprintf(&output_message,_("System Uptime : %u day(s) %u hour(s) %u minute(s)"),updays,uphours, upminutes);
176                 return_code=STATE_OK;
177                 break;
179         case CHECK_USEDDISKSPACE:
181                 if (value_list==NULL)
182                         output_message = strdup (_("missing -l parameters"));
183                 else if (strlen(value_list)!=1)
184                         output_message = strdup (_("wrong -l argument"));
185                 else {
186                         asprintf(&send_buffer,"%s&4&%s", req_password, value_list);
187                         fetch_data (server_address, server_port, send_buffer);
188                         free_disk_space=atof(strtok(recv_buffer,"&"));
189                         total_disk_space=atof(strtok(NULL,"&"));
190                         percent_used_space = ((total_disk_space - free_disk_space) / total_disk_space) * 100;
192                         if (free_disk_space>=0) {
193                                 asprintf(&temp_string,_("%s:\\ - total: %.2f Gb - used: %.2f Gb (%.0f%%) - free %.2f Gb (%.0f%%)"),
194                                                                  value_list, total_disk_space / 1073741824, (total_disk_space - free_disk_space) / 1073741824, percent_used_space,
195                                                                  free_disk_space / 1073741824, (free_disk_space / total_disk_space)*100); 
198                                 if(check_critical_value==TRUE && percent_used_space >= critical_value)
199                                         return_code=STATE_CRITICAL;
200                                 else if (check_warning_value==TRUE && percent_used_space >= warning_value)
201                                         return_code=STATE_WARNING;      
202                                 else
203                                         return_code=STATE_OK;   
205                                 output_message = strdup (temp_string);
206                         }
207                         else {
208                                 output_message = strdup (_("Free disk space : Invalid drive "));
209                                 return_code=STATE_UNKNOWN;
210                         }
211                 }
212                 break;
214         case CHECK_SERVICESTATE:
215         case CHECK_PROCSTATE:
217                 if (value_list==NULL)
218                         output_message = strdup (_("No service/process specified"));
219                 else {
220                         preparelist(value_list);                /* replace , between services with & to send the request */
221                         asprintf(&send_buffer,"%s&%u&%s&%s", req_password,(vars_to_check==CHECK_SERVICESTATE)?5:6,
222                                                          (show_all==TRUE)?_("ShowAll"):_("ShowFail"),value_list);
223                         fetch_data (server_address, server_port, send_buffer);
224                         return_code=atoi(strtok(recv_buffer,"&"));
225                         temp_string=strtok(NULL,"&");
226                         output_message = strdup (temp_string);
227                 }
228                 break;
230         case CHECK_MEMUSE:
231                 
232                 asprintf(&send_buffer,"%s&7", req_password);
233                 fetch_data (server_address, server_port, send_buffer);
234                 mem_commitLimit=atof(strtok(recv_buffer,"&"));
235                 mem_commitByte=atof(strtok(NULL,"&"));
236                 percent_used_space = (mem_commitByte / mem_commitLimit) * 100;
237                 asprintf(&output_message,_("Memory usage: total:%.2f Mb - used: %.2f Mb (%.0f%%) - free: %.2f Mb (%.0f%%)"), 
238                         mem_commitLimit / 1048576, mem_commitByte / 1048567, percent_used_space,  
239                         (mem_commitLimit - mem_commitByte) / 1048576, (mem_commitLimit - mem_commitByte) / mem_commitLimit * 100);
240         
241                 return_code=STATE_OK;
242                 if(check_critical_value==TRUE && percent_used_space >= critical_value)
243                         return_code=STATE_CRITICAL;
244                 else if (check_warning_value==TRUE && percent_used_space >= warning_value)
245                         return_code=STATE_WARNING;      
247                 break;
249         case CHECK_COUNTER:
251                 if (value_list==NULL)
252                         output_message = strdup (_("No counter specified"));
253                 else {
254                         preparelist(value_list);                /* replace , between services with & to send the request */
255                         asprintf(&send_buffer,"%s&8&%s", req_password,value_list);
256                         fetch_data (server_address, server_port, send_buffer);
257                         strtok(value_list,"&");                 /* burn the first parameters */
258                         description = strtok(NULL,"&");
259                         counter_value = atof(recv_buffer);
261                         if (description == NULL) 
262                                 asprintf(&output_message, "%.f", counter_value);
263                         else
264                                 asprintf(&output_message,"%s = %.f",  description, counter_value);
265         
266                         if (critical_value > warning_value) {        /* Normal thresholds */
267                                 if(check_critical_value==TRUE && counter_value >= critical_value)
268                                         return_code=STATE_CRITICAL;
269                                 else if (check_warning_value==TRUE && counter_value >= warning_value)
270                                         return_code=STATE_WARNING;      
271                                 else
272                                         return_code=STATE_OK;   
273                         } 
274                         else {                                       /* inverse thresholds */
275                                 return_code=STATE_OK;
276                                 if(check_critical_value==TRUE && counter_value <= critical_value)
277                                         return_code=STATE_CRITICAL;
278                                 else if (check_warning_value==TRUE && counter_value <= warning_value)
279                                         return_code=STATE_WARNING;      
280                         }
281                 }
282                 break;
284         case CHECK_FILEAGE:
286                 if (value_list==NULL)
287                         output_message = strdup (_("No counter specified"));
288                 else {
289                         preparelist(value_list);                /* replace , between services with & to send the request */
290                         asprintf(&send_buffer,"%s&9&%s", req_password,value_list);
291                         fetch_data (server_address, server_port, send_buffer);
292                         age_in_minutes = atoi(strtok(recv_buffer,"&"));
293                         description = strtok(NULL,"&");
294                         output_message = strdup (description);
295         
296                         if (critical_value > warning_value) {        /* Normal thresholds */
297                                 if(check_critical_value==TRUE && age_in_minutes >= critical_value)
298                                         return_code=STATE_CRITICAL;
299                                 else if (check_warning_value==TRUE && age_in_minutes >= warning_value)
300                                         return_code=STATE_WARNING;      
301                                 else
302                                         return_code=STATE_OK;   
303                         } 
304                         else {                                       /* inverse thresholds */
305                                 if(check_critical_value==TRUE && age_in_minutes <= critical_value)
306                                         return_code=STATE_CRITICAL;
307                                 else if (check_warning_value==TRUE && age_in_minutes <= warning_value)
308                                         return_code=STATE_WARNING;      
309                                 else
310                                         return_code=STATE_OK;   
311                         }
312                 }
313                 break;
315         case CHECK_NONE:
316         default:
317                 usage (_("Please specify a variable to check"));
318                 break;
320         }
322         /* reset timeout */
323         alarm(0);
325         printf("%s\n",output_message);
327         return return_code;
334 \f
335 /* process command-line arguments */
336 int process_arguments(int argc, char **argv){
337         int c;
339         int option = 0;
340         static struct option longopts[] =
341         { 
342                 {"port",     required_argument,0,'p'},
343                 {"timeout",  required_argument,0,'t'},
344                 {"critical", required_argument,0,'c'},
345                 {"warning",  required_argument,0,'w'},
346                 {"variable", required_argument,0,'v'},
347                 {"hostname", required_argument,0,'H'},
348                 {"version",  no_argument,      0,'V'},
349                 {"help",     no_argument,      0,'h'},
350                 {0,0,0,0}
351         };
353         /* no options were supplied */
354         if(argc<2) return ERROR;
356         /* backwards compatibility */
357         if (! is_option(argv[1])) {
358                 server_address = strdup(argv[1]);
359                 argv[1]=argv[0];
360                 argv=&argv[1];
361                 argc--;
362         }
364   for (c=1;c<argc;c++) {
365     if(strcmp("-to",argv[c])==0)
366       strcpy(argv[c],"-t");
367     else if (strcmp("-wv",argv[c])==0)
368       strcpy(argv[c],"-w");
369     else if (strcmp("-cv",argv[c])==0)
370       strcpy(argv[c],"-c");
371         }
373         while (1){
374                 c = getopt_long(argc,argv,"+hVH:t:c:w:p:v:l:s:d:",longopts,&option);
376                 if (c==-1||c==EOF||c==1)
377                         break;
379                 switch (c)
380                         {
381                         case '?': /* print short usage statement if args not parsable */
382                                 printf("%s: Unknown argument: %s\n\n",progname,optarg);
383                                 print_usage();
384                                 exit(STATE_UNKNOWN);
385                         case 'h': /* help */
386                                 print_help();
387                                 exit(STATE_OK);
388                         case 'V': /* version */
389                                 print_revision(progname,"$Revision$");
390                                 exit(STATE_OK);
391                         case 'H': /* hostname */
392                                 if (server_address)     free(server_address);
393                                 server_address = optarg;
394                                 break;
395                         case 's': /* password */
396                                 req_password = optarg;
397                                 break;
398                         case 'p': /* port */
399                                 if (is_intnonneg(optarg))
400                                         server_port=atoi(optarg);
401                                 else
402                                         die(STATE_UNKNOWN,_("Server port an integer (seconds)\nType '%s -h' for additional help\n"),progname);
403                                 break;
404                         case 'v':
405                                 if(strlen(optarg)<4)
406                                         return ERROR;
407                                 if(!strcmp(optarg,"CLIENTVERSION"))
408                                         vars_to_check=CHECK_CLIENTVERSION;
409                                 else if(!strcmp(optarg,"CPULOAD"))
410                                         vars_to_check=CHECK_CPULOAD;
411                                 else if(!strcmp(optarg,"UPTIME"))
412                                         vars_to_check=CHECK_UPTIME;
413                                 else if(!strcmp(optarg,"USEDDISKSPACE"))
414                                         vars_to_check=CHECK_USEDDISKSPACE;
415                                 else if(!strcmp(optarg,"SERVICESTATE"))
416                                         vars_to_check=CHECK_SERVICESTATE;
417                                 else if(!strcmp(optarg,"PROCSTATE"))
418                                         vars_to_check=CHECK_PROCSTATE;
419                                 else if(!strcmp(optarg,"MEMUSE"))
420                                         vars_to_check=CHECK_MEMUSE;
421                                 else if(!strcmp(optarg,"COUNTER"))
422                                         vars_to_check=CHECK_COUNTER;
423                                 else if(!strcmp(optarg,"FILEAGE"))
424                                         vars_to_check=CHECK_FILEAGE;
425                                 else
426                                         return ERROR;
427                                 break;
428                         case 'l': /* value list */
429                                 value_list = optarg;
430                                 break;
431                         case 'w': /* warning threshold */
432                                 warning_value=strtoul(optarg,NULL,10);
433                                 check_warning_value=TRUE;
434                                 break;
435                         case 'c': /* critical threshold */
436                                 critical_value=strtoul(optarg,NULL,10);
437                                 check_critical_value=TRUE;
438                                 break;
439                         case 'd': /* Display select for services */
440                                 if (!strcmp(optarg,"SHOWALL"))
441                                         show_all = TRUE;
442                                 break;
443                         case 't': /* timeout */
444                                 socket_timeout=atoi(optarg);
445                                 if(socket_timeout<=0)
446                                         return ERROR;
447                         }
449         }
451         if (vars_to_check==CHECK_NONE)
452                 return ERROR;
454         if (req_password == NULL)
455                 req_password = strdup (_("None"));
457         return OK;
464 \f
465 void fetch_data (const char *address, int port, const char *sendb) {
466         int result;
468         result=process_tcp_request(address, port, sendb, recv_buffer,sizeof(recv_buffer));
470         if(result!=STATE_OK)
471                 die (result, "could not fetch information from server\n");
472                 
473         if (!strncmp(recv_buffer,"ERROR",5))
474                 die (STATE_UNKNOWN, "NSClient - %s\n",recv_buffer);
477 int strtoularray(unsigned long *array, char *string, const char *delim) {
478         /* split a <delim> delimited string into a long array */
479         int idx=0;
480         char *t1;
482         for (idx=0;idx<MAX_VALUE_LIST;idx++)
483                 array[idx]=0;
484         
485         idx=0;
486         for(t1 = strtok(string,delim);t1 != NULL; t1 = strtok(NULL, delim)) {
487                 if (is_numeric(t1) && idx<MAX_VALUE_LIST) {
488                         array[idx]=strtoul(t1,NULL,10);
489                         idx++;
490                 } else  
491                         return FALSE;
492         }               
493         return TRUE;
496 void preparelist(char *string) {
497         /* Replace all , with & which is the delimiter for the request */
498         int i;
500         for (i = 0; (size_t)i < strlen(string); i++)
501                 if (string[i] == ',') {
502                         string[i]='&';
503                 }
510 \f
511 void print_help(void)
513         print_revision(progname,"$Revision$");
514         printf (_("\
515 Copyright (c) 2000 Yves Rubin (rubiyz@yahoo.com)\n\n\
516 This plugin collects data from the NSClient service running on a\n\
517 Windows NT/2000/XP server.\n\n"));
518         print_usage();
519   printf (_("\nOptions:\n\
520 -H, --hostname=HOST\n\
521   Name of the host to check\n\
522 -p, --port=INTEGER\n\
523   Optional port number (default: %d)\n\
524 -s <password>\n\
525   Password needed for the request\n\
526 -w, --warning=INTEGER\n\
527   Threshold which will result in a warning status\n\
528 -c, --critical=INTEGER\n\
529   Threshold which will result in a critical status\n\
530 -t, --timeout=INTEGER\n\
531   Seconds before connection attempt times out (default: %d)\n\
532 -h, --help\n\
533   Print this help screen\n\
534 -V, --version\n\
535   Print version information\n"),
536                 PORT, DEFAULT_SOCKET_TIMEOUT);
537   printf (_("\
538 -v, --variable=STRING\n\
539   Variable to check.  Valid variables are:\n"));
540   printf (_("\
541    CLIENTVERSION = Get the NSClient version\n\
542      If -l <version> is specified, will return warning if versions differ.\n"));
543   printf (_("\
544    CPULOAD = Average CPU load on last x minutes.\n\
545      Request a -l parameter with the following syntax:\n\
546      -l <minutes range>,<warning threshold>,<critical threshold>.\n\
547      <minute range> should be less than 24*60.\n\
548      Thresholds are percentage and up to 10 requests can be done in one shot.\n\
549      ie: -l 60,90,95,120,90,95\n"));
550   printf (_("\
551    UPTIME = Get the uptime of the machine.\n\
552      No specific parameters. No warning or critical threshold\n"));
553   printf (_("\
554    USEDDISKSPACE = Size and percentage of disk use.\n\
555      Request a -l parameter containing the drive letter only.\n\
556      Warning and critical thresholds can be specified with -w and -c.\n"));
557   printf (_("\
558    MEMUSE = Memory use.\n\
559      Warning and critical thresholds can be specified with -w and -c.\n"));
560   printf (_("\
561    SERVICESTATE = Check the state of one or several services.\n\
562      Request a -l parameters with the following syntax:\n\
563      -l <service1>,<service2>,<service3>,...\n\
564      You can specify -d SHOWALL in case you want to see working services\n\
565                  in the returned string.\n"));
566   printf (_("\
567    PROCSTATE = Check if one or several process are running.\n\
568      Same syntax as SERVICESTATE.\n"));
569   printf (_("\
570    COUNTER = Check any performance counter of Windows NT/2000.\n\
571      Request a -l parameters with the following syntax:\n\
572                  -l \"\\\\<performance object>\\\\counter\",\"<description>\n\
573      The <description> parameter is optional and \n\
574      is given to a printf output command which require a float parameters.\n\
575      Some examples:\n\
576        \"Paging file usage is %%.2f %%%%\"\n\
577        \"%%.f %%%% paging file used.\"\n"));
578         printf (_("Notes:\n\
579  - The NSClient service should be running on the server to get any information\n\
580    (http://nsclient.ready2run.nl).\n\
581  - Critical thresholds should be lower than warning thresholds\n"));
587 void print_usage(void)
589         printf(_("\
590 Usage: %s -H host -v variable [-p port] [-w warning] [-c critical]\n\
591   [-l params] [-d SHOWALL] [-t timeout]\n"), progname);
592         printf (_(UT_HLP_VRS), progname, progname);