int validate_arguments (char **command_line) { if (command_line[0] == NULL) usage4 (_("Could not parse arguments")); if (strncmp(command_line[0],"/",1) != 0 && strncmp(command_line[0],"./",2) != 0) usage4 (_("Require path to command")); }
int main (int argc, char **argv) { int elapsed_time; int status = STATE_UNKNOWN; /* begin, by setting the parameters for a backend connection if the * parameters are null, then the system will try to use reasonable * defaults by looking up environment variables or, failing that, * using hardwired constants */ pgoptions = NULL; /* special options to start up the backend server */ pgtty = NULL; /* debugging tty for the backend server */ setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); if (process_arguments (argc, argv) == ERROR) usage4 (_("Could not parse arguments")); /* Set signal handling and alarm */ if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) { usage4 (_("Cannot catch SIGALRM")); } alarm (timeout_interval); /* make a connection to the database */ time (&start_time); conn = PQsetdbLogin (pghost, pgport, pgoptions, pgtty, dbName, pguser, pgpasswd); time (&end_time); elapsed_time = (int) (end_time - start_time); /* check to see that the backend connection was successfully made */ if (PQstatus (conn) == CONNECTION_BAD) { printf (_("CRITICAL - no connection to '%s' (%s).\n"), dbName, PQerrorMessage (conn)); PQfinish (conn); return STATE_CRITICAL; } else if (elapsed_time > tcrit) { status = STATE_CRITICAL; } else if (elapsed_time > twarn) { status = STATE_WARNING; } else { status = STATE_OK; } PQfinish (conn); printf (_(" %s - database %s (%d sec.)|%s\n"), state_text(status), dbName, elapsed_time, fperfdata("time", elapsed_time, "s", (int)twarn, twarn, (int)tcrit, tcrit, TRUE, 0, FALSE,0)); return status; }
/* process command-line arguments */ int process_arguments (int argc, char **argv) { int c; int option = 0; static struct option longopts[] = { {"critical", required_argument, 0, 'c'}, {"warning", required_argument, 0, 'w'}, {"version", no_argument, 0, 'V'}, {"help", no_argument, 0, 'h'}, {0, 0, 0, 0} }; if (argc < 2) usage ("\n"); while (1) { c = getopt_long (argc, argv, "+hVvc:w:", longopts, &option); if (c == -1 || c == EOF || c == 1) break; switch (c) { case '?': /* print short usage statement if args not parsable */ usage5 (); case 'h': /* help */ print_help (); exit (STATE_UNKNOWN); case 'V': /* version */ print_revision (progname, NP_VERSION); exit (STATE_UNKNOWN); case 'c': /* critical */ critical_range = optarg; break; case 'w': /* warning */ warning_range = optarg; break; } } c = optind; if (warning_range == NULL && argc > c) warning_range = argv[c++]; if (critical_range == NULL && argc > c) critical_range = argv[c++]; /* this will abort in case of invalid ranges */ set_thresholds (&thlds, warning_range, critical_range); if (thlds->warning->end < 0) usage4 (_("Warning threshold must be a positive integer")); if (thlds->critical->end < 0) usage4 (_("Critical threshold must be a positive integer")); return OK; }
int validate_arguments () { if (ld_host==NULL || strlen(ld_host)==0) usage4 (_("Please specify the host name\n")); if (ld_base==NULL) usage4 (_("Please specify the LDAP base\n")); return OK; }
int validate_arguments () { if ((ld_host==NULL || strlen(ld_host)==0) && (ld_uri==NULL || strlen(ld_uri)==0)) usage4 (_("Please specify the host name or LDAP URI\n")); if (ld_base==NULL) usage4 (_("Please specify the LDAP base DN\n")); return OK; }
int main (int argc, char **argv) { int result = STATE_UNKNOWN; setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); if (argc < 2) usage4 (_("Could not parse arguments")); else if (strcmp (argv[1], "-V") == 0 || strcmp (argv[1], "--version") == 0) { print_revision (progname, NP_VERSION); exit (STATE_OK); } else if (strcmp (argv[1], "-h") == 0 || strcmp (argv[1], "--help") == 0) { print_help (); exit (STATE_OK); } else if (!is_integer (argv[1])) usage4 (_("Arguments to check_dummy must be an integer")); else result = atoi (argv[1]); switch (result) { case STATE_OK: printf (_("OK")); break; case STATE_WARNING: printf (_("WARNING")); break; case STATE_CRITICAL: printf (_("CRITICAL")); break; case STATE_UNKNOWN: printf (_("UNKNOWN")); break; default: printf (_("UNKNOWN")); printf (": "); printf (_("Status %d is not a supported error state\n"), result); return STATE_UNKNOWN; } if (argc >= 3) printf (": %s", argv[2]); printf("\n"); return result; }
int validate_arguments () { if (ld_host==NULL || strlen(ld_host)==0) usage4 (_("Please specify the host name\n")); if (ld_base==NULL) usage4 (_("Please specify the LDAP base\n")); if (crit_entries!=NULL || warn_entries!=NULL) { set_thresholds(&entries_thresholds, warn_entries, crit_entries); } return OK; }
int main (int argc, char **argv) { int result = STATE_UNKNOWN; setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); /* Parse extra opts if any */ argv=np_extra_opts (&argc, argv, progname); if (process_arguments (argc, argv) == ERROR) usage4 (_("Could not parse arguments")); /* initialize alarm signal handling */ signal (SIGALRM, socket_timeout_alarm_handler); alarm (socket_timeout); /* ssh_connect exits if error is found */ result = ssh_connect (server_name, port, remote_version); alarm (0); return (result); }
int parse_timeout_string (char *timeout_str) { char *seperated_str; char *timeout_val = ""; char *timeout_sta = NULL; if ( strstr(timeout_str, ":" ) == NULL) { timeout_val = timeout_str; } else if ( strncmp(timeout_str, ":", 1 ) == 0) { seperated_str = strtok(timeout_str, ":"); if ( seperated_str != NULL ) { timeout_sta = seperated_str; } } else { seperated_str = strtok(timeout_str, ":"); timeout_val = seperated_str; seperated_str = strtok(NULL, ":"); if (seperated_str != NULL) { timeout_sta = seperated_str; } } if ( timeout_sta != NULL ) { set_timeout_state(timeout_sta); } if (( timeout_val == NULL ) || ( timeout_val[0] == '\0' )) { return timeout_interval; } else if (is_intpos(timeout_val)) { return atoi(timeout_val); } else { usage4 (_("Timeout value must be a positive integer")); exit (STATE_UNKNOWN); } }
int validate_arguments (void) { if (warn_percent == 0 && crit_percent == 0 && warn_size_bytes == 0 && crit_size_bytes == 0) { return ERROR; } else if (warn_percent < crit_percent) { usage4 (_("Warning percentage should be more than critical percentage")); } else if (warn_size_bytes < crit_size_bytes) { usage4 (_("Warning free space should be more than critical free space")); } return OK; }
int main(int argc, char *argv[]) { int result, offset_result; double offset=0; char *result_line, *perfdata_line; setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); result = offset_result = STATE_OK; /* Parse extra opts if any */ argv=np_extra_opts (&argc, argv, progname); if (process_arguments (argc, argv) == ERROR) usage4 (_("Could not parse arguments")); set_thresholds(&offset_thresholds, owarn, ocrit); /* initialize alarm signal handling */ signal (SIGALRM, socket_timeout_alarm_handler); /* set socket timeout */ alarm (socket_timeout); offset = offset_request(server_address, &offset_result); if (offset_result == STATE_UNKNOWN) { result = (quiet == 1 ? STATE_UNKNOWN : STATE_CRITICAL); } else { result = get_status(fabs(offset), offset_thresholds); } switch (result) { case STATE_CRITICAL : xasprintf(&result_line, _("NTP CRITICAL:")); break; case STATE_WARNING : xasprintf(&result_line, _("NTP WARNING:")); break; case STATE_OK : xasprintf(&result_line, _("NTP OK:")); break; default : xasprintf(&result_line, _("NTP UNKNOWN:")); break; } if(offset_result == STATE_UNKNOWN) { xasprintf(&result_line, "%s %s", result_line, _("Offset unknown")); xasprintf(&perfdata_line, ""); } else { xasprintf(&result_line, "%s %s %.10g secs", result_line, _("Offset"), offset); xasprintf(&perfdata_line, "%s", perfd_offset(offset)); } printf("%s|%s\n", result_line, perfdata_line); if(server_address!=NULL) free(server_address); return result; }
int main (int argc, char **argv) { // base values int status, intvalue; int upminutes, uphours, updays; double value, uptime; char* perf; char* output_message; /* Parse extra opts if any */ argv = np_extra_opts (&argc, argv, progname); if (process_arguments (argc, argv) == ERROR) usage4 (_("Could not parse arguments")); value = getuptime(); if (verbose >= 3) { printf("Uptime in seconds returned from timespec struct: %f\n", value); } intvalue = (int)value; updays = intvalue / 86400; uphours = (intvalue % 86400) / 3600; upminutes = ((intvalue % 86400) % 3600) / 60; if (!strncmp(timeunit, "minutes", strlen("minutes"))) { uptime = intvalue / 60; } else if (!strncmp(timeunit, "hours", strlen("hours"))) { uptime = intvalue / 3600; } else if (!strncmp(timeunit, "days", strlen("days"))) { uptime = intvalue / 86400; } else { uptime = intvalue; } xasprintf(&output_message,_("%u day(s) %u hour(s) %u minute(s)"), updays, uphours, upminutes); xasprintf(&perf,_("%s"), fperfdata("uptime", uptime, "", my_thresholds->warning?TRUE:FALSE, my_thresholds->warning?my_thresholds->warning->end:0, my_thresholds->critical?TRUE:FALSE, my_thresholds->critical?my_thresholds->critical->end:0, FALSE, 0, FALSE, 0) ); status = get_status(uptime, my_thresholds); if (status == STATE_OK) { printf("Uptime %s: %s | %s\n", _("OK"), output_message, perf); } else if (status == STATE_WARNING) { printf("Uptime %s: %s | %s\n", _("WARNING"), output_message, perf); } else if (status == STATE_CRITICAL) { printf("Uptime %s: %s | %s\n", _("CRITICAL"), output_message, perf); } return status; } // end main
int main (int argc, char **argv) { int users = -1; int result = STATE_UNKNOWN; char *perf; struct utmpx *putmpx; setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); perf = strdup (""); /* Parse extra opts if any */ argv = np_extra_opts (&argc, argv, progname); if (process_arguments (argc, argv) == ERROR) usage4 (_("Could not parse arguments")); users = 0; /* get currently logged users from utmpx */ setutxent (); while ((putmpx = getutxent ()) != NULL) if (putmpx->ut_type == USER_PROCESS) users++; endutxent (); /* check the user count against warning and critical thresholds */ if (users > cusers) result = STATE_CRITICAL; else if (users > wusers) result = STATE_WARNING; else if (users >= 0) result = STATE_OK; if (result == STATE_UNKNOWN) printf ("%s\n", _("Unable to read output")); else { asprintf (&perf, "%s", perfdata ("users", users, "", TRUE, wusers, TRUE, cusers, TRUE, 0, FALSE, 0)); printf (_("USERS %s - %d users currently logged in |%s\n"), state_text (result), users, perf); } return result; }
int validate_arguments (void) { if (variable_number == -1) usage4 (_("You must supply the variable number")); if (label == NULL) label = strdup ("value"); if (units == NULL) units = strdup (""); return OK; }
int main(int argc, char **argv){ int dhcp_socket; int result = STATE_UNKNOWN; setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); /* Parse extra opts if any */ argv=np_extra_opts(&argc, argv, progname); if(process_arguments(argc,argv)!=OK){ usage4 (_("Could not parse arguments")); } /* this plugin almost certainly needs root permissions. */ np_warn_if_not_root(); /* create socket for DHCP communications */ dhcp_socket=create_dhcp_socket(); /* get hardware address of client machine */ if(user_specified_mac!=NULL) memcpy(client_hardware_address,user_specified_mac,6); else get_hardware_address(dhcp_socket,network_interface_name); if(unicast) /* get IP address of client machine */ get_ip_address(dhcp_socket,network_interface_name); /* send DHCPDISCOVER packet */ send_dhcp_discover(dhcp_socket); /* wait for a DHCPOFFER packet */ get_dhcp_offer(dhcp_socket); /* close socket we created */ close_dhcp_socket(dhcp_socket); /* determine state/plugin output to return */ result=get_results(); /* free allocated memory */ free_dhcp_offer_list(); free_requested_server_list(); return result; }
int validate_arguments (void) { if (timeunit == NULL) { timeunit = "minutes"; if (verbose >= 3) { printf("No unit of time measurement specified. Using default: \"minutes\"\n"); } } else if (strncmp(timeunit, "seconds", strlen("seconds") + 1 ) && strncmp(timeunit, "minutes", strlen("minutes") + 1) && strncmp(timeunit, "hours", strlen("hours") + 1) && strncmp(timeunit, "days", strlen("days") + 1)) { if (verbose >= 3) { printf("Invalid unit of time measurement specified: \"%s\"\n", timeunit); } usage4(_("Wrong -u argument, expected: seconds, minutes, hours, or days")); } else if (verbose >= 3) { printf("Specified unit of time measurement accepted: \"%s\"\n", timeunit); } return OK; } //end validate
/* process command-line arguments */ int process_arguments (int argc, char **argv) { int c; char* temp; int option = 0; static struct option longopts[] = { {"hostname", required_argument, 0, 'H'}, {"expect", required_argument, 0, 'e'}, {"critical", required_argument, 0, 'c'}, {"warning", required_argument, 0, 'w'}, {"timeout", required_argument, 0, 't'}, {"port", required_argument, 0, 'p'}, {"from", required_argument, 0, 'f'}, {"fqdn", required_argument, 0, 'F'}, {"authtype", required_argument, 0, 'A'}, {"authuser", required_argument, 0, 'U'}, {"authpass", required_argument, 0, 'P'}, {"command", required_argument, 0, 'C'}, {"response", required_argument, 0, 'R'}, {"verbose", no_argument, 0, 'v'}, {"version", no_argument, 0, 'V'}, {"use-ipv4", no_argument, 0, '4'}, {"use-ipv6", no_argument, 0, '6'}, {"help", no_argument, 0, 'h'}, {"starttls",no_argument,0,'S'}, {"certificate",required_argument,0,'D'}, {"ignore-quit-failure",no_argument,0,'q'}, {0, 0, 0, 0} }; if (argc < 2) return ERROR; for (c = 1; c < argc; c++) { if (strcmp ("-to", argv[c]) == 0) strcpy (argv[c], "-t"); else if (strcmp ("-wt", argv[c]) == 0) strcpy (argv[c], "-w"); else if (strcmp ("-ct", argv[c]) == 0) strcpy (argv[c], "-c"); } while (1) { c = getopt_long (argc, argv, "+hVv46t:p:f:e:c:w:H:C:R:SD:F:A:U:P:q", longopts, &option); if (c == -1 || c == EOF) break; switch (c) { case 'H': /* hostname */ if (is_host (optarg)) { server_address = optarg; } else { usage2 (_("Invalid hostname/address"), optarg); } break; case 'p': /* port */ if (is_intpos (optarg)) server_port = atoi (optarg); else usage4 (_("Port must be a positive integer")); break; case 'F': /* localhostname */ localhostname = strdup(optarg); break; case 'f': /* from argument */ from_arg = optarg + strspn(optarg, "<"); from_arg = strndup(from_arg, strcspn(from_arg, ">")); send_mail_from = 1; break; case 'A': authtype = optarg; use_ehlo = TRUE; break; case 'U': authuser = optarg; break; case 'P': authpass = optarg; break; case 'e': /* server expect string on 220 */ server_expect = optarg; break; case 'C': /* commands */ if (ncommands >= command_size) { command_size+=8; commands = realloc (commands, sizeof(char *) * command_size); if (commands == NULL) die (STATE_UNKNOWN, _("Could not realloc() units [%d]\n"), ncommands); } commands[ncommands] = (char *) malloc (sizeof(char) * 255); strncpy (commands[ncommands], optarg, 255); ncommands++; break; case 'R': /* server responses */ if (nresponses >= response_size) { response_size += 8; responses = realloc (responses, sizeof(char *) * response_size); if (responses == NULL) die (STATE_UNKNOWN, _("Could not realloc() units [%d]\n"), nresponses); } responses[nresponses] = (char *) malloc (sizeof(char) * 255); strncpy (responses[nresponses], optarg, 255); nresponses++; break; case 'c': /* critical time threshold */ if (!is_nonnegative (optarg)) usage4 (_("Critical time must be a positive")); else { critical_time = strtod (optarg, NULL); check_critical_time = TRUE; } break; case 'w': /* warning time threshold */ if (!is_nonnegative (optarg)) usage4 (_("Warning time must be a positive")); else { warning_time = strtod (optarg, NULL); check_warning_time = TRUE; } break; case 'v': /* verbose */ verbose++; break; case 'q': ignore_send_quit_failure++; /* ignore problem sending QUIT */ break; case 't': /* timeout */ if (is_intnonneg (optarg)) { socket_timeout = atoi (optarg); } else { usage4 (_("Timeout interval must be a positive integer")); } break; case 'S': /* starttls */ use_ssl = TRUE; use_ehlo = TRUE; break; case 'D': /* Check SSL cert validity */ #ifdef USE_OPENSSL if ((temp=strchr(optarg,','))!=NULL) { *temp='\0'; if (!is_intnonneg (optarg)) usage2 ("Invalid certificate expiration period", optarg); days_till_exp_warn = atoi(optarg); *temp=','; temp++; if (!is_intnonneg (temp)) usage2 (_("Invalid certificate expiration period"), temp); days_till_exp_crit = atoi (temp); } else { days_till_exp_crit=0; if (!is_intnonneg (optarg)) usage2 ("Invalid certificate expiration period", optarg); days_till_exp_warn = atoi (optarg); } check_cert = TRUE; #else usage (_("SSL support not available - install OpenSSL and recompile")); #endif break; case '4': address_family = AF_INET; break; case '6': #ifdef USE_IPV6 address_family = AF_INET6; #else usage4 (_("IPv6 support not available")); #endif break; case 'V': /* version */ print_revision (progname, NP_VERSION); exit (STATE_OK); case 'h': /* help */ print_help (); exit (STATE_OK); case '?': /* help */ usage5 (); } } c = optind; if (server_address == NULL) { if (argv[c]) { if (is_host (argv[c])) server_address = argv[c]; else usage2 (_("Invalid hostname/address"), argv[c]); } else { xasprintf (&server_address, "127.0.0.1"); } } if (server_expect == NULL) server_expect = strdup (SMTP_EXPECT); if (mail_command == NULL) mail_command = strdup("MAIL "); if (from_arg==NULL) from_arg = strdup(" "); return validate_arguments (); }
int main (int argc, char **argv) { short supports_tls=FALSE; int n = 0; double elapsed_time; long microsec; int result = STATE_UNKNOWN; char *cmd_str = NULL; char *helocmd = NULL; char *error_msg = ""; struct timeval tv; /* Catch pipe errors in read/write - sometimes occurs when writing QUIT */ (void) signal (SIGPIPE, SIG_IGN); setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); /* Parse extra opts if any */ argv=np_extra_opts (&argc, argv, progname); if (process_arguments (argc, argv) == ERROR) usage4 (_("Could not parse arguments")); /* If localhostname not set on command line, use gethostname to set */ if(! localhostname){ localhostname = malloc (HOST_MAX_BYTES); if(!localhostname){ printf(_("malloc() failed!\n")); return STATE_CRITICAL; } if(gethostname(localhostname, HOST_MAX_BYTES)){ printf(_("gethostname() failed!\n")); return STATE_CRITICAL; } } if(use_ehlo) xasprintf (&helocmd, "%s%s%s", SMTP_EHLO, localhostname, "\r\n"); else xasprintf (&helocmd, "%s%s%s", SMTP_HELO, localhostname, "\r\n"); if (verbose) printf("HELOCMD: %s", helocmd); /* initialize the MAIL command with optional FROM command */ xasprintf (&cmd_str, "%sFROM:<%s>%s", mail_command, from_arg, "\r\n"); if (verbose && send_mail_from) printf ("FROM CMD: %s", cmd_str); /* initialize alarm signal handling */ (void) signal (SIGALRM, socket_timeout_alarm_handler); /* set socket timeout */ (void) alarm (socket_timeout); /* start timer */ gettimeofday (&tv, NULL); /* try to connect to the host at the given port number */ result = my_tcp_connect (server_address, server_port, &sd); if (result == STATE_OK) { /* we connected */ /* watch for the SMTP connection string and */ /* return a WARNING status if we couldn't read any data */ if (recvlines(buffer, MAX_INPUT_BUFFER) <= 0) { printf (_("recv() failed\n")); return STATE_WARNING; } else { if (verbose) printf ("%s", buffer); /* strip the buffer of carriage returns */ strip (buffer); /* make sure we find the response we are looking for */ if (!strstr (buffer, server_expect)) { if (server_port == SMTP_PORT) printf (_("Invalid SMTP response received from host: %s\n"), buffer); else printf (_("Invalid SMTP response received from host on port %d: %s\n"), server_port, buffer); return STATE_WARNING; } } /* send the HELO/EHLO command */ send(sd, helocmd, strlen(helocmd), 0); /* allow for response to helo command to reach us */ if (recvlines(buffer, MAX_INPUT_BUFFER) <= 0) { printf (_("recv() failed\n")); return STATE_WARNING; } else if(use_ehlo){ if(strstr(buffer, "250 STARTTLS") != NULL || strstr(buffer, "250-STARTTLS") != NULL){ supports_tls=TRUE; } } if(use_ssl && ! supports_tls){ printf(_("WARNING - TLS not supported by server\n")); smtp_quit(); return STATE_WARNING; } #ifdef HAVE_SSL if(use_ssl) { /* send the STARTTLS command */ send(sd, SMTP_STARTTLS, strlen(SMTP_STARTTLS), 0); recvlines(buffer, MAX_INPUT_BUFFER); /* wait for it */ if (!strstr (buffer, server_expect)) { printf (_("Server does not support STARTTLS\n")); smtp_quit(); return STATE_UNKNOWN; } result = np_net_ssl_init(sd); if(result != STATE_OK) { printf (_("CRITICAL - Cannot create SSL context.\n")); np_net_ssl_cleanup(); close(sd); return STATE_CRITICAL; } else { ssl_established = 1; } /* * Resend the EHLO command. * * RFC 3207 (4.2) says: ``The client MUST discard any knowledge * obtained from the server, such as the list of SMTP service * extensions, which was not obtained from the TLS negotiation * itself. The client SHOULD send an EHLO command as the first * command after a successful TLS negotiation.'' For this * reason, some MTAs will not allow an AUTH LOGIN command before * we resent EHLO via TLS. */ if (my_send(helocmd, strlen(helocmd)) <= 0) { printf("%s\n", _("SMTP UNKNOWN - Cannot send EHLO command via TLS.")); my_close(); return STATE_UNKNOWN; } if (verbose) printf(_("sent %s"), helocmd); if ((n = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) { printf("%s\n", _("SMTP UNKNOWN - Cannot read EHLO response via TLS.")); my_close(); return STATE_UNKNOWN; } if (verbose) { printf("%s", buffer); } # ifdef USE_OPENSSL if ( check_cert ) { result = np_net_ssl_check_cert(days_till_exp_warn, days_till_exp_crit); my_close(); return result; } # endif /* USE_OPENSSL */ } #endif if (send_mail_from) { my_send(cmd_str, strlen(cmd_str)); if (recvlines(buffer, MAX_INPUT_BUFFER) >= 1 && verbose) printf("%s", buffer); } while (n < ncommands) { xasprintf (&cmd_str, "%s%s", commands[n], "\r\n"); my_send(cmd_str, strlen(cmd_str)); if (recvlines(buffer, MAX_INPUT_BUFFER) >= 1 && verbose) printf("%s", buffer); strip (buffer); if (n < nresponses) { cflags |= REG_EXTENDED | REG_NOSUB | REG_NEWLINE; errcode = regcomp (&preg, responses[n], cflags); if (errcode != 0) { regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER); printf (_("Could Not Compile Regular Expression")); return ERROR; } excode = regexec (&preg, buffer, 10, pmatch, eflags); if (excode == 0) { result = STATE_OK; } else if (excode == REG_NOMATCH) { result = STATE_WARNING; printf (_("SMTP %s - Invalid response '%s' to command '%s'\n"), state_text (result), buffer, commands[n]); } else { regerror (excode, &preg, errbuf, MAX_INPUT_BUFFER); printf (_("Execute Error: %s\n"), errbuf); result = STATE_UNKNOWN; } } n++; } if (authtype != NULL) { if (strcmp (authtype, "LOGIN") == 0) { char *abuf; int ret; do { if (authuser == NULL) { result = STATE_CRITICAL; xasprintf(&error_msg, _("no authuser specified, ")); break; } if (authpass == NULL) { result = STATE_CRITICAL; xasprintf(&error_msg, _("no authpass specified, ")); break; } /* send AUTH LOGIN */ my_send(SMTP_AUTH_LOGIN, strlen(SMTP_AUTH_LOGIN)); if (verbose) printf (_("sent %s\n"), "AUTH LOGIN"); if ((ret = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) { xasprintf(&error_msg, _("recv() failed after AUTH LOGIN, ")); result = STATE_WARNING; break; } if (verbose) printf (_("received %s\n"), buffer); if (strncmp (buffer, "334", 3) != 0) { result = STATE_CRITICAL; xasprintf(&error_msg, _("invalid response received after AUTH LOGIN, ")); break; } /* encode authuser with base64 */ base64_encode_alloc (authuser, strlen(authuser), &abuf); xasprintf(&abuf, "%s\r\n", abuf); my_send(abuf, strlen(abuf)); if (verbose) printf (_("sent %s\n"), abuf); if ((ret = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) { result = STATE_CRITICAL; xasprintf(&error_msg, _("recv() failed after sending authuser, ")); break; } if (verbose) { printf (_("received %s\n"), buffer); } if (strncmp (buffer, "334", 3) != 0) { result = STATE_CRITICAL; xasprintf(&error_msg, _("invalid response received after authuser, ")); break; } /* encode authpass with base64 */ base64_encode_alloc (authpass, strlen(authpass), &abuf); xasprintf(&abuf, "%s\r\n", abuf); my_send(abuf, strlen(abuf)); if (verbose) { printf (_("sent %s\n"), abuf); } if ((ret = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) { result = STATE_CRITICAL; xasprintf(&error_msg, _("recv() failed after sending authpass, ")); break; } if (verbose) { printf (_("received %s\n"), buffer); } if (strncmp (buffer, "235", 3) != 0) { result = STATE_CRITICAL; xasprintf(&error_msg, _("invalid response received after authpass, ")); break; } break; } while (0); } else { result = STATE_CRITICAL; xasprintf(&error_msg, _("only authtype LOGIN is supported, ")); } } /* tell the server we're done */ smtp_quit(); /* finally close the connection */ close (sd); } /* reset the alarm */ alarm (0); microsec = deltime (tv); elapsed_time = (double)microsec / 1.0e6; if (result == STATE_OK) { if (check_critical_time && elapsed_time > critical_time) result = STATE_CRITICAL; else if (check_warning_time && elapsed_time > warning_time) result = STATE_WARNING; } printf (_("SMTP %s - %s%.3f sec. response time%s%s|%s\n"), state_text (result), error_msg, elapsed_time, verbose?", ":"", verbose?buffer:"", fperfdata ("time", elapsed_time, "s", (int)check_warning_time, warning_time, (int)check_critical_time, critical_time, TRUE, 0, FALSE, 0)); return result; }
int main (int argc, char **argv) { int result = STATE_UNKNOWN; int disk_result = STATE_UNKNOWN; char *output; char *details; char *perf; char *preamble; double inode_space_pct; double warning_high_tide; double critical_high_tide; int temp_result; struct mount_entry *me; struct fs_usage fsp, tmpfsp; struct parameter_list *temp_list, *path; preamble = strdup (" - free space:"); output = strdup (""); details = strdup (""); perf = strdup (""); stat_buf = malloc(sizeof *stat_buf); setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); mount_list = read_file_system_list (0); /* Parse extra opts if any */ argv = np_extra_opts (&argc, argv, progname); if (process_arguments (argc, argv) == ERROR) usage4 (_("Could not parse arguments")); /* If a list of paths has not been selected, find entire mount list and create list of paths */ if (path_selected == FALSE) { for (me = mount_list; me; me = me->me_next) { if (! (path = np_find_parameter(path_select_list, me->me_mountdir))) { path = np_add_parameter(&path_select_list, me->me_mountdir); } path->best_match = me; path->group = group; set_all_thresholds(path); } } np_set_best_match(path_select_list, mount_list, exact_match); /* Error if no match found for specified paths */ temp_list = path_select_list; while (temp_list) { if (! temp_list->best_match) { die (STATE_CRITICAL, _("DISK %s: %s not found\n"), _("CRITICAL"), temp_list->name); } temp_list = temp_list->name_next; } /* Process for every path in list */ for (path = path_select_list; path; path=path->name_next) { if (verbose >= 3 && path->freespace_percent->warning != NULL && path->freespace_percent->critical != NULL) printf("Thresholds(pct) for %s warn: %f crit %f\n",path->name, path->freespace_percent->warning->end, path->freespace_percent->critical->end); if (verbose >= 3 && path->group != NULL) printf("Group of %s: %s\n",path->name,path->group); /* reset disk result */ disk_result = STATE_UNKNOWN; me = path->best_match; /* Filters */ /* Remove filesystems already seen */ if (np_seen_name(seen, me->me_mountdir)) { continue; } np_add_name(&seen, me->me_mountdir); if (path->group == NULL) { /* Skip remote filesystems if we're not interested in them */ if (me->me_remote && show_local_fs) { if (stat_remote_fs) stat_path(path); continue; /* Skip pseudo fs's if we haven't asked for all fs's */ } else if (me->me_dummy && !show_all_fs) { continue; /* Skip excluded fstypes */ } else if (fs_exclude_list && np_find_name (fs_exclude_list, me->me_type)) { continue; /* Skip excluded fs's */ } else if (dp_exclude_list && (np_find_name (dp_exclude_list, me->me_devname) || np_find_name (dp_exclude_list, me->me_mountdir))) { continue; /* Skip not included fstypes */ } else if (fs_include_list && !np_find_name (fs_include_list, me->me_type)) { continue; } } stat_path(path); get_fs_usage (me->me_mountdir, me->me_devname, &fsp); if (fsp.fsu_blocks && strcmp ("none", me->me_mountdir)) { get_stats (path, &fsp); if (verbose >= 3) { printf ("For %s, used_pct=%g free_pct=%g used_units=%g free_units=%g total_units=%g used_inodes_pct=%g free_inodes_pct=%g fsp.fsu_blocksize=%llu mult=%llu\n", me->me_mountdir, path->dused_pct, path->dfree_pct, path->dused_units, path->dfree_units, path->dtotal_units, path->dused_inodes_percent, path->dfree_inodes_percent, fsp.fsu_blocksize, mult); } /* Threshold comparisons */ temp_result = get_status(path->dfree_units, path->freespace_units); if (verbose >=3) printf("Freespace_units result=%d\n", temp_result); disk_result = max_state( disk_result, temp_result ); temp_result = get_status(path->dfree_pct, path->freespace_percent); if (verbose >=3) printf("Freespace%% result=%d\n", temp_result); disk_result = max_state( disk_result, temp_result ); temp_result = get_status(path->dused_units, path->usedspace_units); if (verbose >=3) printf("Usedspace_units result=%d\n", temp_result); disk_result = max_state( disk_result, temp_result ); temp_result = get_status(path->dused_pct, path->usedspace_percent); if (verbose >=3) printf("Usedspace_percent result=%d\n", temp_result); disk_result = max_state( disk_result, temp_result ); temp_result = get_status(path->dused_inodes_percent, path->usedinodes_percent); if (verbose >=3) printf("Usedinodes_percent result=%d\n", temp_result); disk_result = max_state( disk_result, temp_result ); temp_result = get_status(path->dfree_inodes_percent, path->freeinodes_percent); if (verbose >=3) printf("Freeinodes_percent result=%d\n", temp_result); disk_result = max_state( disk_result, temp_result ); result = max_state(result, disk_result); /* What a mess of units. The output shows free space, the perf data shows used space. Yikes! Hack here. Trying to get warn/crit levels from freespace_(units|percent) for perf data. Assumption that start=0. Roll on new syntax... */ /* *_high_tide must be reinitialized at each run */ warning_high_tide = UINT_MAX; critical_high_tide = UINT_MAX; if (path->freespace_units->warning != NULL) { warning_high_tide = path->dtotal_units - path->freespace_units->warning->end; } if (path->freespace_percent->warning != NULL) { warning_high_tide = abs( min( (double) warning_high_tide, (double) (1.0 - path->freespace_percent->warning->end/100)*path->dtotal_units )); } if (path->freespace_units->critical != NULL) { critical_high_tide = path->dtotal_units - path->freespace_units->critical->end; } if (path->freespace_percent->critical != NULL) { critical_high_tide = abs( min( (double) critical_high_tide, (double) (1.0 - path->freespace_percent->critical->end/100)*path->dtotal_units )); } /* Nb: *_high_tide are unset when == UINT_MAX */ xasprintf (&perf, "%s %s", perf, perfdata ((!strcmp(me->me_mountdir, "none") || display_mntp) ? me->me_devname : me->me_mountdir, path->dused_units, units, (warning_high_tide != UINT_MAX ? TRUE : FALSE), warning_high_tide, (critical_high_tide != UINT_MAX ? TRUE : FALSE), critical_high_tide, TRUE, 0, TRUE, path->dtotal_units)); if (disk_result==STATE_OK && erronly && !verbose) continue; xasprintf (&output, "%s %s %.0f %s (%.0f%%", output, (!strcmp(me->me_mountdir, "none") || display_mntp) ? me->me_devname : me->me_mountdir, path->dfree_units, units, path->dfree_pct); /* Whether or not to put all disks on new line */ if (newlines) { if (path->dused_inodes_percent < 0) { xasprintf(&output, "%s inode=-);\n", output); } else { xasprintf(&output, "%s inode=%.0f%%);\n", output, path->dfree_inodes_percent ); } } else { if (path->dused_inodes_percent < 0) { xasprintf(&output, "%s inode=-);", output); } else { xasprintf(&output, "%s inode=%.0f%%);", output, path->dfree_inodes_percent ); } } /* TODO: Need to do a similar debug line xasprintf (&details, _("%s\n\ %.0f of %.0f %s (%.0f%% inode=%.0f%%) free on %s (type %s mounted on %s) warn:%lu crit:%lu warn%%:%.0f%% crit%%:%.0f%%"), details, dfree_units, dtotal_units, units, dfree_pct, inode_space_pct, me->me_devname, me->me_type, me->me_mountdir, (unsigned long)w_df, (unsigned long)c_df, w_dfp, c_dfp); */ } } if (verbose >= 2) xasprintf (&output, "%s%s", output, details); if (newlines) { printf ("DISK %s%s\n%s|%s\n", state_text (result), (erronly && result==STATE_OK) ? "" : preamble, output, perf); } else { printf ("DISK %s%s%s|%s\n", state_text (result), (erronly && result==STATE_OK) ? "" : preamble, output, perf); } return result; }
int main (int argc, char *argv[]) { LDAP *ld; LDAPMessage *result; /* should be int result = STATE_UNKNOWN; */ int status = STATE_UNKNOWN; long microsec; double elapsed_time; /* for ldap tls */ int tls; int version=3; /* for entry counting */ LDAPMessage *next_entry; int status_entries = STATE_OK; int num_entries = 0; setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); if (strstr(argv[0],"check_ldaps")) { xasprintf (&progname, "check_ldaps"); } /* Parse extra opts if any */ argv=np_extra_opts (&argc, argv, progname); if (process_arguments (argc, argv) == ERROR) usage4 (_("Could not parse arguments")); if (strstr(argv[0],"check_ldaps") && ! starttls && ! ssl_on_connect) starttls = TRUE; /* initialize alarm signal handling */ signal (SIGALRM, socket_timeout_alarm_handler); /* set socket timeout */ alarm (timeout_interval); /* get the start time */ gettimeofday (&tv, NULL); /* initialize ldap */ if (ld_uri != NULL) { #ifdef HAVE_LDAP_INITIALIZE int result = ldap_initialize(&ld, ld_uri); if (result != LDAP_SUCCESS) { printf ("Failed to connect to LDAP server at %s: %s\n", ld_uri, ldap_err2string(result)); return STATE_CRITICAL; } #else printf ("Sorry, this version of %s was compiled without URI support!\n", argv[0]); return STATE_CRITICAL; #endif } #ifdef HAVE_LDAP_INIT else if (!(ld = ldap_init (ld_host, ld_port))) { printf ("Could not connect to the server at port %i\n", ld_port); return STATE_CRITICAL; } #else else if (!(ld = ldap_open (ld_host, ld_port))) { if (verbose) ldap_perror(ld, "ldap_open"); printf (_("Could not connect to the server at port %i\n"), ld_port); return STATE_CRITICAL; } #endif /* HAVE_LDAP_INIT */ #ifdef HAVE_LDAP_SET_OPTION /* set ldap options */ if (ldap_set_option (ld, LDAP_OPT_PROTOCOL_VERSION, &ld_protocol) != LDAP_OPT_SUCCESS ) { printf(_("Could not set protocol version %d\n"), ld_protocol); return STATE_CRITICAL; } #endif if (ld_port == LDAPS_PORT || ssl_on_connect) { xasprintf (&SERVICE, "LDAPS"); #if defined(HAVE_LDAP_SET_OPTION) && defined(LDAP_OPT_X_TLS) /* ldaps: set option tls */ tls = LDAP_OPT_X_TLS_HARD; if (ldap_set_option (ld, LDAP_OPT_X_TLS, &tls) != LDAP_SUCCESS) { if (verbose) ldap_perror(ld, "ldaps_option"); printf (_("Could not init TLS at port %i!\n"), ld_port); return STATE_CRITICAL; } #else printf (_("TLS not supported by the libraries!\n")); return STATE_CRITICAL; #endif /* LDAP_OPT_X_TLS */ } else if (starttls) { xasprintf (&SERVICE, "LDAP-TLS"); #if defined(HAVE_LDAP_SET_OPTION) && defined(HAVE_LDAP_START_TLS_S) /* ldap with startTLS: set option version */ if (ldap_get_option(ld,LDAP_OPT_PROTOCOL_VERSION, &version) == LDAP_OPT_SUCCESS ) { if (version < LDAP_VERSION3) { version = LDAP_VERSION3; ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &version); } } /* call start_tls */ if (ldap_start_tls_s(ld, NULL, NULL) != LDAP_SUCCESS) { if (verbose) ldap_perror(ld, "ldap_start_tls"); printf (_("Could not init startTLS at port %i!\n"), ld_port); return STATE_CRITICAL; } #else printf (_("startTLS not supported by the library, needs LDAPv3!\n")); return STATE_CRITICAL; #endif /* HAVE_LDAP_START_TLS_S */ } /* bind to the ldap server */ if (ldap_bind_s (ld, ld_binddn, ld_passwd, LDAP_AUTH_SIMPLE) != LDAP_SUCCESS) { if (verbose) ldap_perror(ld, "ldap_bind"); printf (_("Could not bind to the LDAP server\n")); return STATE_CRITICAL; } /* do a search of all objectclasses in the base dn */ if (ldap_search_s (ld, ld_base, (crit_entries!=NULL || warn_entries!=NULL) ? LDAP_SCOPE_SUBTREE : LDAP_SCOPE_BASE, ld_attr, NULL, 0, &result) != LDAP_SUCCESS) { if (verbose) ldap_perror(ld, "ldap_search"); printf (_("Could not search/find objectclasses in %s\n"), ld_base); return STATE_CRITICAL; } else if (crit_entries!=NULL || warn_entries!=NULL) { num_entries = ldap_count_entries(ld, result); } /* unbind from the ldap server */ ldap_unbind (ld); /* reset the alarm handler */ alarm (0); /* calcutate the elapsed time and compare to thresholds */ microsec = deltime (tv); elapsed_time = (double)microsec / 1.0e6; if (crit_time!=UNDEFINED && elapsed_time>crit_time) status = STATE_CRITICAL; else if (warn_time!=UNDEFINED && elapsed_time>warn_time) status = STATE_WARNING; else status = STATE_OK; if(entries_thresholds != NULL) { if (verbose) { printf ("entries found: %d\n", num_entries); print_thresholds("entry threasholds", entries_thresholds); } status_entries = get_status(num_entries, entries_thresholds); if (status_entries == STATE_CRITICAL) { status = STATE_CRITICAL; } else if (status != STATE_CRITICAL) { status = status_entries; } } /* print out the result */ if (crit_entries!=NULL || warn_entries!=NULL) { printf (_("LDAP %s - found %d entries in %.3f seconds|%s %s\n"), state_text (status), num_entries, elapsed_time, fperfdata ("time", elapsed_time, "s", (int)warn_time, warn_time, (int)crit_time, crit_time, TRUE, 0, FALSE, 0), sperfdata ("entries", (double)num_entries, "", warn_entries, crit_entries, TRUE, 0.0, FALSE, 0.0)); } else { printf (_("LDAP %s - %.3f seconds response time|%s\n"), state_text (status), elapsed_time, fperfdata ("time", elapsed_time, "s", (int)warn_time, warn_time, (int)crit_time, crit_time, TRUE, 0, FALSE, 0)); } return status; }
int main (int argc, char **argv) { char command_line[1024]; int result = STATE_UNKNOWN; int line; char input_buffer[MAX_INPUT_BUFFER]; char query_string[512]; char *errmsg; char *temp_buffer; int line_status = ONLINE; int paper_status = 0; int intervention_required = 0; int peripheral_error = 0; int paper_jam = 0; int paper_out = 0; int toner_low = 0; int page_punt = 0; int memory_out = 0; int door_open = 0; int paper_output = 0; char display_message[MAX_INPUT_BUFFER]; errmsg = malloc(MAX_INPUT_BUFFER); setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); /* Parse extra opts if any */ argv=np_extra_opts (&argc, argv, progname); if (process_arguments (argc, argv) == ERROR) usage4 (_("Could not parse arguments")); /* removed ' 2>1' at end of command 10/27/1999 - EG */ /* create the query string */ sprintf (query_string, "%s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0", HPJD_LINE_STATUS, HPJD_PAPER_STATUS, HPJD_INTERVENTION_REQUIRED, HPJD_GD_PERIPHERAL_ERROR, HPJD_GD_PAPER_JAM, HPJD_GD_PAPER_OUT, HPJD_GD_TONER_LOW, HPJD_GD_PAGE_PUNT, HPJD_GD_MEMORY_OUT, HPJD_GD_DOOR_OPEN, HPJD_GD_PAPER_OUTPUT, HPJD_GD_STATUS_DISPLAY); /* get the command to run */ sprintf (command_line, "%s -OQa -m : -v 1 -c %s %s:%hd %s", PATH_TO_SNMPGET, community, address, port, query_string); /* run the command */ child_process = spopen (command_line); if (child_process == NULL) { printf (_("Could not open pipe: %s\n"), command_line); return STATE_UNKNOWN; } child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r"); if (child_stderr == NULL) { printf (_("Could not open stderr for %s\n"), command_line); } result = STATE_OK; line = 0; while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process)) { /* strip the newline character from the end of the input */ if (input_buffer[strlen (input_buffer) - 1] == '\n') input_buffer[strlen (input_buffer) - 1] = 0; line++; temp_buffer = strtok (input_buffer, "="); temp_buffer = strtok (NULL, "="); if (temp_buffer == NULL && line < 13) { result = STATE_UNKNOWN; strcpy (errmsg, input_buffer); } else { switch (line) { case 1: /* 1st line should contain the line status */ line_status = atoi (temp_buffer); break; case 2: /* 2nd line should contain the paper status */ paper_status = atoi (temp_buffer); break; case 3: /* 3rd line should be intervention required */ intervention_required = atoi (temp_buffer); break; case 4: /* 4th line should be peripheral error */ peripheral_error = atoi (temp_buffer); break; case 5: /* 5th line should contain the paper jam status */ paper_jam = atoi (temp_buffer); break; case 6: /* 6th line should contain the paper out status */ paper_out = atoi (temp_buffer); break; case 7: /* 7th line should contain the toner low status */ toner_low = atoi (temp_buffer); break; case 8: /* did data come too slow for engine */ page_punt = atoi (temp_buffer); break; case 9: /* did we run out of memory */ memory_out = atoi (temp_buffer); break; case 10: /* is there a door open */ door_open = atoi (temp_buffer); break; case 11: /* is output tray full */ paper_output = atoi (temp_buffer); break; case 12: /* display panel message */ strcpy (display_message, temp_buffer + 1); break; default: /* fold multiline message */ strncat (display_message, input_buffer, sizeof (display_message) - strlen (display_message) - 1); } } /* break out of the read loop if we encounter an error */ if (result != STATE_OK) break; } /* WARNING if output found on stderr */ if (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_stderr)) { result = max_state (result, STATE_WARNING); /* remove CRLF */ if (input_buffer[strlen (input_buffer) - 1] == '\n') input_buffer[strlen (input_buffer) - 1] = 0; sprintf (errmsg, "%s", input_buffer ); } /* close stderr */ (void) fclose (child_stderr); /* close the pipe */ if (spclose (child_process)) result = max_state (result, STATE_WARNING); /* if there wasn't any output, display an error */ if (line == 0) { /* might not be the problem, but most likely is. */ result = STATE_UNKNOWN ; xasprintf (&errmsg, "%s : Timeout from host %s\n", errmsg, address ); } /* if we had no read errors, check the printer status results... */ if (result == STATE_OK) { if (paper_jam) { result = STATE_WARNING; strcpy (errmsg, _("Paper Jam")); } else if (paper_out) { result = STATE_WARNING; strcpy (errmsg, _("Out of Paper")); } else if (line_status == OFFLINE) { if (strcmp (errmsg, "POWERSAVE ON") != 0) { result = STATE_WARNING; strcpy (errmsg, _("Printer Offline")); } } else if (peripheral_error) { result = STATE_WARNING; strcpy (errmsg, _("Peripheral Error")); } else if (intervention_required) { result = STATE_WARNING; strcpy (errmsg, _("Intervention Required")); } else if (toner_low) { result = STATE_WARNING; strcpy (errmsg, _("Toner Low")); } else if (memory_out) { result = STATE_WARNING; strcpy (errmsg, _("Insufficient Memory")); } else if (door_open) { result = STATE_WARNING; strcpy (errmsg, _("A Door is Open")); } else if (paper_output) { result = STATE_WARNING; strcpy (errmsg, _("Output Tray is Full")); } else if (page_punt) { result = STATE_WARNING; strcpy (errmsg, _("Data too Slow for Engine")); } else if (paper_status) { result = STATE_WARNING; strcpy (errmsg, _("Unknown Paper Error")); } } if (result == STATE_OK) printf (_("Printer ok - (%s)\n"), display_message); else if (result == STATE_UNKNOWN) { printf ("%s\n", errmsg); /* if printer could not be reached, escalate to critical */ if (strstr (errmsg, "Timeout")) result = STATE_CRITICAL; } else if (result == STATE_WARNING) printf ("%s (%s)\n", errmsg, display_message); return result; }
/* process command-line arguments */ static int process_arguments (int argc, char **argv) { int c; int escape = 0; int option = 0; static struct option longopts[] = { {"hostname", required_argument, 0, 'H'}, {"critical", required_argument, 0, 'c'}, {"warning", required_argument, 0, 'w'}, {"critical-codes", required_argument, 0, 'C'}, {"warning-codes", required_argument, 0, 'W'}, {"timeout", required_argument, 0, 't'}, {"protocol", required_argument, 0, 'P'}, /* FIXME: Unhandled */ {"port", required_argument, 0, 'p'}, {"escape", no_argument, 0, 'E'}, {"all", no_argument, 0, 'A'}, {"send", required_argument, 0, 's'}, {"expect", required_argument, 0, 'e'}, {"maxbytes", required_argument, 0, 'm'}, {"quit", required_argument, 0, 'q'}, {"jail", no_argument, 0, 'j'}, {"delay", required_argument, 0, 'd'}, {"refuse", required_argument, 0, 'r'}, {"mismatch", required_argument, 0, 'M'}, {"use-ipv4", no_argument, 0, '4'}, {"use-ipv6", no_argument, 0, '6'}, {"verbose", no_argument, 0, 'v'}, {"version", no_argument, 0, 'V'}, {"help", no_argument, 0, 'h'}, {"ssl", no_argument, 0, 'S'}, {"certificate", required_argument, 0, 'D'}, {0, 0, 0, 0} }; if (argc < 2) usage4 (_("No arguments found")); /* backwards compatibility */ for (c = 1; c < argc; c++) { if (strcmp ("-to", argv[c]) == 0) strcpy (argv[c], "-t"); else if (strcmp ("-wt", argv[c]) == 0) strcpy (argv[c], "-w"); else if (strcmp ("-ct", argv[c]) == 0) strcpy (argv[c], "-c"); } if (!is_option (argv[1])) { server_address = argv[1]; argv[1] = argv[0]; argv = &argv[1]; argc--; } while (1) { c = getopt_long (argc, argv, "+hVv46EAH:s:e:q:m:c:w:t:p:C:W:d:Sr:jD:M:", longopts, &option); if (c == -1 || c == EOF || c == 1) break; switch (c) { case '?': /* print short usage statement if args not parsable */ usage5 (); case 'h': /* help */ print_help (); exit (STATE_OK); case 'V': /* version */ print_revision (progname, NP_VERSION); exit (STATE_OK); case 'v': /* verbose mode */ flags |= FLAG_VERBOSE; break; case '4': address_family = AF_INET; break; case '6': #ifdef USE_IPV6 address_family = AF_INET6; #else usage4 (_("IPv6 support not available")); #endif break; case 'H': /* hostname */ server_address = optarg; break; case 'c': /* critical */ critical_time = strtod (optarg, NULL); flags |= FLAG_TIME_CRIT; break; case 'j': /* hide output */ flags |= FLAG_HIDE_OUTPUT; break; case 'w': /* warning */ warning_time = strtod (optarg, NULL); flags |= FLAG_TIME_WARN; break; case 'C': crit_codes = realloc (crit_codes, ++crit_codes_count); crit_codes[crit_codes_count - 1] = optarg; break; case 'W': warn_codes = realloc (warn_codes, ++warn_codes_count); warn_codes[warn_codes_count - 1] = optarg; break; case 't': /* timeout */ if (!is_intpos (optarg)) usage4 (_("Timeout interval must be a positive integer")); else socket_timeout = atoi (optarg); break; case 'p': /* port */ if (!is_intpos (optarg)) usage4 (_("Port must be a positive integer")); else server_port = atoi (optarg); break; case 'E': escape = 1; break; case 's': if (escape) server_send = np_escaped_string(optarg); else asprintf(&server_send, "%s", optarg); break; case 'e': /* expect string (may be repeated) */ flags &= ~FLAG_EXACT_MATCH; if (server_expect_count == 0) server_expect = malloc (sizeof (char *) * (++server_expect_count)); else server_expect = realloc (server_expect, sizeof (char *) * (++server_expect_count)); server_expect[server_expect_count - 1] = optarg; break; case 'm': if (!is_intpos (optarg)) usage4 (_("Maxbytes must be a positive integer")); else maxbytes = strtol (optarg, NULL, 0); break; case 'q': if (escape) server_quit = np_escaped_string(optarg); else asprintf(&server_quit, "%s\r\n", optarg); break; case 'r': if (!strncmp(optarg,"ok",2)) econn_refuse_state = STATE_OK; else if (!strncmp(optarg,"warn",4)) econn_refuse_state = STATE_WARNING; else if (!strncmp(optarg,"crit",4)) econn_refuse_state = STATE_CRITICAL; else usage4 (_("Refuse must be one of ok, warn, crit")); break; case 'M': if (!strncmp(optarg,"ok",2)) expect_mismatch_state = STATE_OK; else if (!strncmp(optarg,"warn",4)) expect_mismatch_state = STATE_WARNING; else if (!strncmp(optarg,"crit",4)) expect_mismatch_state = STATE_CRITICAL; else usage4 (_("Mismatch must be one of ok, warn, crit")); break; case 'd': if (is_intpos (optarg)) delay = atoi (optarg); else usage4 (_("Delay must be a positive integer")); break; case 'D': /* Check SSL cert validity - days 'til certificate expiration */ #ifdef HAVE_SSL # ifdef USE_OPENSSL /* XXX */ if (!is_intnonneg (optarg)) usage2 (_("Invalid certificate expiration period"), optarg); days_till_exp = atoi (optarg); check_cert = TRUE; flags |= FLAG_SSL; break; # endif /* USE_OPENSSL */ #endif /* fallthrough if we don't have ssl */ case 'S': #ifdef HAVE_SSL flags |= FLAG_SSL; #else die (STATE_UNKNOWN, _("Invalid option - SSL is not available")); #endif break; case 'A': flags |= FLAG_MATCH_ALL; break; } } if (server_address == NULL) usage4 (_("You must provide a server address")); else if (server_address[0] != '/' && is_host (server_address) == FALSE) die (STATE_CRITICAL, "%s %s - %s: %s\n", SERVICE, state_text(STATE_CRITICAL), _("Invalid hostname, address or socket"), server_address); return TRUE; }
/* process command-line arguments */ int process_arguments (int argc, char **argv) { int c; int option = 0; static struct option longopts[] = { {"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'V'}, {"host", required_argument, 0, 'H'}, /* backward compatibility */ {"hostname", required_argument, 0, 'H'}, {"port", required_argument, 0, 'p'}, {"use-ipv4", no_argument, 0, '4'}, {"use-ipv6", no_argument, 0, '6'}, {"timeout", required_argument, 0, 't'}, {"verbose", no_argument, 0, 'v'}, {"remote-version", required_argument, 0, 'r'}, {0, 0, 0, 0} }; if (argc < 2) return ERROR; for (c = 1; c < argc; c++) if (strcmp ("-to", argv[c]) == 0) strcpy (argv[c], "-t"); while (1) { c = getopt_long (argc, argv, "+Vhv46t:r:H:p:", longopts, &option); if (c == -1 || c == EOF) break; switch (c) { case '?': /* help */ usage5 (); case 'V': /* version */ print_revision (progname, NP_VERSION); exit (STATE_OK); case 'h': /* help */ print_help (); exit (STATE_OK); case 'v': /* verbose */ verbose = TRUE; break; case 't': /* timeout period */ if (!is_integer (optarg)) usage2 (_("Timeout interval must be a positive integer"), optarg); else socket_timeout = atoi (optarg); break; case '4': address_family = AF_INET; break; case '6': #ifdef USE_IPV6 address_family = AF_INET6; #else usage4 (_("IPv6 support not available")); #endif break; case 'r': /* remote version */ remote_version = optarg; break; case 'H': /* host */ if (is_host (optarg) == FALSE) usage2 (_("Invalid hostname/address"), optarg); server_name = optarg; break; case 'p': /* port */ if (is_intpos (optarg)) { port = atoi (optarg); } else { usage2 (_("Port number must be a positive integer"), optarg); } } } c = optind; if (server_name == NULL && c < argc) { if (is_host (argv[c])) { server_name = argv[c++]; } } if (port == -1 && c < argc) { if (is_intpos (argv[c])) { port = atoi (argv[c++]); } else { print_usage (); exit (STATE_UNKNOWN); } } return validate_arguments (); }
int main (int argc, char **argv) { int result = STATE_UNKNOWN; int i; char *status = NULL; struct timeval tv; size_t len; int match = -1; setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); /* determine program- and service-name quickly */ progname = strrchr(argv[0], '/'); if(progname != NULL) progname++; else progname = argv[0]; len = strlen(progname); if(len > 6 && !memcmp(progname, "check_", 6)) { SERVICE = strdup(progname + 6); for(i = 0; i < len - 6; i++) SERVICE[i] = toupper(SERVICE[i]); } /* set up a resonable buffer at first (will be realloc()'ed if * user specifies other options) */ server_expect = calloc(sizeof(char *), 2); /* determine defaults for this service's protocol */ if (!strncmp(SERVICE, "UDP", 3)) { PROTOCOL = IPPROTO_UDP; } else if (!strncmp(SERVICE, "FTP", 3)) { EXPECT = "220"; QUIT = "QUIT\r\n"; PORT = 21; } else if (!strncmp(SERVICE, "POP", 3) || !strncmp(SERVICE, "POP3", 4)) { EXPECT = "+OK"; QUIT = "QUIT\r\n"; PORT = 110; } else if (!strncmp(SERVICE, "SMTP", 4)) { EXPECT = "220"; QUIT = "QUIT\r\n"; PORT = 25; } else if (!strncmp(SERVICE, "IMAP", 4)) { EXPECT = "* OK"; QUIT = "a1 LOGOUT\r\n"; PORT = 143; } #ifdef HAVE_SSL else if (!strncmp(SERVICE, "SIMAP", 5)) { EXPECT = "* OK"; QUIT = "a1 LOGOUT\r\n"; flags |= FLAG_SSL; PORT = 993; } else if (!strncmp(SERVICE, "SPOP", 4)) { EXPECT = "+OK"; QUIT = "QUIT\r\n"; flags |= FLAG_SSL; PORT = 995; } else if (!strncmp(SERVICE, "SSMTP", 5)) { EXPECT = "220"; QUIT = "QUIT\r\n"; flags |= FLAG_SSL; PORT = 465; } else if (!strncmp(SERVICE, "JABBER", 6)) { SEND = "<stream:stream to=\'host\' xmlns=\'jabber:client\' xmlns:stream=\'http://etherx.jabber.org/streams\'>\n"; EXPECT = "<?xml version=\'1.0\'?><stream:stream xmlns=\'jabber:client\' xmlns:stream=\'http://etherx.jabber.org/streams\'"; QUIT = "</stream:stream>\n"; flags |= FLAG_HIDE_OUTPUT; PORT = 5222; } else if (!strncmp (SERVICE, "NNTPS", 5)) { server_expect_count = 2; server_expect[0] = "200"; server_expect[1] = "201"; QUIT = "QUIT\r\n"; flags |= FLAG_SSL; PORT = 563; } #endif else if (!strncmp (SERVICE, "NNTP", 4)) { server_expect_count = 2; server_expect = malloc(sizeof(char *) * server_expect_count); server_expect[0] = strdup("200"); server_expect[1] = strdup("201"); QUIT = "QUIT\r\n"; PORT = 119; } else if (!strncmp(SERVICE, "CLAMD", 5)) { SEND = "PING"; EXPECT = "PONG"; QUIT = NULL; PORT = 3310; } /* fallthrough check, so it's supposed to use reverse matching */ else if (strcmp (SERVICE, "TCP")) usage (_("CRITICAL - Generic check_tcp called with unknown service\n")); server_address = "127.0.0.1"; server_port = PORT; server_send = SEND; server_quit = QUIT; status = NULL; /* Parse extra opts if any */ argv=np_extra_opts (&argc, argv, progname); if (process_arguments (argc, argv) == ERROR) usage4 (_("Could not parse arguments")); if(flags & FLAG_VERBOSE) { printf("Using service %s\n", SERVICE); printf("Port: %d\n", server_port); printf("flags: 0x%x\n", (int)flags); } if(EXPECT && !server_expect_count) server_expect_count++; if(PROTOCOL==IPPROTO_UDP && !(server_expect_count && server_send)){ usage(_("With UDP checks, a send/expect string must be specified.")); } /* set up the timer */ signal (SIGALRM, socket_timeout_alarm_handler); alarm (socket_timeout); /* try to connect to the host at the given port number */ gettimeofday (&tv, NULL); result = np_net_connect (server_address, server_port, &sd, PROTOCOL); if (result == STATE_CRITICAL) return STATE_CRITICAL; #ifdef HAVE_SSL if (flags & FLAG_SSL){ result = np_net_ssl_init(sd); if (result == STATE_OK && check_cert == TRUE) { result = np_net_ssl_check_cert(days_till_exp); } } if(result != STATE_OK || check_cert == TRUE){ np_net_ssl_cleanup(); if(sd) close(sd); return result; } #endif /* HAVE_SSL */ if (server_send != NULL) { /* Something to send? */ my_send(server_send, strlen(server_send)); } if (delay > 0) { tv.tv_sec += delay; sleep (delay); } if(flags & FLAG_VERBOSE) { if (server_send) { printf("Send string: %s\n", server_send); } if (server_quit) { printf("Quit string: %s\n", server_quit); } printf("server_expect_count: %d\n", (int)server_expect_count); for(i = 0; i < server_expect_count; i++) printf("\t%d: %s\n", i, server_expect[i]); } /* if(len) later on, we know we have a non-NULL response */ len = 0; if (server_expect_count) { /* watch for the expect string */ while ((i = my_recv(buffer, sizeof(buffer))) > 0) { status = realloc(status, len + i + 1); memcpy(&status[len], buffer, i); len += i; /* stop reading if user-forced or data-starved */ if(i < sizeof(buffer) || (maxbytes && len >= maxbytes)) break; if (maxbytes && len >= maxbytes) break; } /* no data when expected, so return critical */ if (len == 0) die (STATE_CRITICAL, _("No data received from host\n")); /* force null-termination and strip whitespace from end of output */ status[len--] = '\0'; /* print raw output if we're debugging */ if(flags & FLAG_VERBOSE) printf("received %d bytes from host\n#-raw-recv-------#\n%s\n#-raw-recv-------#\n", (int)len + 1, status); while(isspace(status[len])) status[len--] = '\0'; match = np_expect_match(status, server_expect, server_expect_count, (flags & FLAG_MATCH_ALL ? TRUE : FALSE), (flags & FLAG_EXACT_MATCH ? TRUE : FALSE), (flags & FLAG_VERBOSE ? TRUE : FALSE)); } if (server_quit != NULL) { my_send(server_quit, strlen(server_quit)); } #ifdef HAVE_SSL np_net_ssl_cleanup(); #endif if (sd) close (sd); microsec = deltime (tv); elapsed_time = (double)microsec / 1.0e6; if (flags & FLAG_TIME_CRIT && elapsed_time > critical_time) result = STATE_CRITICAL; else if (flags & FLAG_TIME_WARN && elapsed_time > warning_time) result = STATE_WARNING; /* did we get the response we hoped? */ if(match == FALSE && result != STATE_CRITICAL) result = expect_mismatch_state; /* reset the alarm */ alarm (0); /* this is a bit stupid, because we don't want to print the * response time (which can look ok to the user) if we didn't get * the response we were looking for. if-else */ printf("%s %s - ", SERVICE, state_text(result)); if(match == FALSE && len && !(flags & FLAG_HIDE_OUTPUT)) printf("Unexpected response from host/socket: %s", status); else { if(match == FALSE) printf("Unexpected response from host/socket on "); else printf("%.3f second response time on ", elapsed_time); if(server_address[0] != '/') printf("port %d", server_port); else printf("socket %s", server_address); } if (match != FALSE && !(flags & FLAG_HIDE_OUTPUT) && len) printf (" [%s]", status); /* perf-data doesn't apply when server doesn't talk properly, * so print all zeroes on warn and crit. Use fperfdata since * localisation settings can make different outputs */ if(match == FALSE) printf ("|%s", fperfdata ("time", elapsed_time, "s", (flags & FLAG_TIME_WARN ? TRUE : FALSE), 0, (flags & FLAG_TIME_CRIT ? TRUE : FALSE), 0, TRUE, 0, TRUE, socket_timeout) ); else printf("|%s", fperfdata ("time", elapsed_time, "s", (flags & FLAG_TIME_WARN ? TRUE : FALSE), warning_time, (flags & FLAG_TIME_CRIT ? TRUE : FALSE), critical_time, TRUE, 0, TRUE, socket_timeout) ); putchar('\n'); return result; }
int main (int argc, char **argv) { char *input_buffer; char *input_line; char *procprog; pid_t mypid = 0; int procuid = 0; pid_t procpid = 0; pid_t procppid = 0; int procvsz = 0; int procrss = 0; int procseconds = 0; float procpcpu = 0; char procstat[8]; char procetime[MAX_INPUT_BUFFER] = { '\0' }; char *procargs; const char *zombie = "Z"; int resultsum = 0; /* bitmask of the filter criteria met by a process */ int found = 0; /* counter for number of lines returned in `ps` output */ int procs = 0; /* counter for number of processes meeting filter criteria */ int pos; /* number of spaces before 'args' in `ps` output */ int cols; /* number of columns in ps output */ int expected_cols = PS_COLS - 1; int warn = 0; /* number of processes in warn state */ int crit = 0; /* number of processes in crit state */ int i = 0, j = 0; int result = STATE_UNKNOWN; output chld_out, chld_err; setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); setlocale(LC_NUMERIC, "POSIX"); input_buffer = malloc (MAX_INPUT_BUFFER); procprog = malloc (MAX_INPUT_BUFFER); xasprintf (&metric_name, "PROCS"); metric = METRIC_PROCS; /* Parse extra opts if any */ argv=np_extra_opts (&argc, argv, progname); if (process_arguments (argc, argv) == ERROR) usage4 (_("Could not parse arguments")); /* get our pid */ mypid = getpid(); /* Set signal handling and alarm timeout */ if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) { die (STATE_UNKNOWN, _("Cannot catch SIGALRM")); } (void) alarm ((unsigned) timeout_interval); if (verbose >= 2) printf (_("CMD: %s\n"), PS_COMMAND); if (input_filename == NULL) { result = cmd_run( PS_COMMAND, &chld_out, &chld_err, 0); if (chld_err.lines > 0) { printf ("%s: %s", _("System call sent warnings to stderr"), chld_err.line[0]); exit(STATE_WARNING); } } else { result = cmd_file_read( input_filename, &chld_out, 0); } /* flush first line: j starts at 1 */ for (j = 1; j < chld_out.lines; j++) { input_line = chld_out.line[j]; if (verbose >= 3) printf ("%s", input_line); strcpy (procprog, ""); xasprintf (&procargs, "%s", ""); cols = sscanf (input_line, PS_FORMAT, PS_VARLIST); /* Zombie processes do not give a procprog command */ if ( cols < expected_cols && strstr(procstat, zombie) ) { cols = expected_cols; } if ( cols >= expected_cols ) { resultsum = 0; xasprintf (&procargs, "%s", input_line + pos); strip (procargs); /* Some ps return full pathname for command. This removes path */ strcpy(procprog, base_name(procprog)); /* we need to convert the elapsed time to seconds */ procseconds = convert_to_seconds(procetime); if (verbose >= 3) printf ("proc#=%d uid=%d vsz=%d rss=%d pid=%d ppid=%d pcpu=%.2f stat=%s etime=%s prog=%s args=%s\n", procs, procuid, procvsz, procrss, procpid, procppid, procpcpu, procstat, procetime, procprog, procargs); /* Ignore self */ if (mypid == procpid) continue; if ((options & STAT) && (strstr (statopts, procstat))) resultsum |= STAT; if ((options & ARGS) && procargs && (strstr (procargs, args) != NULL)) resultsum |= ARGS; if ((options & EREG_ARGS) && procargs && (regexec(&re_args, procargs, (size_t) 0, NULL, 0) == 0)) resultsum |= EREG_ARGS; if ((options & PROG) && procprog && (strcmp (prog, procprog) == 0)) resultsum |= PROG; if ((options & PPID) && (procppid == ppid)) resultsum |= PPID; if ((options & USER) && (procuid == uid)) resultsum |= USER; if ((options & VSZ) && (procvsz >= vsz)) resultsum |= VSZ; if ((options & RSS) && (procrss >= rss)) resultsum |= RSS; if ((options & PCPU) && (procpcpu >= pcpu)) resultsum |= PCPU; found++; /* Next line if filters not matched */ if (!(options == resultsum || options == ALL)) continue; procs++; if (verbose >= 2) { printf ("Matched: uid=%d vsz=%d rss=%d pid=%d ppid=%d pcpu=%.2f stat=%s etime=%s prog=%s args=%s\n", procuid, procvsz, procrss, procpid, procppid, procpcpu, procstat, procetime, procprog, procargs); } if (metric == METRIC_VSZ) i = get_status ((double)procvsz, procs_thresholds); else if (metric == METRIC_RSS) i = get_status ((double)procrss, procs_thresholds); /* TODO? float thresholds for --metric=CPU */ else if (metric == METRIC_CPU) i = get_status (procpcpu, procs_thresholds); else if (metric == METRIC_ELAPSED) i = get_status ((double)procseconds, procs_thresholds); if (metric != METRIC_PROCS) { if (i == STATE_WARNING) { warn++; xasprintf (&fails, "%s%s%s", fails, (strcmp(fails,"") ? ", " : ""), procprog); result = max_state (result, i); } if (i == STATE_CRITICAL) { crit++; xasprintf (&fails, "%s%s%s", fails, (strcmp(fails,"") ? ", " : ""), procprog); result = max_state (result, i); } } } /* This should not happen */ else if (verbose) { printf(_("Not parseable: %s"), input_buffer); } } if (found == 0) { /* no process lines parsed so return STATE_UNKNOWN */ printf (_("Unable to read output\n")); return STATE_UNKNOWN; } if ( result == STATE_UNKNOWN ) result = STATE_OK; /* Needed if procs found, but none match filter */ if ( metric == METRIC_PROCS ) { result = max_state (result, get_status ((double)procs, procs_thresholds) ); } if ( result == STATE_OK ) { printf ("%s %s: ", metric_name, _("OK")); } else if (result == STATE_WARNING) { printf ("%s %s: ", metric_name, _("WARNING")); if ( metric != METRIC_PROCS ) { printf (_("%d warn out of "), warn); } } else if (result == STATE_CRITICAL) { printf ("%s %s: ", metric_name, _("CRITICAL")); if (metric != METRIC_PROCS) { printf (_("%d crit, %d warn out of "), crit, warn); } } printf (ngettext ("%d process", "%d processes", (unsigned long) procs), procs); if (strcmp(fmt,"") != 0) { printf (_(" with %s"), fmt); } if ( verbose >= 1 && strcmp(fails,"") ) printf (" [%s]", fails); if (metric == METRIC_PROCS) printf (" | procs=%d;%s;%s;0;", procs, warning_range ? warning_range : "", critical_range ? critical_range : ""); else printf (" | procs=%d;;;0; procs_warn=%d;;;0; procs_crit=%d;;;0;", procs, warn, crit); printf ("\n"); return result; }
/* process command-line arguments */ int process_arguments (int argc, char **argv) { int c = 1; char *user; struct passwd *pw; int option = 0; int err; int cflags = REG_NOSUB | REG_EXTENDED; char errbuf[MAX_INPUT_BUFFER]; char *temp_string; int i=0; static struct option longopts[] = { {"warning", required_argument, 0, 'w'}, {"critical", required_argument, 0, 'c'}, {"metric", required_argument, 0, 'm'}, {"timeout", required_argument, 0, 't'}, {"status", required_argument, 0, 's'}, {"ppid", required_argument, 0, 'p'}, {"command", required_argument, 0, 'C'}, {"vsz", required_argument, 0, 'z'}, {"rss", required_argument, 0, 'r'}, {"pcpu", required_argument, 0, 'P'}, {"elapsed", required_argument, 0, 'e'}, {"argument-array", required_argument, 0, 'a'}, {"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'V'}, {"verbose", no_argument, 0, 'v'}, {"ereg-argument-array", required_argument, 0, CHAR_MAX+1}, {"input-file", required_argument, 0, CHAR_MAX+2}, {0, 0, 0, 0} }; for (c = 1; c < argc; c++) if (strcmp ("-to", argv[c]) == 0) strcpy (argv[c], "-t"); while (1) { c = getopt_long (argc, argv, "Vvht:c:w:p:s:u:C:a:z:r:m:P:", longopts, &option); if (c == -1 || c == EOF) break; switch (c) { case '?': /* help */ usage5 (); case 'h': /* help */ print_help (); exit (STATE_OK); case 'V': /* version */ print_revision (progname, NP_VERSION); exit (STATE_OK); case 't': /* timeout period */ if (!is_integer (optarg)) usage2 (_("Timeout interval must be a positive integer"), optarg); else timeout_interval = atoi (optarg); break; case 'c': /* critical threshold */ critical_range = optarg; break; case 'w': /* warning threshold */ warning_range = optarg; break; case 'p': /* process id */ if (sscanf (optarg, "%d%[^0-9]", &ppid, tmp) == 1) { xasprintf (&fmt, "%s%sPPID = %d", (fmt ? fmt : "") , (options ? ", " : ""), ppid); options |= PPID; break; } usage4 (_("Parent Process ID must be an integer!")); case 's': /* status */ if (statopts) break; else statopts = optarg; xasprintf (&fmt, _("%s%sSTATE = %s"), (fmt ? fmt : ""), (options ? ", " : ""), statopts); options |= STAT; break; case 'u': /* user or user id */ if (is_integer (optarg)) { uid = atoi (optarg); pw = getpwuid ((uid_t) uid); /* check to be sure user exists */ if (pw == NULL) usage2 (_("UID was not found"), optarg); } else { pw = getpwnam (optarg); /* check to be sure user exists */ if (pw == NULL) usage2 (_("User name was not found"), optarg); /* then get uid */ uid = pw->pw_uid; } user = pw->pw_name; xasprintf (&fmt, "%s%sUID = %d (%s)", (fmt ? fmt : ""), (options ? ", " : ""), uid, user); options |= USER; break; case 'C': /* command */ /* TODO: allow this to be passed in with --metric */ if (prog) break; else prog = optarg; xasprintf (&fmt, _("%s%scommand name '%s'"), (fmt ? fmt : ""), (options ? ", " : ""), prog); options |= PROG; break; case 'a': /* args (full path name with args) */ /* TODO: allow this to be passed in with --metric */ if (args) break; else args = optarg; xasprintf (&fmt, "%s%sargs '%s'", (fmt ? fmt : ""), (options ? ", " : ""), args); options |= ARGS; break; case CHAR_MAX+1: err = regcomp(&re_args, optarg, cflags); if (err != 0) { regerror (err, &re_args, errbuf, MAX_INPUT_BUFFER); die (STATE_UNKNOWN, "PROCS %s: %s - %s\n", _("UNKNOWN"), _("Could not compile regular expression"), errbuf); } /* Strip off any | within the regex optarg */ temp_string = strdup(optarg); while(temp_string[i]!='\0'){ if(temp_string[i]=='|') temp_string[i]=','; i++; } xasprintf (&fmt, "%s%sregex args '%s'", (fmt ? fmt : ""), (options ? ", " : ""), temp_string); options |= EREG_ARGS; break; case 'r': /* RSS */ if (sscanf (optarg, "%d%[^0-9]", &rss, tmp) == 1) { xasprintf (&fmt, "%s%sRSS >= %d", (fmt ? fmt : ""), (options ? ", " : ""), rss); options |= RSS; break; } usage4 (_("RSS must be an integer!")); case 'z': /* VSZ */ if (sscanf (optarg, "%d%[^0-9]", &vsz, tmp) == 1) { xasprintf (&fmt, "%s%sVSZ >= %d", (fmt ? fmt : ""), (options ? ", " : ""), vsz); options |= VSZ; break; } usage4 (_("VSZ must be an integer!")); case 'P': /* PCPU */ /* TODO: -P 1.5.5 is accepted */ if (sscanf (optarg, "%f%[^0-9.]", &pcpu, tmp) == 1) { xasprintf (&fmt, "%s%sPCPU >= %.2f", (fmt ? fmt : ""), (options ? ", " : ""), pcpu); options |= PCPU; break; } usage4 (_("PCPU must be a float!")); case 'm': xasprintf (&metric_name, "%s", optarg); if ( strcmp(optarg, "PROCS") == 0) { metric = METRIC_PROCS; break; } else if ( strcmp(optarg, "VSZ") == 0) { metric = METRIC_VSZ; break; } else if ( strcmp(optarg, "RSS") == 0 ) { metric = METRIC_RSS; break; } else if ( strcmp(optarg, "CPU") == 0 ) { metric = METRIC_CPU; break; } else if ( strcmp(optarg, "ELAPSED") == 0) { metric = METRIC_ELAPSED; break; } usage4 (_("Metric must be one of PROCS, VSZ, RSS, CPU, ELAPSED!")); case 'v': /* command */ verbose++; break; case CHAR_MAX+2: input_filename = optarg; break; } } c = optind; if ((! warning_range) && argv[c]) warning_range = argv[c++]; if ((! critical_range) && argv[c]) critical_range = argv[c++]; if (statopts == NULL && argv[c]) { xasprintf (&statopts, "%s", argv[c++]); xasprintf (&fmt, _("%s%sSTATE = %s"), (fmt ? fmt : ""), (options ? ", " : ""), statopts); options |= STAT; } /* this will abort in case of invalid ranges */ set_thresholds (&procs_thresholds, warning_range, critical_range); return validate_arguments (); }
int main(int argc, char *argv[]){ int result, offset_result, jitter_result; double offset=0, jitter=0; char *result_line, *perfdata_line; setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); result = offset_result = jitter_result = STATE_OK; /* Parse extra opts if any */ argv=np_extra_opts (&argc, argv, progname); if (process_arguments (argc, argv) == ERROR) usage4 (_("Could not parse arguments")); set_thresholds(&offset_thresholds, owarn, ocrit); set_thresholds(&jitter_thresholds, jwarn, jcrit); /* initialize alarm signal handling */ signal (SIGALRM, socket_timeout_alarm_handler); /* set socket timeout */ alarm (socket_timeout); offset = offset_request(server_address, &offset_result); /* check_ntp used to always return CRITICAL if offset_result == STATE_UNKNOWN. * Now we'll only do that is the offset thresholds were set */ if (do_offset && offset_result == STATE_UNKNOWN) { result = STATE_CRITICAL; } else { result = get_status(fabs(offset), offset_thresholds); } /* If not told to check the jitter, we don't even send packets. * jitter is checked using NTP control packets, which not all * servers recognize. Trying to check the jitter on OpenNTPD * (for example) will result in an error */ if(do_jitter){ jitter=jitter_request(server_address, &jitter_result); result = max_state_alt(result, get_status(jitter, jitter_thresholds)); /* -1 indicates that we couldn't calculate the jitter * Only overrides STATE_OK from the offset */ if(jitter == -1.0 && result == STATE_OK) result = STATE_UNKNOWN; } result = max_state_alt(result, jitter_result); switch (result) { case STATE_CRITICAL : xasprintf(&result_line, _("NTP CRITICAL:")); break; case STATE_WARNING : xasprintf(&result_line, _("NTP WARNING:")); break; case STATE_OK : xasprintf(&result_line, _("NTP OK:")); break; default : xasprintf(&result_line, _("NTP UNKNOWN:")); break; } if(offset_result == STATE_UNKNOWN){ xasprintf(&result_line, "%s %s", result_line, _("Offset unknown")); xasprintf(&perfdata_line, ""); } else { xasprintf(&result_line, "%s %s %.10g secs", result_line, _("Offset"), offset); xasprintf(&perfdata_line, "%s", perfd_offset(offset)); } if (do_jitter) { xasprintf(&result_line, "%s, jitter=%f", result_line, jitter); xasprintf(&perfdata_line, "%s %s", perfdata_line, perfd_jitter(jitter)); } printf("%s|%s\n", result_line, perfdata_line); if(server_address!=NULL) free(server_address); return result; }
int process_arguments(int argc, char **argv){ int c; int option=0; static struct option longopts[] = { {"version", no_argument, 0, 'V'}, {"help", no_argument, 0, 'h'}, {"verbose", no_argument, 0, 'v'}, {"use-ipv4", no_argument, 0, '4'}, {"use-ipv6", no_argument, 0, '6'}, {"warning", required_argument, 0, 'w'}, {"critical", required_argument, 0, 'c'}, {"jwarn", required_argument, 0, 'j'}, {"jcrit", required_argument, 0, 'k'}, {"timeout", required_argument, 0, 't'}, {"hostname", required_argument, 0, 'H'}, {0, 0, 0, 0} }; if (argc < 2) usage ("\n"); while (1) { c = getopt_long (argc, argv, "Vhv46w:c:j:k:t:H:", longopts, &option); if (c == -1 || c == EOF || c == 1) break; switch (c) { case 'h': print_help(); exit(STATE_OK); break; case 'V': print_revision(progname, NP_VERSION); exit(STATE_OK); break; case 'v': verbose++; break; case 'w': do_offset=1; owarn = optarg; break; case 'c': do_offset=1; ocrit = optarg; break; case 'j': do_jitter=1; jwarn = optarg; break; case 'k': do_jitter=1; jcrit = optarg; break; case 'H': if(is_host(optarg) == FALSE) usage2(_("Invalid hostname/address"), optarg); server_address = strdup(optarg); break; case 't': socket_timeout=atoi(optarg); break; case '4': address_family = AF_INET; break; case '6': #ifdef USE_IPV6 address_family = AF_INET6; #else usage4 (_("IPv6 support not available")); #endif break; case '?': /* print short usage statement if args not parsable */ usage5 (); break; } } if(server_address == NULL){ usage4(_("Hostname was not supplied")); } return 0; }
int main (int argc, char **argv) { MYSQL mysql; MYSQL_RES *res; MYSQL_ROW row; double value; char *error = NULL; int status; setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); /* Parse extra opts if any */ argv=np_extra_opts (&argc, argv, progname); if (process_arguments (argc, argv) == ERROR) usage4 (_("Could not parse arguments")); /* initialize mysql */ mysql_init (&mysql); mysql_options(&mysql,MYSQL_READ_DEFAULT_GROUP,"client"); /* establish a connection to the server and error checking */ if (!mysql_real_connect(&mysql,db_host,db_user,db_pass,db,db_port,db_socket,0)) { if (mysql_errno (&mysql) == CR_UNKNOWN_HOST) die (STATE_WARNING, "QUERY %s: %s\n", _("WARNING"), mysql_error (&mysql)); else if (mysql_errno (&mysql) == CR_VERSION_ERROR) die (STATE_WARNING, "QUERY %s: %s\n", _("WARNING"), mysql_error (&mysql)); else if (mysql_errno (&mysql) == CR_OUT_OF_MEMORY) die (STATE_WARNING, "QUERY %s: %s\n", _("WARNING"), mysql_error (&mysql)); else if (mysql_errno (&mysql) == CR_IPSOCK_ERROR) die (STATE_WARNING, "QUERY %s: %s\n", _("WARNING"), mysql_error (&mysql)); else if (mysql_errno (&mysql) == CR_SOCKET_CREATE_ERROR) die (STATE_WARNING, "QUERY %s: %s\n", _("WARNING"), mysql_error (&mysql)); else die (STATE_CRITICAL, "QUERY %s: %s\n", _("CRITICAL"), mysql_error (&mysql)); } if (mysql_query (&mysql, sql_query) != 0) { error = strdup(mysql_error(&mysql)); mysql_close (&mysql); die (STATE_CRITICAL, "QUERY %s: %s - %s\n", _("CRITICAL"), _("Error with query"), error); } /* store the result */ if ( (res = mysql_store_result (&mysql)) == NULL) { error = strdup(mysql_error(&mysql)); mysql_close (&mysql); die (STATE_CRITICAL, "QUERY %s: Error with store_result - %s\n", _("CRITICAL"), error); } /* Check there is some data */ if (mysql_num_rows(res) == 0) { mysql_close(&mysql); die (STATE_WARNING, "QUERY %s: %s\n", _("WARNING"), _("No rows returned")); } /* fetch the first row */ if ( (row = mysql_fetch_row (res)) == NULL) { error = strdup(mysql_error(&mysql)); mysql_free_result (res); mysql_close (&mysql); die (STATE_CRITICAL, "QUERY %s: Fetch row error - %s\n", _("CRITICAL"), error); } /* free the result */ mysql_free_result (res); /* close the connection */ mysql_close (&mysql); if (! is_numeric(row[0])) { die (STATE_CRITICAL, "QUERY %s: %s - '%s'\n", _("CRITICAL"), _("Is not a numeric"), row[0]); } value = strtod(row[0], NULL); if (verbose >= 3) printf("mysql result: %f\n", value); status = get_status(value, my_thresholds); if (status == STATE_OK) { printf("QUERY %s: ", _("OK")); } else if (status == STATE_WARNING) { printf("QUERY %s: ", _("WARNING")); } else if (status == STATE_CRITICAL) { printf("QUERY %s: ", _("CRITICAL")); } printf(_("'%s' returned %f"), sql_query, value); printf("\n"); return status; }
void set_timeout_state (char *state) { if ((timeout_state = translate_state(state)) == ERROR) usage4 (_("Timeout result must be a valid state name (OK, WARNING, CRITICAL, UNKNOWN) or integer (0-3).")); }