Exemplo n.º 1
0
char *perfd_offset (double offset)
{
	return fperfdata ("offset", offset, "s",
		TRUE, offset_thresholds->warning->end,
		TRUE, offset_thresholds->critical->end,
		FALSE, 0, FALSE, 0);
}
Exemplo n.º 2
0
char *perfd_jitter (double jitter)
{
	return fperfdata ("jitter", jitter, "s",
		do_jitter, jitter_thresholds->warning->end,
		do_jitter, jitter_thresholds->critical->end,
		TRUE, 0, FALSE, 0);
}
Exemplo n.º 3
0
int
ssh_connect (char *haddr, int hport, char *remote_version)
{
	int sd;
	int result;
	char *output = NULL;
	char *buffer = NULL;
	char *ssh_proto = NULL;
	char *ssh_server = NULL;
	static char *rev_no = VERSION;
	struct timeval tv;
	double elapsed_time;

	gettimeofday(&tv, NULL);

	result = my_tcp_connect (haddr, hport, &sd);

	if (result != STATE_OK)
		return result;

	output = (char *) malloc (BUFF_SZ + 1);
	memset (output, 0, BUFF_SZ + 1);
	recv (sd, output, BUFF_SZ, 0);
	if (strncmp (output, "SSH", 3)) {
		printf (_("Server answer: %s"), output);
		close(sd);
		exit (STATE_CRITICAL);
	}
	else {
		strip (output);
		if (verbose)
			printf ("%s\n", output);
		ssh_proto = output + 4;
		ssh_server = ssh_proto + strspn (ssh_proto, "-0123456789. ");
		ssh_proto[strspn (ssh_proto, "0123456789. ")] = 0;

		xasprintf (&buffer, "SSH-%s-check_ssh_%s\r\n", ssh_proto, rev_no);
		send (sd, buffer, strlen (buffer), MSG_DONTWAIT);
		if (verbose)
			printf ("%s\n", buffer);

		if (remote_version && strcmp(remote_version, ssh_server)) {
			printf
				(_("SSH WARNING - %s (protocol %s) version mismatch, expected '%s'\n"),
				 ssh_server, ssh_proto, remote_version);
			close(sd);
			exit (STATE_WARNING);
		}

		elapsed_time = (double)deltime(tv) / 1.0e6;

		printf
			(_("SSH OK - %s (protocol %s) | %s\n"),
			 ssh_server, ssh_proto, fperfdata("time", elapsed_time, "s",
			 FALSE, 0, FALSE, 0, TRUE, 0, TRUE, (int)socket_timeout));
		close(sd);
		exit (STATE_OK);
	}
}
Exemplo n.º 4
0
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
Exemplo n.º 5
0
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;
}
Exemplo n.º 6
0
int
main (int argc, char **argv)
{
  char *command_line = NULL;
  char input_buffer[MAX_INPUT_BUFFER];
  char *address = NULL; /* comma seperated str with addrs/ptrs (sorted) */
  char **addresses = NULL;
  int n_addresses = 0;
  char *msg = NULL;
  char *temp_buffer = NULL;
  int non_authoritative = FALSE;
  int result = STATE_UNKNOWN;
  double elapsed_time;
  long microsec;
  struct timeval tv;
  int multi_address;
  int parse_address = FALSE; /* This flag scans for Address: but only after Name: */
  output chld_out, chld_err;
  size_t i;

  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);

  /* Set signal handling and alarm */
  if (signal (SIGALRM, runcmd_timeout_alarm_handler) == SIG_ERR) {
    usage_va(_("Cannot catch SIGALRM"));
  }

  /* Parse extra opts if any */
  argv=np_extra_opts (&argc, argv, progname);

  if (process_arguments (argc, argv) == ERROR) {
    usage_va(_("Could not parse arguments"));
  }

  /* get the command to run */
  xasprintf (&command_line, "%s %s %s", NSLOOKUP_COMMAND, query_address, dns_server);

  alarm (timeout_interval);
  gettimeofday (&tv, NULL);

  if (verbose)
    printf ("%s\n", command_line);

  /* run the command */
  if((np_runcmd(command_line, &chld_out, &chld_err, 0)) != 0) {
    msg = (char *)_("nslookup returned an error status");
    result = STATE_WARNING;
  }

  /* scan stdout */
  for(i = 0; i < chld_out.lines; i++) {
    if (addresses == NULL)
      addresses = malloc(sizeof(*addresses)*10);
    else if (!(n_addresses % 10))
      addresses = realloc(addresses,sizeof(*addresses) * (n_addresses + 10));

    if (verbose)
      puts(chld_out.line[i]);

    if (strstr (chld_out.line[i], ".in-addr.arpa")) {
      if ((temp_buffer = strstr (chld_out.line[i], "name = ")))
        addresses[n_addresses++] = strdup (temp_buffer + 7);
      else {
        msg = (char *)_("Warning plugin error");
        result = STATE_WARNING;
      }
    }

    /* the server is responding, we just got the host name... */
    if (strstr (chld_out.line[i], "Name:"))
      parse_address = TRUE;
    else if (parse_address == TRUE && (strstr (chld_out.line[i], "Address:") ||
             strstr (chld_out.line[i], "Addresses:"))) {
      temp_buffer = index (chld_out.line[i], ':');
      temp_buffer++;

      /* Strip leading spaces */
      for (; *temp_buffer != '\0' && *temp_buffer == ' '; temp_buffer++)
        /* NOOP */;

      strip(temp_buffer);
      if (temp_buffer==NULL || strlen(temp_buffer)==0) {
        die (STATE_CRITICAL,
             _("DNS CRITICAL - '%s' returned empty host name string\n"),
             NSLOOKUP_COMMAND);
      }

      addresses[n_addresses++] = strdup(temp_buffer);
    }
    else if (strstr (chld_out.line[i], _("Non-authoritative answer:"))) {
      non_authoritative = TRUE;
    }


    result = error_scan (chld_out.line[i]);
    if (result != STATE_OK) {
      msg = strchr (chld_out.line[i], ':');
      if(msg) msg++;
      break;
    }
  }

  /* scan stderr */
  for(i = 0; i < chld_err.lines; i++) {
    if (verbose)
      puts(chld_err.line[i]);

    if (error_scan (chld_err.line[i]) != STATE_OK) {
      result = max_state (result, error_scan (chld_err.line[i]));
      msg = strchr(input_buffer, ':');
      if(msg) msg++;
    }
  }

  if (addresses) {
    int i,slen;
    char *adrp;
    qsort(addresses, n_addresses, sizeof(*addresses), qstrcmp);
    for(i=0, slen=1; i < n_addresses; i++) {
      slen += strlen(addresses[i])+1;
    }
    adrp = address = malloc(slen);
    for(i=0; i < n_addresses; i++) {
      if (i) *adrp++ = ',';
      strcpy(adrp, addresses[i]);
      adrp += strlen(addresses[i]);
    }
    *adrp = 0;
  } else
    die (STATE_CRITICAL,
         _("DNS CRITICAL - '%s' msg parsing exited with no address\n"),
         NSLOOKUP_COMMAND);

  /* compare to expected address */
  if (result == STATE_OK && expected_address_cnt > 0) {
    result = STATE_CRITICAL;
    temp_buffer = "";
    for (i=0; i<expected_address_cnt; i++) {
      /* check if we get a match and prepare an error string */
      if (strcmp(address, expected_address[i]) == 0) result = STATE_OK;
      xasprintf(&temp_buffer, "%s%s; ", temp_buffer, expected_address[i]);
    }
    if (result == STATE_CRITICAL) {
      /* Strip off last semicolon... */
      temp_buffer[strlen(temp_buffer)-2] = '\0';
      xasprintf(&msg, _("expected '%s' but got '%s'"), temp_buffer, address);
    }
  }

  /* check if authoritative */
  if (result == STATE_OK && expect_authority && non_authoritative) {
    result = STATE_CRITICAL;
    xasprintf(&msg, _("server %s is not authoritative for %s"), dns_server, query_address);
  }

  microsec = deltime (tv);
  elapsed_time = (double)microsec / 1.0e6;

  if (result == STATE_OK) {
    if (strchr (address, ',') == NULL)
      multi_address = FALSE;
    else
      multi_address = TRUE;

    result = get_status(elapsed_time, time_thresholds);
    if (result == STATE_OK) {
      printf ("DNS %s: ", _("OK"));
    } else if (result == STATE_WARNING) {
      printf ("DNS %s: ", _("WARNING"));
    } else if (result == STATE_CRITICAL) {
      printf ("DNS %s: ", _("CRITICAL"));
    }
    printf (ngettext("%.3f second response time", "%.3f seconds response time", elapsed_time), elapsed_time);
    printf (_(". %s returns %s"), query_address, address);
    printf ("|%s\n", fperfdata ("time", elapsed_time, "s", FALSE, 0, FALSE, 0, TRUE, 0, FALSE, 0));
  }
  else if (result == STATE_WARNING)
    printf (_("DNS WARNING - %s\n"),
            !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);
  else if (result == STATE_CRITICAL)
    printf (_("DNS CRITICAL - %s\n"),
            !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);
  else
    printf (_("DNS UNKNOWN - %s\n"),
            !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);

  return result;
}
Exemplo n.º 7
0
int
main (int argc, char **argv)
{
  char *command_line;
  int result = STATE_UNKNOWN;
  char *p, *ret[QSTAT_MAX_RETURN_ARGS];
  size_t i = 0;
  output chld_out;

  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)
    usage_va(_("Could not parse arguments"));

  result = STATE_OK;

  /* create the command line to execute */
  xasprintf (&command_line, "%s -raw %s -%s %s",
            PATH_TO_QSTAT, QSTAT_DATA_DELIMITER, game_type, server_ip);

  if (port)
    xasprintf (&command_line, "%s:%-d", command_line, port);

  if (verbose > 0)
    printf ("%s\n", command_line);

  /* run the command. historically, this plugin ignores output on stderr,
   * as well as return status of the qstat program */
  (void)np_runcmd(command_line, &chld_out, NULL, 0);

  /* sanity check */
  /* was thinking about running qstat without any options, capturing the
     -default line, parsing it & making an array of all know server types
     but thought this would be too much hassle considering this is a tool
     for intelligent sysadmins (ha). Could put a static array of known
     server types in a header file but then we'd be limiting ourselves

     In the end, I figured I'd simply let an error occur & then trap it
   */

  if (!strncmp (chld_out.line[0], "unknown option", 14)) {
    printf (_("CRITICAL - Host type parameter incorrect!\n"));
    result = STATE_CRITICAL;
    return result;
  }

  p = (char *) strtok (chld_out.line[0], QSTAT_DATA_DELIMITER);
  while (p != NULL) {
    ret[i] = p;
    p = (char *) strtok (NULL, QSTAT_DATA_DELIMITER);
    i++;
    if (i >= QSTAT_MAX_RETURN_ARGS)
      break;
  }

  if (strstr (ret[2], QSTAT_HOST_ERROR)) {
    printf (_("CRITICAL - Host not found\n"));
    result = STATE_CRITICAL;
  }
  else if (strstr (ret[2], QSTAT_HOST_DOWN)) {
    printf (_("CRITICAL - Game server down or unavailable\n"));
    result = STATE_CRITICAL;
  }
  else if (strstr (ret[2], QSTAT_HOST_TIMEOUT)) {
    printf (_("CRITICAL - Game server timeout\n"));
    result = STATE_CRITICAL;
  }
  else {
    printf ("OK: %s/%s %s (%s), Ping: %s ms|%s %s\n",
            ret[qstat_game_players],
            ret[qstat_game_players_max],
            ret[qstat_game_field],
            ret[qstat_map_field],
            ret[qstat_ping_field],
            perfdata ("players", atol(ret[qstat_game_players]), "",
                      FALSE, 0, FALSE, 0,
                      TRUE, 0, TRUE, atol(ret[qstat_game_players_max])),
            fperfdata ("ping", strtod(ret[qstat_ping_field], NULL), "",
                      FALSE, 0, FALSE, 0,
                      TRUE, 0, FALSE, 0));
  }

  return result;
}
Exemplo n.º 8
0
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;
}
Exemplo n.º 9
0
int
main (int argc, char **argv)
{
	PGconn *conn;
	char *conninfo = NULL;

	struct timeval start_timeval;
	struct timeval end_timeval;
	double elapsed_time;
	int status = STATE_UNKNOWN;
	int query_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);

	/* Parse extra opts if any */
	argv=np_extra_opts (&argc, argv, progname);

	if (process_arguments (argc, argv) == ERROR)
		usage4 (_("Could not parse arguments"));
	if (verbose > 2)
		printf("Arguments initialized\n");

	/* Set signal handling and alarm */
	if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) {
		usage4 (_("Cannot catch SIGALRM"));
	}
	alarm (timeout_interval);

	if (pgparams)
		asprintf (&conninfo, "%s ", pgparams);

	asprintf (&conninfo, "%sdbname = '%s'", conninfo ? conninfo : "", dbName);
	if (pghost)
		asprintf (&conninfo, "%s host = '%s'", conninfo, pghost);
	if (pgport)
		asprintf (&conninfo, "%s port = '%s'", conninfo, pgport);
	if (pgoptions)
		asprintf (&conninfo, "%s options = '%s'", conninfo, pgoptions);
	/* if (pgtty) -- ignored by PQconnectdb */
	if (pguser)
		asprintf (&conninfo, "%s user = '******'", conninfo, pguser);

	if (verbose) /* do not include password (see right below) in output */
		printf ("Connecting to PostgreSQL using conninfo: %s%s\n", conninfo,
				pgpasswd ? " password = <hidden>" : "");

	if (pgpasswd)
		asprintf (&conninfo, "%s password = '******'", conninfo, pgpasswd);

	/* make a connection to the database */
	gettimeofday (&start_timeval, NULL);
	conn = PQconnectdb (conninfo);
	gettimeofday (&end_timeval, NULL);

	while (start_timeval.tv_usec > end_timeval.tv_usec) {
		--end_timeval.tv_sec;
		end_timeval.tv_usec += 1000000;
	}
	elapsed_time = (double)(end_timeval.tv_sec - start_timeval.tv_sec)
		+ (double)(end_timeval.tv_usec - start_timeval.tv_usec) / 1000000.0;

	if (verbose)
		printf("Time elapsed: %f\n", elapsed_time);

	/* check to see that the backend connection was successfully made */
	if (verbose)
		printf("Verifying connection\n");
	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;
	}

	if (verbose) {
		char *server_host = PQhost (conn);
		int server_version = PQserverVersion (conn);

		printf ("Successfully connected to database %s (user %s) "
				"at server %s%s%s (server version: %d.%d.%d, "
				"protocol version: %d, pid: %d)\n",
				PQdb (conn), PQuser (conn),
				PSQL_SOCKET3 (server_host, PQport (conn)),
				PSQL_SERVER_VERSION3 (server_version),
				PQprotocolVersion (conn), PQbackendPID (conn));
	}

	printf (_(" %s - database %s (%f sec.)|%s\n"),
	        state_text(status), dbName, elapsed_time,
	        fperfdata("time", elapsed_time, "s",
	                 !!(twarn > 0.0), twarn, !!(tcrit > 0.0), tcrit, TRUE, 0, FALSE,0));

	if (pgquery)
		query_status = do_query (conn, pgquery);

	if (verbose)
		printf("Closing connection\n");
	PQfinish (conn);
	return (pgquery && query_status > status) ? query_status : status;
}
Exemplo n.º 10
0
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;
}
Exemplo n.º 11
0
int
main (int argc, char **argv)
{
	int result = STATE_OK;
	FILE *fp;
	int line;
	char input_buffer[MAX_INPUT_BUFFER];
	char *temp_buffer;
	time_t current_time;
	char *error_message;
	time_t timestamp = 0L;
	unsigned long average_incoming_rate = 0L;
	unsigned long average_outgoing_rate = 0L;
	unsigned long maximum_incoming_rate = 0L;
	unsigned long maximum_outgoing_rate = 0L;
	unsigned long incoming_rate = 0L;
	unsigned long outgoing_rate = 0L;
	double adjusted_incoming_rate = 0.0;
	double adjusted_outgoing_rate = 0.0;
	char incoming_speed_rating[8];
	char outgoing_speed_rating[8];

	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"));

	/* open the MRTG log file for reading */
	fp = fopen (log_file, "r");
	if (fp == NULL)
		usage4 (_("Unable to open MRTG log file"));

	line = 0;
	while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, fp)) {

		line++;

		/* skip the first line of the log file */
		if (line == 1)
			continue;

		/* break out of read loop */
		/* if we've passed the number of entries we want to read */
		if (line > 2)
			break;

		/* grab the timestamp */
		temp_buffer = strtok (input_buffer, " ");
		timestamp = strtoul (temp_buffer, NULL, 10);

		/* grab the average incoming transfer rate */
		temp_buffer = strtok (NULL, " ");
		average_incoming_rate = strtoul (temp_buffer, NULL, 10);

		/* grab the average outgoing transfer rate */
		temp_buffer = strtok (NULL, " ");
		average_outgoing_rate = strtoul (temp_buffer, NULL, 10);

		/* grab the maximum incoming transfer rate */
		temp_buffer = strtok (NULL, " ");
		maximum_incoming_rate = strtoul (temp_buffer, NULL, 10);

		/* grab the maximum outgoing transfer rate */
		temp_buffer = strtok (NULL, " ");
		maximum_outgoing_rate = strtoul (temp_buffer, NULL, 10);
	}

	/* close the log file */
	fclose (fp);

	/* if we couldn't read enough data, return an unknown error */
	if (line <= 2)
		usage4 (_("Unable to process MRTG log file"));

	/* make sure the MRTG data isn't too old */
	time (&current_time);
	if ((expire_minutes > 0) &&
	    (current_time - timestamp) > (expire_minutes * 60))
		die (STATE_WARNING,	_("MRTG data has expired (%d minutes old)\n"),
		     (int) ((current_time - timestamp) / 60));

	/* else check the incoming/outgoing rates */
	if (use_average == TRUE) {
		incoming_rate = average_incoming_rate;
		outgoing_rate = average_outgoing_rate;
	}
	else {
		incoming_rate = maximum_incoming_rate;
		outgoing_rate = maximum_outgoing_rate;
	}

	/* report incoming traffic in Bytes/sec */
	if (incoming_rate < 1024) {
		strcpy (incoming_speed_rating, "B/s");
		adjusted_incoming_rate = (double) incoming_rate;
	}

	/* report incoming traffic in KBytes/sec */
	else if (incoming_rate < (1024 * 1024)) {
		strcpy (incoming_speed_rating, "KB/s");
		adjusted_incoming_rate = (double) (incoming_rate / 1024.0);
	}

	/* report incoming traffic in MBytes/sec */
	else {
		strcpy (incoming_speed_rating, "MB/s");
		adjusted_incoming_rate = (double) (incoming_rate / 1024.0 / 1024.0);
	}

	/* report outgoing traffic in Bytes/sec */
	if (outgoing_rate < 1024) {
		strcpy (outgoing_speed_rating, "B/s");
		adjusted_outgoing_rate = (double) outgoing_rate;
	}

	/* report outgoing traffic in KBytes/sec */
	else if (outgoing_rate < (1024 * 1024)) {
		strcpy (outgoing_speed_rating, "KB/s");
		adjusted_outgoing_rate = (double) (outgoing_rate / 1024.0);
	}

	/* report outgoing traffic in MBytes/sec */
	else {
		strcpy (outgoing_speed_rating, "MB/s");
		adjusted_outgoing_rate = (double) (outgoing_rate / 1024.0 / 1024.0);
	}

	if (incoming_rate > incoming_critical_threshold
			|| outgoing_rate > outgoing_critical_threshold) {
		result = STATE_CRITICAL;
	}
	else if (incoming_rate > incoming_warning_threshold
					 || outgoing_rate > outgoing_warning_threshold) {
		result = STATE_WARNING;
	}

	xasprintf (&error_message, _("%s. In = %0.1f %s, %s. Out = %0.1f %s|%s %s\n"),
	          (use_average == TRUE) ? _("Avg") : _("Max"), adjusted_incoming_rate,
	          incoming_speed_rating, (use_average == TRUE) ? _("Avg") : _("Max"),
	          adjusted_outgoing_rate, outgoing_speed_rating,
	          fperfdata("in", adjusted_incoming_rate, incoming_speed_rating,
	                   (int)incoming_warning_threshold, incoming_warning_threshold,
	                   (int)incoming_critical_threshold, incoming_critical_threshold,
	                   TRUE, 0, FALSE, 0),
	          fperfdata("out", adjusted_outgoing_rate, outgoing_speed_rating,
	                   (int)outgoing_warning_threshold, outgoing_warning_threshold,
	                   (int)outgoing_critical_threshold, outgoing_critical_threshold,
	                   TRUE, 0, FALSE, 0));

	printf (_("Traffic %s - %s\n"), state_text(result), error_message);

	return result;
}
Exemplo n.º 12
0
int
textscan (char *buf)
{
  char *rtastr = NULL;
  char *losstr = NULL;
  char *xmtstr = NULL;
  double loss;
  double rta;
  double xmt;
  int status = STATE_UNKNOWN;

  if (strstr (buf, "not found")) {
    die (STATE_CRITICAL, _("FPING UNKNOW - %s not found\n"), server_name);

  }
  else if (strstr (buf, "is unreachable") || strstr (buf, "Unreachable")) {
    die (STATE_CRITICAL, _("FPING CRITICAL - %s is unreachable\n"),
               "host");

  }
  else if (strstr (buf, "Operation not permitted") || strstr (buf, "No such device") ) {
    die (STATE_UNKNOWN, _("FPING UNKNOWN - %s parameter error\n"),
               "host");
  }
  else if (strstr (buf, "is down")) {
    die (STATE_CRITICAL, _("FPING CRITICAL - %s is down\n"), server_name);

  }
  else if (strstr (buf, "is alive")) {
    status = STATE_OK;

  }
  else if (strstr (buf, "xmt/rcv/%loss") && strstr (buf, "min/avg/max")) {
    losstr = strstr (buf, "=");
    losstr = 1 + strstr (losstr, "/");
    losstr = 1 + strstr (losstr, "/");
    rtastr = strstr (buf, "min/avg/max");
    rtastr = strstr (rtastr, "=");
    rtastr = 1 + index (rtastr, '/');
    loss = strtod (losstr, NULL);
    rta = strtod (rtastr, NULL);
    if (cpl_p == TRUE && loss > cpl)
      status = STATE_CRITICAL;
    else if (crta_p == TRUE  && rta > crta)
      status = STATE_CRITICAL;
    else if (wpl_p == TRUE && loss > wpl)
      status = STATE_WARNING;
    else if (wrta_p == TRUE && rta > wrta)
      status = STATE_WARNING;
    else
      status = STATE_OK;
    die (status,
          _("FPING %s - %s (loss=%.0f%%, rta=%f ms)|%s %s\n"),
         state_text (status), server_name, loss, rta,
         perfdata ("loss", (long int)loss, "%", wpl_p, wpl, cpl_p, cpl, TRUE, 0, TRUE, 100),
         fperfdata ("rta", rta/1.0e3, "s", wrta_p, wrta/1.0e3, crta_p, crta/1.0e3, TRUE, 0, FALSE, 0));

  }
  else if(strstr (buf, "xmt/rcv/%loss") ) {
    /* no min/max/avg if host was unreachable in fping v2.2.b1 */
    /* in v2.4b2: 10.99.0.1 : xmt/rcv/%loss = 0/0/0% */
    losstr = strstr (buf, "=");
    xmtstr = 1 + losstr;
    xmt = strtod (xmtstr, NULL);
    if(xmt == 0)
        die (STATE_CRITICAL, _("FPING CRITICAL - %s is down\n"), server_name);
    losstr = 1 + strstr (losstr, "/");
    losstr = 1 + strstr (losstr, "/");
    loss = strtod (losstr, NULL);
    if (atoi(losstr) == 100)
      status = STATE_CRITICAL;
    else if (cpl_p == TRUE && loss > cpl)
      status = STATE_CRITICAL;
    else if (wpl_p == TRUE && loss > wpl)
      status = STATE_WARNING;
    else
      status = STATE_OK;
    /* loss=%.0f%%;%d;%d;0;100 */
    die (status, _("FPING %s - %s (loss=%.0f%% )|%s\n"),
         state_text (status), server_name, loss ,
         perfdata ("loss", (long int)loss, "%", wpl_p, wpl, cpl_p, cpl, TRUE, 0, TRUE, 100));

  }
  else {
    status = max_state (status, STATE_WARNING);
  }

  return status;
}
Exemplo n.º 13
0
int
main (int argc, char **argv)
{
  char *command_line = NULL;
  char input_buffer[MAX_INPUT_BUFFER];
  char *address = NULL; /* comma seperated str with addrs/ptrs (sorted) */
  char **addresses = NULL;
  int n_addresses = 0;
  char *msg = NULL;
  char query_found[16] = "";
  char *temp_buffer = NULL;
  int non_authoritative = TRUE;
  int result = STATE_UNKNOWN;
  double elapsed_time;
  long microsec;
  struct timeval tv;
  int multi_address;
  int parse_address = FALSE; /* This flag scans for Address: but only after Name: */
  output chld_out, chld_err;
  size_t i;

  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);

  /* Set signal handling and alarm */
  if (signal (SIGALRM, runcmd_timeout_alarm_handler) == SIG_ERR) {
    usage_va(_("Cannot catch SIGALRM"));
  }

  /* Parse extra opts if any */
  argv=np_extra_opts (&argc, argv, progname);

  if (process_arguments (argc, argv) == ERROR) {
    usage_va(_("Could not parse arguments"));
  }

  /* get the command to run */
  xasprintf (&command_line, "%s %s %s %s", NSLOOKUP_COMMAND, query_type, query_address, dns_server);

  alarm (timeout_interval);
  gettimeofday (&tv, NULL);

  if (verbose)
    printf ("%s\n", command_line);

  /* run the command */
  if((np_runcmd(command_line, &chld_out, &chld_err, 0)) != 0) {
    msg = (char *)_("nslookup returned an error status");
    result = STATE_WARNING;
  }

  /* scan stdout */
  for(i = 0; i < chld_out.lines; i++) {
    if (addresses == NULL)
      addresses = malloc(sizeof(*addresses)*10);
    else if (!(n_addresses % 10))
      addresses = realloc(addresses,sizeof(*addresses) * (n_addresses + 10));

    if (verbose)
      puts(chld_out.line[i]);

    if (strstr (chld_out.line[i], "Authoritative answers can be found from:")) {
      non_authoritative = FALSE;
      break;
    }
    /* the server is responding, we just got the host name... */
    if (strstr (chld_out.line[i], "Name:"))
      parse_address = TRUE;
    /* begin handling types of records */
    if (strstr (chld_out.line[i], "AAAA address")) {
      if (verbose) printf("Found AAAA record\n");
      temp_buffer = rindex (chld_out.line[i], ' ');
      addresses[n_addresses++] = check_new_address(temp_buffer);
      strncpy(query_found, "-querytype=AAAA", sizeof(query_found));
    }
    else if (strstr (chld_out.line[i], "exchanger =")) {
      if (verbose) printf("Found MX record\n");
      temp_buffer = index (chld_out.line[i], '=');
      addresses[n_addresses++] = check_new_address(temp_buffer);
      strncpy(query_found, "-querytype=MX", sizeof(query_found));
    }
    else if (strstr (chld_out.line[i], "service =")) {
      if (verbose) printf("Found SRV record\n");
      temp_buffer = index (chld_out.line[i], '=');
      addresses[n_addresses++] = check_new_address(temp_buffer);
      strncpy(query_found, "-querytype=SRV", sizeof(query_found));
    }
    else if (accept_cname && strstr (chld_out.line[i], "canonical name =")) {
      if (verbose) printf("Found CNAME record\n");
      temp_buffer = index (chld_out.line[i], '=');
      addresses[n_addresses++] = check_new_address(temp_buffer);
      strncpy(query_found, "-querytype=CNAME", sizeof(query_found));
    }
    else if (parse_address == TRUE && (strstr (chld_out.line[i], "Address:") || strstr (chld_out.line[i], "Addresses:"))) {
      if (verbose) printf("Found A record\n");
      temp_buffer = index (chld_out.line[i], ':');
      addresses[n_addresses++] = check_new_address(temp_buffer);
      strncpy(query_found, "-querytype=A", sizeof(query_found));
    }
    else if (strstr (chld_out.line[i], "nameserver =")) {
      if (verbose) printf("Found NS record\n");
      temp_buffer = index (chld_out.line[i], '=');
      addresses[n_addresses++] = check_new_address(temp_buffer);
      strncpy(query_found, "-querytype=NS", sizeof(query_found));
    }
    else if (strstr (chld_out.line[i], "dname =")) {
      if (verbose) printf("Found DNAME record\n");
      temp_buffer = index (chld_out.line[i], '=');
      addresses[n_addresses++] = check_new_address(temp_buffer);
      strncpy(query_found, "-querytype=DNAME", sizeof(query_found));
    }
    /* must be after other records with "name" as an identifier, as ptr does not spefify */
    else if (strstr (chld_out.line[i], "name =")) {
      if (verbose) printf("Found PTR record\n");
      temp_buffer = index (chld_out.line[i], '=');
      addresses[n_addresses++] = check_new_address(temp_buffer);
      strncpy(query_found, "-querytype=PTR", sizeof(query_found));
    }
    else if (strstr (chld_out.line[i], "protocol =")) {
      if (verbose) printf("Found WKS record\n");
      temp_buffer = index (chld_out.line[i], '=');
      addresses[n_addresses++] = check_new_address(temp_buffer);
      strncpy(query_found, "-querytype=WKS", sizeof(query_found));
    }
    /* TODO: needs to be changed to handle txt output and max size of txt recrods */
    else if (strstr (chld_out.line[i], "text =")) {
      if (verbose) printf("Found TXT record\n");
      temp_buffer = index (chld_out.line[i], '=');
      addresses[n_addresses++] = check_new_address(temp_buffer);
      strncpy(query_found, "-querytype=TXT", sizeof(query_found));
    }
    /* only matching for origin records, if requested other fields could be included at a later date */
    else if (strstr (chld_out.line[i], "origin =")) {
      if (verbose) printf("Found SOA record\n");
      temp_buffer = index(chld_out.line[i], '=');
      addresses[n_addresses++] = check_new_address(temp_buffer);
      strncpy(query_found, "-querytype=SOA", sizeof(query_found));
    }

    if (strstr (chld_out.line[i], _("Non-authoritative answer:"))) {
      non_authoritative = TRUE;
    }

    result = error_scan (chld_out.line[i]);
    if (result != STATE_OK) {
      msg = strchr (chld_out.line[i], ':');
      if(msg) msg++;
      break;
    }
  }

  /* scan stderr */
  for(i = 0; i < chld_err.lines; i++) { 
    if (verbose)
      puts(chld_err.line[i]);

    if (error_scan (chld_err.line[i]) != STATE_OK) {
      result = max_state (result, error_scan (chld_err.line[i]));
      msg = strchr(input_buffer, ':');
      if(msg) msg++;
    }
  }

  if (addresses) {
    int i,slen;
    char *adrp;
    qsort(addresses, n_addresses, sizeof(*addresses), qstrcmp);
    for(i=0, slen=1; i < n_addresses; i++) {
      slen += strlen(addresses[i])+1;
    }
    adrp = address = malloc(slen);
    for(i=0; i < n_addresses; i++) {
      if (i) *adrp++ = ',';
      strcpy(adrp, addresses[i]);
      adrp += strlen(addresses[i]);
    }
    *adrp = 0;
  } else
    die (STATE_CRITICAL,
         _("DNS CRITICAL - '%s' msg parsing exited with no address\n"),
         NSLOOKUP_COMMAND);

  /* compare to expected address */
  if (result == STATE_OK && expected_address_cnt > 0) {
    result = STATE_CRITICAL;
    temp_buffer = "";
    for (i=0; i<expected_address_cnt; i++) {
      /* check if we get a match and prepare an error string */
      if (strcmp(address, expected_address[i]) == 0) result = STATE_OK;
      xasprintf(&temp_buffer, "%s%s; ", temp_buffer, expected_address[i]);
    }
    if (result == STATE_CRITICAL) {
      /* Strip off last semicolon... */
      temp_buffer[strlen(temp_buffer)-2] = '\0';
      xasprintf(&msg, _("expected '%s' but got '%s'"), temp_buffer, address);
    }
  }

  /* check if authoritative */
  if (result == STATE_OK && expect_authority && !non_authoritative) {
    result = STATE_CRITICAL;

    if (strncmp(dns_server, "", 1))
      xasprintf(&msg, _("server %s is not authoritative for %s"), dns_server, query_address);
    else
      xasprintf(&msg, _("there is no authoritative server for %s"), query_address);
  }

  /* compare query type to query found, if query type is ANY we can skip as any record is accepted*/
  if (result == STATE_OK && strncmp(query_type, "", 1) && (strncmp(query_type, "-querytype=ANY", 15) != 0)) {
    if (strncmp(query_type, query_found, 16) != 0) {
      if (verbose)
        printf( "Failed query for %s only found %s, or nothing\n", query_type, query_found);
      result = STATE_CRITICAL;
      xasprintf(&msg, _("query type of %s was not found for %s"), query_type, query_address);
    }
  }

  microsec = deltime (tv);
  elapsed_time = (double)microsec / 1.0e6;

  if (result == STATE_OK) {
    if (strchr (address, ',') == NULL)
      multi_address = FALSE;
    else
      multi_address = TRUE;

    result = get_status(elapsed_time, time_thresholds);
    if (result == STATE_OK) {
      printf ("DNS %s: ", _("OK"));
    } else if (result == STATE_WARNING) {
      printf ("DNS %s: ", _("WARNING"));
    } else if (result == STATE_CRITICAL) {
      printf ("DNS %s: ", _("CRITICAL"));
    }
    printf (ngettext("%.3f second response time", "%.3f seconds response time", elapsed_time), elapsed_time);
    printf (_(". %s returns %s"), query_address, address);
    if ((time_thresholds->warning != NULL) && (time_thresholds->critical != NULL)) {
      printf ("|%s\n", fperfdata ("time", elapsed_time, "s",
                                  TRUE, time_thresholds->warning->end,
                                  TRUE, time_thresholds->critical->end,
                                  TRUE, 0, FALSE, 0));
    } else if ((time_thresholds->warning == NULL) && (time_thresholds->critical != NULL)) {
      printf ("|%s\n", fperfdata ("time", elapsed_time, "s",
                                  FALSE, 0,
                                  TRUE, time_thresholds->critical->end,
                                  TRUE, 0, FALSE, 0));
    } else if ((time_thresholds->warning != NULL) && (time_thresholds->critical == NULL)) {
      printf ("|%s\n", fperfdata ("time", elapsed_time, "s",
                                  TRUE, time_thresholds->warning->end,
                                  FALSE, 0,
                                  TRUE, 0, FALSE, 0));
    } else
      printf ("|%s\n", fperfdata ("time", elapsed_time, "s", FALSE, 0, FALSE, 0, TRUE, 0, FALSE, 0));
  }
  else if (result == STATE_WARNING)
    printf (_("DNS WARNING - %s\n"),
            !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);
  else if (result == STATE_CRITICAL)
    printf (_("DNS CRITICAL - %s\n"),
            !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);
  else
    printf (_("DNS UNKNOWN - %s\n"),
            !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);

  return result;
}
Exemplo n.º 14
0
int
ssh_connect_p (char *haddr, int hport, char *remote_version, char * remote_fingerprint)
{
	struct timeval tv;
	double elapsed_time;

	ssh_session my_ssh_session;
	int  version;
	int myversion;
	int hlen;
	int rc;
	int state;
	int i;
	unsigned char *hash = NULL;
	char *  fingerprint;
	int in_known_host;

	int sshv1,sshv2,sshv3;

	gettimeofday(&tv, NULL);

	my_ssh_session = ssh_new();

	if (my_ssh_session == NULL)
		return STATE_CRITICAL;

	ssh_options_set(my_ssh_session, SSH_OPTIONS_HOST, haddr);
	ssh_options_set(my_ssh_session, SSH_OPTIONS_PORT, &hport);
	rc = ssh_connect(my_ssh_session);
	if (rc != SSH_OK) {
		printf ("Connect to Server failed\n");
		exit (STATE_CRITICAL);
	}
	in_known_host=-1;
	state = ssh_is_server_known(my_ssh_session);
	hlen = ssh_get_pubkey_hash(my_ssh_session, &hash);

	/* Get the finger print as a string */
	fingerprint = ssh_get_hexa(hash, hlen);
	if(remote_fingerprint && strcmp(remote_fingerprint, "known_host") == NULL) {
		if(state != SSH_SERVER_KNOWN_OK) {
			printf ("SSH CRITICAL - Fingerprint (%s) checked in known_hosts failed\n", remote_fingerprint,fingerprint);
			exit(STATE_CRITICAL);
		} else {
			in_known_host=1;
		}
	}

	/* FIXME: This alwats eval to false... */
	if(remote_fingerprint && strcmp(remote_fingerprint, "known_host") && strcmp(remote_fingerprint, fingerprint)) {
		printf ("SSH CRITICAL - Fingerprint (%s) mismatched %s\n", remote_fingerprint,fingerprint);
		free(fingerprint);
		exit(STATE_CRITICAL);
	}

	version = ssh_get_openssh_version(my_ssh_session);
	if(remote_version && sscanf(remote_version, "%d.%d.%d", &sshv1, &sshv2, &sshv3)) {
		myversion = SSH_VERSION_INT(sshv1, sshv2, sshv3);
		if(version < myversion) {
			printf ("SSH WARNING version on server is below %s\n", remote_version);
			exit(STATE_CRITICAL);
		}
	}

	elapsed_time = (double)deltime(tv) / 1.0e6;

	printf (_("SSH OK - fingerprint: %s (Version %d) known_host_check:%d | %s\n"),
	        fingerprint, version,in_known_host, fperfdata("time", elapsed_time, "s",
	        FALSE, 0, FALSE, 0, TRUE, 0, TRUE, (int)socket_timeout));
	free(fingerprint);
	ssh_disconnect(my_ssh_session);
	ssh_free(my_ssh_session);
	exit(STATE_OK);

}
Exemplo n.º 15
0
int
main (int argc, char **argv)
{
    char *cmd = NULL;
    char *rawcmd = NULL;
    int result = STATE_UNKNOWN;
    int this_result = STATE_UNKNOWN;
    int i;

    setlocale (LC_ALL, "");
    setlocale (LC_NUMERIC, "C");
    bindtextdomain (PACKAGE, LOCALEDIR);
    textdomain (PACKAGE);

    addresses = malloc (sizeof(char*) * max_addr);
    addresses[0] = NULL;

    /* Parse extra opts if any */
    argv=np_extra_opts (&argc, argv, progname);

    if (process_arguments (argc, argv) == ERROR)
        usage4 (_("Could not parse arguments"));

    /* Set signal handling and alarm */
    if (signal (SIGALRM, popen_timeout_alarm_handler) == SIG_ERR) {
        usage4 (_("Cannot catch SIGALRM"));
    }

    /* If ./configure finds ping has timeout values, set plugin alarm slightly
     * higher so that we can use response from command line ping */
#if defined(PING_PACKETS_FIRST) && defined(PING_HAS_TIMEOUT)
    alarm (timeout_interval + 1);
#else
    alarm (timeout_interval);
#endif

    for (i = 0 ; i < n_addresses ; i++) {

#ifdef PING6_COMMAND
        if (address_family != AF_INET && is_inet6_addr(addresses[i]))
            rawcmd = strdup(PING6_COMMAND);
        else
            rawcmd = strdup(PING_COMMAND);
#else
        rawcmd = strdup(PING_COMMAND);
#endif

        /* does the host address of number of packets argument come first? */
#ifdef PING_PACKETS_FIRST
# ifdef PING_HAS_TIMEOUT
        xasprintf (&cmd, rawcmd, timeout_interval, max_packets, addresses[i]);
# else
        xasprintf (&cmd, rawcmd, max_packets, addresses[i]);
# endif
#else
        xasprintf (&cmd, rawcmd, addresses[i], max_packets);
#endif

        if (verbose >= 2)
            printf ("CMD: %s\n", cmd);

        /* run the command */
        this_result = run_ping (cmd, addresses[i]);

        if (pl == UNKNOWN_PACKET_LOSS || rta < 0.0) {
            printf ("%s\n", cmd);
            die (STATE_UNKNOWN,
                 _("CRITICAL - Could not interpret output from ping command\n"));
        }

        if (pl >= cpl || rta >= crta || rta < 0)
            this_result = STATE_CRITICAL;
        else if (pl >= wpl || rta >= wrta)
            this_result = STATE_WARNING;
        else if (pl >= 0 && rta >= 0)
            this_result = max_state (STATE_OK, this_result);

        if (n_addresses > 1 && this_result != STATE_UNKNOWN)
            die (STATE_OK, "%s is alive\n", addresses[i]);

        if (display_html == TRUE)
            printf ("<A HREF='%s/traceroute.cgi?%s'>", CGIURL, addresses[i]);
        if (pl == 100)
            printf (_("PING %s - %sPacket loss = %d%%"), state_text (this_result), warn_text,
                    pl);
        else
            printf (_("PING %s - %sPacket loss = %d%%, RTA = %2.2f ms"),
                    state_text (this_result), warn_text, pl, rta);
        if (display_html == TRUE)
            printf ("</A>");

        /* Print performance data */
        printf("|%s", fperfdata ("rta", (double) rta, "ms",
                                 wrta>0?TRUE:FALSE, wrta,
                                 crta>0?TRUE:FALSE, crta,
                                 TRUE, 0, FALSE, 0));
        printf(" %s\n", perfdata ("pl", (long) pl, "%",
                                  wpl>0?TRUE:FALSE, wpl,
                                  cpl>0?TRUE:FALSE, cpl,
                                  TRUE, 0, FALSE, 0));

        if (verbose >= 2)
            printf ("%f:%d%% %f:%d%%\n", wrta, wpl, crta, cpl);

        result = max_state (result, this_result);
        free (rawcmd);
        free (cmd);
    }

    return result;
}
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);

	if (opt_file != NULL)
		mysql_options(&mysql,MYSQL_READ_DEFAULT_FILE,opt_file);

	if (opt_group != NULL)
		mysql_options(&mysql,MYSQL_READ_DEFAULT_GROUP,opt_group);
	else
		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 | %s"), sql_query, value,
	 fperfdata("result", value, "",
	 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)
	);

	printf("\n");

	return status;
}
Exemplo n.º 17
0
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;
}
Exemplo n.º 18
0
int main(int argc, char **argv){

/* should be 	int result = STATE_UNKNOWN; */

	int return_code = STATE_UNKNOWN;
	char *send_buffer=NULL;
	char *output_message=NULL;
	char *perfdata=NULL;
	char *temp_string=NULL;
	char *temp_string_perf=NULL;
	char *description=NULL,*counter_unit = NULL;
	char *minval = NULL, *maxval = NULL, *errcvt = NULL;
	char *fds=NULL, *tds=NULL;
	char *numstr;

	double total_disk_space=0;
	double free_disk_space=0;
	double percent_used_space=0;
	double warning_used_space=0;
	double critical_used_space=0;
	double mem_commitLimit=0;
	double mem_commitByte=0;
	double fminval = 0, fmaxval = 0;
	unsigned long utilization;
	unsigned long uptime;
	unsigned long age_in_minutes;
	double counter_value = 0.0;
	int offset=0;
	int updays=0;
	int uphours=0;
	int upminutes=0;

	int isPercent = FALSE;
	int allRight = FALSE;

	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);

	/* set socket timeout */
	alarm(socket_timeout);

	switch (vars_to_check) {

	case CHECK_CLIENTVERSION:

		xasprintf(&send_buffer, "%s&1", req_password);
		fetch_data (server_address, server_port, send_buffer);
		if (value_list != NULL && strcmp(recv_buffer, value_list) != 0) {
			xasprintf (&output_message, _("Wrong client version - running: %s, required: %s"), recv_buffer, value_list);
			return_code = STATE_WARNING;
		} else {
			xasprintf (&output_message, "%s", recv_buffer);
			return_code = STATE_OK;
		}
		break;

	case CHECK_CPULOAD:

		if (value_list==NULL)
			output_message = strdup (_("missing -l parameters"));
		else if (strtoularray(lvalue_list,value_list,",")==FALSE)
			output_message = strdup (_("wrong -l parameter."));
		else {
			/* -l parameters is present with only integers */
			return_code=STATE_OK;
			temp_string = strdup (_("CPU Load"));
			temp_string_perf = strdup (" ");

			/* loop until one of the parameters is wrong or not present */
			while (lvalue_list[0+offset]> (unsigned long)0 &&
						 lvalue_list[0+offset]<=(unsigned long)17280 &&
						 lvalue_list[1+offset]> (unsigned long)0 &&
						 lvalue_list[1+offset]<=(unsigned long)100 &&
						 lvalue_list[2+offset]> (unsigned long)0 &&
						 lvalue_list[2+offset]<=(unsigned long)100) {

				/* Send request and retrieve data */
				xasprintf(&send_buffer,"%s&2&%lu",req_password,lvalue_list[0+offset]);
				fetch_data (server_address, server_port, send_buffer);

				utilization=strtoul(recv_buffer,NULL,10);

				/* Check if any of the request is in a warning or critical state */
				if(utilization >= lvalue_list[2+offset])
					return_code=STATE_CRITICAL;
				else if(utilization >= lvalue_list[1+offset] && return_code<STATE_WARNING)
					return_code=STATE_WARNING;

				xasprintf(&output_message,_(" %lu%% (%lu min average)"), utilization, lvalue_list[0+offset]);
				xasprintf(&temp_string,"%s%s",temp_string,output_message);
				xasprintf(&perfdata,_(" '%lu min avg Load'=%lu%%;%lu;%lu;0;100"), lvalue_list[0+offset], utilization,
				  lvalue_list[1+offset], lvalue_list[2+offset]);
				xasprintf(&temp_string_perf,"%s%s",temp_string_perf,perfdata);
				offset+=3;	/* move across the array */
			}

			if (strlen(temp_string)>10) {  /* we had at least one loop */
				output_message = strdup (temp_string);
				perfdata = temp_string_perf;
			} else
				output_message = strdup (_("not enough values for -l parameters"));
		}
		break;

	case CHECK_UPTIME:

		if (value_list == NULL) {
			value_list = "minutes";
		}
		if (strncmp(value_list, "seconds", strlen("seconds") + 1 ) && 
			strncmp(value_list, "minutes", strlen("minutes") + 1) && 
			strncmp(value_list, "hours", strlen("hours") + 1) && 
			strncmp(value_list, "days", strlen("days") + 1)) {

			output_message = strdup (_("wrong -l argument"));
		} else {
			xasprintf(&send_buffer, "%s&3", req_password);
			fetch_data (server_address, server_port, send_buffer);
			uptime=strtoul(recv_buffer,NULL,10);
			updays = uptime / 86400;
			uphours = (uptime % 86400) / 3600;
			upminutes = ((uptime % 86400) % 3600) / 60;

			if (!strncmp(value_list, "minutes", strlen("minutes")))
				uptime = uptime / 60;
			else if (!strncmp(value_list, "hours", strlen("hours")))
				uptime = uptime / 3600;
			else if (!strncmp(value_list, "days", strlen("days")))
				uptime = uptime / 86400;
			/* else uptime in seconds, nothing to do */

			xasprintf(&output_message,_("System Uptime - %u day(s) %u hour(s) %u minute(s) |uptime=%lu"),updays, uphours, upminutes, uptime);

			if (check_critical_value==TRUE && uptime <= critical_value)
				return_code=STATE_CRITICAL;
			else if (check_warning_value==TRUE && uptime <= warning_value)
				return_code=STATE_WARNING;
			else
				return_code=STATE_OK;
		}
		break;

	case CHECK_USEDDISKSPACE:

		if (value_list==NULL)
			output_message = strdup (_("missing -l parameters"));
		else if (strlen(value_list)!=1)
			output_message = strdup (_("wrong -l argument"));
		else {
			xasprintf(&send_buffer,"%s&4&%s", req_password, value_list);
			fetch_data (server_address, server_port, send_buffer);
			fds=strtok(recv_buffer,"&");
			tds=strtok(NULL,"&");
			if(fds!=NULL)
				free_disk_space=atof(fds);
			if(tds!=NULL)
				total_disk_space=atof(tds);

			if (total_disk_space>0 && free_disk_space>=0) {
				percent_used_space = ((total_disk_space - free_disk_space) / total_disk_space) * 100;
				warning_used_space = ((float)warning_value / 100) * total_disk_space;
				critical_used_space = ((float)critical_value / 100) * total_disk_space;

				xasprintf(&temp_string,_("%s:\\ - total: %.2f Gb - used: %.2f Gb (%.0f%%) - free %.2f Gb (%.0f%%)"),
				  value_list, total_disk_space / 1073741824, (total_disk_space - free_disk_space) / 1073741824,
				  percent_used_space, free_disk_space / 1073741824, (free_disk_space / total_disk_space)*100);
				xasprintf(&temp_string_perf,_("'%s:\\ Used Space'=%.2fGb;%.2f;%.2f;0.00;%.2f"), value_list,
				  (total_disk_space - free_disk_space) / 1073741824, warning_used_space / 1073741824,
				  critical_used_space / 1073741824, total_disk_space / 1073741824);

				if(check_critical_value==TRUE && percent_used_space >= critical_value)
					return_code=STATE_CRITICAL;
				else if (check_warning_value==TRUE && percent_used_space >= warning_value)
					return_code=STATE_WARNING;
				else
					return_code=STATE_OK;

				output_message = strdup (temp_string);
				perfdata = temp_string_perf;
			} else {
				output_message = strdup (_("Free disk space : Invalid drive"));
				return_code=STATE_UNKNOWN;
			}
		}
		break;

	case CHECK_SERVICESTATE:
	case CHECK_PROCSTATE:

		if (value_list==NULL)
			output_message = strdup (_("No service/process specified"));
		else {
			preparelist(value_list);		/* replace , between services with & to send the request */
			xasprintf(&send_buffer,"%s&%u&%s&%s", req_password,(vars_to_check==CHECK_SERVICESTATE)?5:6,
							 (show_all==TRUE) ? "ShowAll" : "ShowFail",value_list);
			fetch_data (server_address, server_port, send_buffer);
			numstr = strtok(recv_buffer,"&");
			if (numstr == NULL)
				die(STATE_UNKNOWN, _("could not fetch information from server\n"));
			return_code=atoi(numstr);
			temp_string=strtok(NULL,"&");
			output_message = strdup (temp_string);
		}
		break;

	case CHECK_MEMUSE:

		xasprintf(&send_buffer,"%s&7", req_password);
		fetch_data (server_address, server_port, send_buffer);
		numstr = strtok(recv_buffer,"&");
		if (numstr == NULL)
			die(STATE_UNKNOWN, _("could not fetch information from server\n"));
		mem_commitLimit=atof(numstr);
		numstr = strtok(NULL,"&");
		if (numstr == NULL)
			die(STATE_UNKNOWN, _("could not fetch information from server\n"));
		mem_commitByte=atof(numstr);
		percent_used_space = (mem_commitByte / mem_commitLimit) * 100;
		warning_used_space = ((float)warning_value / 100) * mem_commitLimit;
		critical_used_space = ((float)critical_value / 100) * mem_commitLimit;

		/* Divisor should be 1048567, not 3044515, as we are measuring "Commit Charge" here,
		which equals RAM + Pagefiles. */
		xasprintf(&output_message,_("Memory usage: total:%.2f Mb - used: %.2f Mb (%.0f%%) - free: %.2f Mb (%.0f%%)"),
		  mem_commitLimit / 1048567, mem_commitByte / 1048567, percent_used_space,
		  (mem_commitLimit - mem_commitByte) / 1048567, (mem_commitLimit - mem_commitByte) / mem_commitLimit * 100);
		xasprintf(&perfdata,_("'Memory usage'=%.2fMb;%.2f;%.2f;0.00;%.2f"), mem_commitByte / 1048567,
		  warning_used_space / 1048567, critical_used_space / 1048567, mem_commitLimit / 1048567);

		return_code=STATE_OK;
		if(check_critical_value==TRUE && percent_used_space >= critical_value)
			return_code=STATE_CRITICAL;
		else if (check_warning_value==TRUE && percent_used_space >= warning_value)
			return_code=STATE_WARNING;

		break;

	case CHECK_COUNTER:


		/*
		CHECK_COUNTER has been modified to provide extensive perfdata information.
		In order to do this, some modifications have been done to the code
		and some constraints have been introduced.

		1) For the sake of simplicity of the code, perfdata information will only be
		 provided when the "description" field is added.

		2) If the counter you're going to measure is percent-based, the code will detect
		 the percent sign in its name and will attribute minimum (0%) and maximum (100%)
		 values automagically, as well the ¨%" sign to graph units.

		3) OTOH, if the counter is "absolute", you'll have to provide the following
		 the counter unit - that is, the dimensions of the counter you're getting. Examples:
		 pages/s, packets transferred, etc.

		4) If you want, you may provide the minimum and maximum values to expect. They aren't mandatory,
		 but once specified they MUST have the same order of magnitude and units of -w and -c; otherwise.
		 strange things will happen when you make graphs of your data.
		*/

		if (value_list == NULL)
			output_message = strdup (_("No counter specified"));
		else
		{
			preparelist (value_list);	/* replace , between services with & to send the request */
			isPercent = (strchr (value_list, '%') != NULL);

			strtok (value_list, "&");	/* burn the first parameters */
			description = strtok (NULL, "&");
			counter_unit = strtok (NULL, "&");
			xasprintf (&send_buffer, "%s&8&%s", req_password, value_list);
			fetch_data (server_address, server_port, send_buffer);
			counter_value = atof (recv_buffer);

			if (description == NULL)
			xasprintf (&output_message, "%.f", counter_value);
			else if (isPercent)
			{
				counter_unit = strdup ("%");
				allRight = TRUE;
			}

			if ((counter_unit != NULL) && (!allRight))
			{
				minval = strtok (NULL, "&");
				maxval = strtok (NULL, "&");

				/* All parameters specified. Let's check the numbers */

				fminval = (minval != NULL) ? strtod (minval, &errcvt) : -1;
				fmaxval = (minval != NULL) ? strtod (maxval, &errcvt) : -1;

				if ((fminval == 0) && (minval == errcvt))
					output_message = strdup (_("Minimum value contains non-numbers"));
				else
				{
					if ((fmaxval == 0) && (maxval == errcvt))
						output_message = strdup (_("Maximum value contains non-numbers"));
					else
						allRight = TRUE;	/* Everything is OK. */

				}
			}
			else if ((counter_unit == NULL) && (description != NULL))
				output_message = strdup (_("No unit counter specified"));

			if (allRight)
			{
				/* Let's format the output string, finally... */
					if (strstr(description, "%") == NULL) {
						xasprintf (&output_message, "%s = %.2f %s", description, counter_value, counter_unit);
					} else {
						/* has formatting, will segv if wrong */
						xasprintf (&output_message, description, counter_value);
					}
					xasprintf (&output_message, "%s |", output_message);
					xasprintf (&output_message,"%s %s", output_message,
						fperfdata (description, counter_value,
							counter_unit, 1, warning_value, 1, critical_value,
							(!(isPercent) && (minval != NULL)), fminval,
							(!(isPercent) && (minval != NULL)), fmaxval));
			}
		}

		if (critical_value > warning_value)
		{			/* Normal thresholds */
			if (check_critical_value == TRUE && counter_value >= critical_value)
				return_code = STATE_CRITICAL;
			else if (check_warning_value == TRUE && counter_value >= warning_value)
				return_code = STATE_WARNING;
			else
				return_code = STATE_OK;
		}
		else
		{			/* inverse thresholds */
			return_code = STATE_OK;
			if (check_critical_value == TRUE && counter_value <= critical_value)
				return_code = STATE_CRITICAL;
			else if (check_warning_value == TRUE && counter_value <= warning_value)
				return_code = STATE_WARNING;
		}
	break;

	case CHECK_FILEAGE:

		if (value_list==NULL)
			output_message = strdup (_("No counter specified"));
		else {
			preparelist(value_list);		/* replace , between services with & to send the request */
			xasprintf(&send_buffer,"%s&9&%s", req_password,value_list);
			fetch_data (server_address, server_port, send_buffer);
			age_in_minutes = atoi(strtok(recv_buffer,"&"));
			description = strtok(NULL,"&");
			output_message = strdup (description);

			if (critical_value > warning_value) {        /* Normal thresholds */
				if(check_critical_value==TRUE && age_in_minutes >= critical_value)
					return_code=STATE_CRITICAL;
				else if (check_warning_value==TRUE && age_in_minutes >= warning_value)
					return_code=STATE_WARNING;
				else
					return_code=STATE_OK;
			}
			else {                                       /* inverse thresholds */
				if(check_critical_value==TRUE && age_in_minutes <= critical_value)
					return_code=STATE_CRITICAL;
				else if (check_warning_value==TRUE && age_in_minutes <= warning_value)
					return_code=STATE_WARNING;
				else
					return_code=STATE_OK;
			}
		}
		break;

	case CHECK_INSTANCES:
		if (value_list==NULL)
			output_message = strdup (_("No counter specified"));
		else {
			xasprintf(&send_buffer,"%s&10&%s", req_password,value_list);
			fetch_data (server_address, server_port, send_buffer);
			if (!strncmp(recv_buffer,"ERROR",5)) {
				printf("NSClient - %s\n",recv_buffer);
				exit(STATE_UNKNOWN);
			}
			xasprintf(&output_message,"%s",recv_buffer);
			return_code=STATE_OK;
		}
		break;

	case CHECK_NONE:
	default:
		usage4 (_("Please specify a variable to check"));
		break;

	}

	/* reset timeout */
	alarm(0);

	if (perfdata==NULL)
		printf("%s\n",output_message);
	else
		printf("%s | %s\n",output_message,perfdata);
	return return_code;
}
Exemplo n.º 19
0
int
main (int argc, char **argv)
{
  char *command_line;
  output chld_out, chld_err;
  char *msg = NULL;
  size_t i;
  char *t;
  long microsec;
  double elapsed_time;
  int result = STATE_UNKNOWN;
  int timeout_interval_dig;

  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);

  /* Set signal handling and alarm */
  if (signal (SIGALRM, runcmd_timeout_alarm_handler) == SIG_ERR)
    usage_va(_("Cannot catch SIGALRM"));

  /* Parse extra opts if any */
  argv=np_extra_opts (&argc, argv, progname);

  if (process_arguments (argc, argv) == ERROR)
    usage_va(_("Could not parse arguments"));

  /* dig applies the timeout to each try, so we need to work around this */
  timeout_interval_dig = timeout_interval / number_tries + number_tries;

  /* get the command to run */
  xasprintf (&command_line, "%s %s %s -p %d @%s %s %s +tries=%d +time=%d",
            PATH_TO_DIG, dig_args, query_transport, server_port, dns_server, query_address, record_type, number_tries, timeout_interval_dig);

  alarm (timeout_interval);
  gettimeofday (&tv, NULL);

  if (verbose) {
    printf ("%s\n", command_line);
    if(expected_address != NULL) {
      printf (_("Looking for: '%s'\n"), expected_address);
    } else {
      printf (_("Looking for: '%s'\n"), query_address);
    }
  }

  /* run the command */
  if(np_runcmd(command_line, &chld_out, &chld_err, 0) != 0) {
    result = STATE_WARNING;
    msg = (char *)_("dig returned an error status");
  }

  for(i = 0; i < chld_out.lines; i++) {
    /* the server is responding, we just got the host name... */
    if (strstr (chld_out.line[i], ";; ANSWER SECTION:")) {

      /* loop through the whole 'ANSWER SECTION' */
      for(; i < chld_out.lines; i++) {
        /* get the host address */
        if (verbose)
          printf ("%s\n", chld_out.line[i]);

        if (strstr (chld_out.line[i], (expected_address == NULL ? query_address : expected_address)) != NULL) {
          msg = chld_out.line[i];
          result = STATE_OK;

          /* Translate output TAB -> SPACE */
          t = msg;
          while ((t = strchr(t, '\t')) != NULL) *t = ' ';
          break;
        }
      }

      if (result == STATE_UNKNOWN) {
        msg = (char *)_("Server not found in ANSWER SECTION");
        result = STATE_WARNING;
      }

      /* we found the answer section, so break out of the loop */
      break;
    }
  }

  if (result == STATE_UNKNOWN) {
    msg = (char *)_("No ANSWER SECTION found");
    result = STATE_CRITICAL;
  }

  /* If we get anything on STDERR, at least set warning */
  if(chld_err.buflen > 0) {
    result = max_state(result, STATE_WARNING);
    if(!msg) for(i = 0; i < chld_err.lines; i++) {
      msg = strchr(chld_err.line[0], ':');
      if(msg) {
        msg++;
        break;
      }
    }
  }

  microsec = deltime (tv);
  elapsed_time = (double)microsec / 1.0e6;

  if (critical_interval > UNDEFINED && elapsed_time > critical_interval)
    result = STATE_CRITICAL;

  else if (warning_interval > UNDEFINED && elapsed_time > warning_interval)
    result = STATE_WARNING;

  printf ("DNS %s - %.3f seconds response time (%s)|%s\n",
          state_text (result), elapsed_time,
          msg ? msg : _("Probably a non-existent host/domain"),
          fperfdata("time", elapsed_time, "s",
                    (warning_interval>UNDEFINED?TRUE:FALSE),
                    warning_interval,
                    (critical_interval>UNDEFINED?TRUE:FALSE),
            critical_interval,
            TRUE, 0, FALSE, 0));
  return result;
}
Exemplo n.º 20
0
int
main (int argc, char **argv)
{

	MYSQL mysql;
	MYSQL_RES *res;
	MYSQL_ROW row;

	/* should be status */

	char *result = NULL;
	char *error = NULL;
	char slaveresult[SLAVERESULTSIZE];
	char* perf;

        perf = strdup ("");

	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);
	
	if (opt_file != NULL)
		mysql_options(&mysql,MYSQL_READ_DEFAULT_FILE,opt_file);

	if (opt_group != NULL)
		mysql_options(&mysql,MYSQL_READ_DEFAULT_GROUP,opt_group);
	else
		mysql_options(&mysql,MYSQL_READ_DEFAULT_GROUP,"client");

	if (ssl)
		mysql_ssl_set(&mysql,key,cert,ca_cert,ca_dir,ciphers);
	/* 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, "%s\n", mysql_error (&mysql));
		else if (mysql_errno (&mysql) == CR_VERSION_ERROR)
			die (STATE_WARNING, "%s\n", mysql_error (&mysql));
		else if (mysql_errno (&mysql) == CR_OUT_OF_MEMORY)
			die (STATE_WARNING, "%s\n", mysql_error (&mysql));
		else if (mysql_errno (&mysql) == CR_IPSOCK_ERROR)
			die (STATE_WARNING, "%s\n", mysql_error (&mysql));
		else if (mysql_errno (&mysql) == CR_SOCKET_CREATE_ERROR)
			die (STATE_WARNING, "%s\n", mysql_error (&mysql));
		else
			die (STATE_CRITICAL, "%s\n", mysql_error (&mysql));
	}

	/* get the server stats */
	result = strdup (mysql_stat (&mysql));

	/* error checking once more */
	if (mysql_error (&mysql)) {
		if (mysql_errno (&mysql) == CR_SERVER_GONE_ERROR)
			die (STATE_CRITICAL, "%s\n", mysql_error (&mysql));
		else if (mysql_errno (&mysql) == CR_SERVER_LOST)
			die (STATE_CRITICAL, "%s\n", mysql_error (&mysql));
		else if (mysql_errno (&mysql) == CR_UNKNOWN_ERROR)
			die (STATE_CRITICAL, "%s\n", mysql_error (&mysql));
	}

	/* try to fetch some perf data */
	if (mysql_query (&mysql, "show global status") == 0) {
		if ( (res = mysql_store_result (&mysql)) == NULL) {
			error = strdup(mysql_error(&mysql));
			mysql_close (&mysql);
			die (STATE_CRITICAL, _("status store_result error: %s\n"), error);
		}

		while ( (row = mysql_fetch_row (res)) != NULL) {
			int i;

			for(i = 0; i < LENGTH_METRIC_UNIT; i++) {
				if (strcmp(row[0], metric_unit[i]) == 0) {
					xasprintf(&perf, "%s%s ", perf, perfdata(metric_unit[i],
						atol(row[1]), "", FALSE, 0, FALSE, 0, FALSE, 0, FALSE, 0));
					continue;
				}
			}
			for(i = 0; i < LENGTH_METRIC_COUNTER; i++) {
				if (strcmp(row[0], metric_counter[i]) == 0) {
					xasprintf(&perf, "%s%s ", perf, perfdata(metric_counter[i],
						atol(row[1]), "c", FALSE, 0, FALSE, 0, FALSE, 0, FALSE, 0));
					continue;
				}
			}
		}
		/* remove trailing space */
                if (strlen(perf) > 0)
                    perf[strlen(perf) - 1] = '\0';
	}

	if(check_slave) {
		/* check the slave status */
		if (mysql_query (&mysql, "show slave status") != 0) {
			error = strdup(mysql_error(&mysql));
			mysql_close (&mysql);
			die (STATE_CRITICAL, _("slave query error: %s\n"), error);
		}

		/* store the result */
		if ( (res = mysql_store_result (&mysql)) == NULL) {
			error = strdup(mysql_error(&mysql));
			mysql_close (&mysql);
			die (STATE_CRITICAL, _("slave store_result error: %s\n"), error);
		}

		/* Check there is some data */
		if (mysql_num_rows(res) == 0) {
			mysql_close(&mysql);
			die (STATE_WARNING, "%s\n", _("No slaves defined"));
		}

		/* 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, _("slave fetch row error: %s\n"), error);
		}

		if (mysql_field_count (&mysql) == 12) {
			/* mysql 3.23.x */
			snprintf (slaveresult, SLAVERESULTSIZE, _("Slave running: %s"), row[6]);
			if (strcmp (row[6], "Yes") != 0) {
				mysql_free_result (res);
				mysql_close (&mysql);
				die (STATE_CRITICAL, "%s\n", slaveresult);
			}

		} else {
			/* mysql 4.x.x and mysql 5.x.x */
			int slave_io_field = -1 , slave_sql_field = -1, seconds_behind_field = -1, i, num_fields;
			MYSQL_FIELD* fields;

			num_fields = mysql_num_fields(res);
			fields = mysql_fetch_fields(res);
			for(i = 0; i < num_fields; i++) {
				if (strcmp(fields[i].name, "Slave_IO_Running") == 0) {
					slave_io_field = i;
					continue;
				}
				if (strcmp(fields[i].name, "Slave_SQL_Running") == 0) {
					slave_sql_field = i;
					continue;
				}
				if (strcmp(fields[i].name, "Seconds_Behind_Master") == 0) {
					seconds_behind_field = i;
					continue;
				}
			}

			/* Check if slave status is available */
			if ((slave_io_field < 0) || (slave_sql_field < 0) || (num_fields == 0)) {
				mysql_free_result (res);
				mysql_close (&mysql);
				die (STATE_CRITICAL, "Slave status unavailable\n");
			}

			/* Save slave status in slaveresult */
			snprintf (slaveresult, SLAVERESULTSIZE, "Slave IO: %s Slave SQL: %s Seconds Behind Master: %s", row[slave_io_field], row[slave_sql_field], seconds_behind_field!=-1?row[seconds_behind_field]:"Unknown");

			/* Raise critical error if SQL THREAD or IO THREAD are stopped */
			if (strcmp (row[slave_io_field], "Yes") != 0 || strcmp (row[slave_sql_field], "Yes") != 0) {
				mysql_free_result (res);
				mysql_close (&mysql);
				die (STATE_CRITICAL, "%s\n", slaveresult);
			}

			if (verbose >=3) {
				if (seconds_behind_field == -1) {
					printf("seconds_behind_field not found\n");
				} else {
					printf ("seconds_behind_field(index %d)=%s\n", seconds_behind_field, row[seconds_behind_field]);
				}
			}

			/* Check Seconds Behind against threshold */
			if ((seconds_behind_field != -1) && (strcmp (row[seconds_behind_field], "NULL") != 0)) {
				double value = atof(row[seconds_behind_field]);
				int status;

				status = get_status(value, my_threshold);

				xasprintf (&perf, "%s %s", perf, fperfdata ("seconds behind master", value, "s",
        	                        TRUE, (double) warning_time,
                	                TRUE, (double) critical_time,
                        	        FALSE, 0,
                                	FALSE, 0));

				if (status == STATE_WARNING) {
					printf("SLOW_SLAVE %s: %s|%s\n", _("WARNING"), slaveresult, perf);
					exit(STATE_WARNING);
				} else if (status == STATE_CRITICAL) {
					printf("SLOW_SLAVE %s: %s|%s\n", _("CRITICAL"), slaveresult, perf);
					exit(STATE_CRITICAL);
				}
			}
		}

		/* free the result */
		mysql_free_result (res);
	}

	/* close the connection */
	mysql_close (&mysql);

	/* print out the result of stats */
	if (check_slave) {
		printf ("%s %s|%s\n", result, slaveresult, perf);
	} else {
		printf ("%s|%s\n", result, perf);
	}

	return STATE_OK;
}