예제 #1
0
int
main (int argc, char **argv)
{
	char *input_buffer;
	char *input_line;
	char *procprog;
	char *proc_cgroup_hierarchy;

	pid_t mypid = 0;
	pid_t myppid = 0;
	struct stat statbuf;
	dev_t mydev = 0;
	ino_t myino = 0;
	int procuid = 0;
	pid_t procpid = 0;
	pid_t procppid = 0;
	pid_t kthread_ppid = 0;
	int procvsz = 0;
	int procrss = 0;
	int procseconds = 0;
	float procpcpu = 0;
	char procstat[8];
	char procetime[MAX_INPUT_BUFFER] = { '\0' };
	char *procargs;
	char *tmp;

	const char *zombie = "Z";

	int resultsum = 0; /* bitmask of the filter criteria met by a process */
	int found = 0; /* counter for number of lines returned in `ps` output */
	int procs = 0; /* counter for number of processes meeting filter criteria */
	int pos; /* number of spaces before 'args' in `ps` output */
	int cols; /* number of columns in ps output */
	int expected_cols = PS_COLS - 1;
	int warn = 0; /* number of processes in warn state */
	int crit = 0; /* number of processes in crit state */
	int i = 0, j = 0;
	int result = STATE_UNKNOWN;
	int ret = 0;
	output chld_out, chld_err;

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

	input_buffer = malloc (MAX_INPUT_BUFFER);
	procprog = malloc (MAX_INPUT_BUFFER);
	proc_cgroup_hierarchy = malloc (MAX_INPUT_BUFFER);

	xasprintf (&metric_name, "PROCS");
	metric = METRIC_PROCS;

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

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

	/* find ourself */
	mypid = getpid();
	myppid = getppid();
	if (usepid || stat_exe(mypid, &statbuf) == -1) {
		/* usepid might have been set by -T */
		usepid = 1;
	} else {
		usepid = 0;
		mydev = statbuf.st_dev;
		myino = statbuf.st_ino;
	}

	/* Set signal handling and alarm timeout */
	if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) {
		die (STATE_UNKNOWN, _("Cannot catch SIGALRM"));
	}
	(void) alarm ((unsigned) timeout_interval);

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

	if (input_filename == NULL) {
		result = cmd_run( PS_COMMAND, &chld_out, &chld_err, 0);
		if (chld_err.lines > 0) {
			printf ("%s: %s", _("System call sent warnings to stderr"), chld_err.line[0]);
			exit(STATE_WARNING);
		}
	} else {
		result = cmd_file_read( input_filename, &chld_out, 0);
	}

	/* flush first line: j starts at 1 */
	for (j = 1; j < chld_out.lines; j++) {
		input_line = chld_out.line[j];

		if (verbose >= 3)
			printf ("%s", input_line);

		strcpy (procprog, "");
		strcpy (proc_cgroup_hierarchy, "");
		xasprintf (&procargs, "%s", "");

		cols = sscanf (input_line, PS_FORMAT, PS_VARLIST);

		/* Zombie processes do not give a procprog command */
		if ( cols < expected_cols && strstr(procstat, zombie) ) {
			cols = expected_cols;
		}
		if ( cols >= expected_cols ) {
			resultsum = 0;
			xasprintf (&procargs, "%s", input_line + pos);
			strip (procargs);

			/* Some ps return full pathname for command. This removes path */
			strcpy(procprog, base_name(procprog));

			/* we need to convert the elapsed time to seconds */
			procseconds = convert_to_seconds(procetime);

			if (verbose >= 3) {
				printf ("proc#=%d uid=%d vsz=%d rss=%d pid=%d ppid=%d pcpu=%.2f stat=%s etime=%s prog=%s args=%s",
					procs, procuid, procvsz, procrss,
					procpid, procppid, procpcpu, procstat,
					procetime, procprog, procargs);
				if (strstr(PS_COMMAND, "cgroup") != NULL) {
					printf(" proc_cgroup_hierarchy=%s\n", proc_cgroup_hierarchy);
				} else {
					printf("\n");
				}
			}

			/* Ignore self */
			if ((usepid && mypid == procpid) ||
				(!usepid && ((ret = stat_exe(procpid, &statbuf) != -1) && statbuf.st_dev == mydev && statbuf.st_ino == myino) ||
				 (ret == -1 && errno == ENOENT))) {
				if (verbose >= 3)
					 printf("not considering - is myself or gone\n");
				continue;
			}
			/* Ignore parent*/
			else if (myppid == procpid) {
				if (verbose >= 3)
					 printf("not considering - is parent\n");
				continue;
			}

			/* filter kernel threads (childs of KTHREAD_PARENT)*/
			/* TODO adapt for other OSes than GNU/Linux
					sorry for not doing that, but I've no other OSes to test :-( */
			if (kthread_filter == 1) {
				/* get pid KTHREAD_PARENT */
				if (kthread_ppid == 0 && !strcmp(procprog, KTHREAD_PARENT) )
					kthread_ppid = procpid;

				if (kthread_ppid == procppid) {
					if (verbose >= 2)
						printf ("Ignore kernel thread: pid=%d ppid=%d prog=%s args=%s\n", procpid, procppid, procprog, procargs);
					continue;
				}
			}

			if ((options & STAT) && (strstr (statopts, procstat)))
				resultsum |= STAT;
			if ((options & ARGS) && procargs && (strstr (procargs, args) != NULL))
				resultsum |= ARGS;
			if ((options & EREG_ARGS) && procargs && (regexec(&re_args, procargs, (size_t) 0, NULL, 0) == 0))
				resultsum |= EREG_ARGS;
			if ((options & PROG) && procprog && (strcmp (prog, procprog) == 0))
				resultsum |= PROG;
			if ((options & PPID) && (procppid == ppid))
				resultsum |= PPID;
			if ((options & USER) && (procuid == uid))
				resultsum |= USER;
			if ((options & VSZ)  && (procvsz >= vsz))
				resultsum |= VSZ;
			if ((options & RSS)  && (procrss >= rss))
				resultsum |= RSS;
			if ((options & PCPU)  && (procpcpu >= pcpu))
				resultsum |= PCPU;
			if (options & CGROUP_HIERARCHY) {
				if(!strncmp(proc_cgroup_hierarchy,"-", 2) && !strncmp(cgroup_hierarchy,"/", 2)) {
					resultsum |= CGROUP_HIERARCHY;
				} else {
					if((tmp = strstr(proc_cgroup_hierarchy,":/")) != NULL) {
						if(!strcmp(tmp+1,cgroup_hierarchy)) {
							resultsum |= CGROUP_HIERARCHY;
						};
					};
				};
			};

			found++;

			/* Next line if filters not matched */
			if (!(options == resultsum || options == ALL))
				continue;

			procs++;
			if (verbose >= 2) {
				printf ("Matched: uid=%d vsz=%d rss=%d pid=%d ppid=%d pcpu=%.2f stat=%s etime=%s prog=%s args=%s",
					procuid, procvsz, procrss,
					procpid, procppid, procpcpu, procstat, 
					procetime, procprog, procargs);
				if (strstr(PS_COMMAND, "cgroup") != NULL) {
					printf(" cgroup_hierarchy=%s\n", cgroup_hierarchy);
				} else {
					printf("\n");
				}
			}

			if (metric == METRIC_VSZ)
				i = get_status ((double)procvsz, procs_thresholds);
			else if (metric == METRIC_RSS)
				i = get_status ((double)procrss, procs_thresholds);
			/* TODO? float thresholds for --metric=CPU */
			else if (metric == METRIC_CPU)
				i = get_status (procpcpu, procs_thresholds);
			else if (metric == METRIC_ELAPSED)
				i = get_status ((double)procseconds, procs_thresholds);

			if (metric != METRIC_PROCS) {
				if (i == STATE_WARNING) {
					warn++;
					xasprintf (&fails, "%s%s%s", fails, (strcmp(fails,"") ? ", " : ""), procprog);
					result = max_state (result, i);
				}
				if (i == STATE_CRITICAL) {
					crit++;
					xasprintf (&fails, "%s%s%s", fails, (strcmp(fails,"") ? ", " : ""), procprog);
					result = max_state (result, i);
				}
			}
		} 
		/* This should not happen */
		else if (verbose) {
			printf(_("Not parseable: %s"), input_buffer);
		}
	}

	if (found == 0) {							/* no process lines parsed so return STATE_UNKNOWN */
		printf (_("Unable to read output\n"));
		return STATE_UNKNOWN;
	}

	if ( result == STATE_UNKNOWN ) 
		result = STATE_OK;

	/* Needed if procs found, but none match filter */
	if ( metric == METRIC_PROCS ) {
		result = max_state (result, get_status ((double)procs, procs_thresholds) );
	}

	if ( result == STATE_OK ) {
		printf ("%s %s: ", metric_name, _("OK"));
	} else if (result == STATE_WARNING) {
		printf ("%s %s: ", metric_name, _("WARNING"));
		if ( metric != METRIC_PROCS ) {
			printf (_("%d warn out of "), warn);
		}
	} else if (result == STATE_CRITICAL) {
		printf ("%s %s: ", metric_name, _("CRITICAL"));
		if (metric != METRIC_PROCS) {
			printf (_("%d crit, %d warn out of "), crit, warn);
		}
	} 
	printf (ngettext ("%d process", "%d processes", (unsigned long) procs), procs);
	
	if (strcmp(fmt,"") != 0) {
		printf (_(" with %s"), fmt);
	}

	if ( verbose >= 1 && strcmp(fails,"") )
		printf (" [%s]", fails);

	if (metric == METRIC_PROCS)
		printf (" | procs=%d;%s;%s;0;", procs,
				warning_range ? warning_range : "",
				critical_range ? critical_range : "");
	else
		printf (" | procs=%d;;;0; procs_warn=%d;;;0; procs_crit=%d;;;0;", procs, warn, crit);

	printf ("\n");
	return result;
}
예제 #2
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;
}
예제 #3
0
int
main (int argc, char **argv)
{
	int result = STATE_UNKNOWN;
	char input_buffer[MAX_INPUT_BUFFER];
	unsigned long latest_entry_time = 0L;
	unsigned long temp_entry_time = 0L;
	int proc_entries = 0;
	time_t current_time;
	char *temp_ptr;
	FILE *fp;
	int procuid = 0;
	int procpid = 0;
	int procppid = 0;
	int procvsz = 0;
	int procrss = 0;
	float procpcpu = 0;
	char procstat[8];
#ifdef PS_USES_PROCETIME
	char procetime[MAX_INPUT_BUFFER];
#endif /* PS_USES_PROCETIME */
	char procprog[MAX_INPUT_BUFFER];
	char *procargs;
	int pos, cols;
	int expected_cols = PS_COLS - 1;
	const char *zombie = "Z";
	char *temp_string;
	output chld_out, chld_err;
	size_t i;

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

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

	/* handle timeouts gracefully... */
	alarm (timeout_interval);

	/* open the status log */
	fp = fopen (status_log, "r");
	if (fp == NULL) {
		die (STATE_CRITICAL, "NAGIOS %s: %s\n", _("CRITICAL"), _("Cannot open status log for reading!"));
	}

	/* get the date/time of the last item updated in the log */
	while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, fp)) {
		if ((temp_ptr = strstr (input_buffer, "created=")) != NULL) {
			temp_entry_time = strtoul (temp_ptr + 8, NULL, 10);
			latest_entry_time = temp_entry_time;
			break;
		} else if ((temp_ptr = strtok (input_buffer, "]")) != NULL) {
			temp_entry_time = strtoul (temp_ptr + 1, NULL, 10);
			if (temp_entry_time > latest_entry_time)
				latest_entry_time = temp_entry_time;
		}
	}
	fclose (fp);

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

	/* run the command to check for the Nagios process.. */
	if((result = np_runcmd(PS_COMMAND, &chld_out, &chld_err, 0)) != 0)
		result = STATE_WARNING;

	/* count the number of matching Nagios processes... */
	for(i = 0; i < chld_out.lines; i++) {
		cols = sscanf (chld_out.line[i], PS_FORMAT, PS_VARLIST);
		/* Zombie processes do not give a procprog command */
		if ( cols == (expected_cols - 1) && strstr(procstat, zombie) ) {
			cols = expected_cols;
			/* Set some value for procargs for the strip command further below
			 * Seen to be a problem on some Solaris 7 and 8 systems */
			chld_out.line[i][pos] = '\n';
			chld_out.line[i][pos+1] = 0x0;
		}
		if ( cols >= expected_cols ) {
			xasprintf (&procargs, "%s", chld_out.line[i] + pos);
			strip (procargs);

			/* Some ps return full pathname for command. This removes path */
			temp_string = strtok ((char *)procprog, "/");
			while (temp_string) {
				strcpy(procprog, temp_string);
				temp_string = strtok (NULL, "/");
			}

			/* May get empty procargs */
			if (!strstr(procargs, argv[0]) && strstr(procargs, process_string) && strcmp(procargs,"")) {
				proc_entries++;
				if (verbose >= 2) {
					printf (_("Found process: %s %s\n"), procprog, procargs);
				}
			}
		}
	}

	/* If we get anything on stderr, at least set warning */
	if(chld_err.buflen)
		result = max_state (result, STATE_WARNING);

	/* reset the alarm handler */
	alarm (0);

	if (proc_entries == 0) {
		die (STATE_CRITICAL, "NAGIOS %s: %s\n", _("CRITICAL"), _("Could not locate a running Nagios process!"));
	}

	if (latest_entry_time == 0L) {
		die (STATE_CRITICAL, "NAGIOS %s: %s\n", _("CRITICAL"), _("Cannot parse Nagios log file for valid time"));
	}

	time (&current_time);
	if ((int)(current_time - latest_entry_time) > (expire_minutes * 60)) {
		result = STATE_WARNING;
	} else {
		result = STATE_OK;
	}

	printf ("NAGIOS %s: ", (result == STATE_OK) ? _("OK") : _("WARNING"));
	printf (ngettext ("%d process", "%d processes", proc_entries), proc_entries);
	printf (", ");
	printf (
	  ngettext ("status log updated %d second ago",
	    "status log updated %d seconds ago",
	    (int) (current_time - latest_entry_time) ),
	    (int) (current_time - latest_entry_time) );
	printf ("\n");

	return result;
}
예제 #4
0
int
main (int argc, char **argv)
{
/* normaly should be  int result = STATE_UNKNOWN; */

  int status = STATE_UNKNOWN;
  int result = 0;
  char *fping_prog = NULL;
  char *server = NULL;
  char *command_line = NULL;
  char *input_buffer = NULL;
  char *option_string = "";
  input_buffer = malloc (MAX_INPUT_BUFFER);

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

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

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

  server = strscpy (server, server_name);

  /* compose the command */
  if (target_timeout)
    xasprintf(&option_string, "%s-t %d ", option_string, target_timeout);
  if (packet_interval)
    xasprintf(&option_string, "%s-p %d ", option_string, packet_interval);
  if (sourceip)
    xasprintf(&option_string, "%s-S %s ", option_string, sourceip);
  if (sourceif)
    xasprintf(&option_string, "%s-I %s ", option_string, sourceif);

#ifdef PATH_TO_FPING6
  if (address_family == AF_INET6)
    fping_prog = strdup(PATH_TO_FPING6);
  else
    fping_prog = strdup(PATH_TO_FPING);
#else
  fping_prog = strdup(PATH_TO_FPING);
#endif

  xasprintf (&command_line, "%s %s-b %d -c %d %s", fping_prog,
            option_string, packet_size, packet_count, server);

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

  /* run the command */
  child_process = spopen (command_line);
  if (child_process == NULL) {
    printf (_("Could not open pipe: %s\n"), command_line);
    return STATE_UNKNOWN;
  }

  child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r");
  if (child_stderr == NULL) {
    printf (_("Could not open stderr for %s\n"), command_line);
  }

  while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process)) {
    if (verbose)
      printf ("%s", input_buffer);
    status = max_state (status, textscan (input_buffer));
  }

  /* If we get anything on STDERR, at least set warning */
  while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_stderr)) {
    status = max_state (status, STATE_WARNING);
    if (verbose)
      printf ("%s", input_buffer);
    status = max_state (status, textscan (input_buffer));
  }
  (void) fclose (child_stderr);

  /* close the pipe */
  if (result = spclose (child_process))
    /* need to use max_state not max */
    status = max_state (status, STATE_WARNING);

  if (result > 1 ) {
    status = max_state (status, STATE_UNKNOWN);
    if (result == 2) {
      die (STATE_UNKNOWN, _("FPING UNKNOWN - IP address not found\n"));
    }
    if (result == 3) {
      die (STATE_UNKNOWN, _("FPING UNKNOWN - invalid commandline argument\n"));
    }
    if (result == 4) {
      die (STATE_UNKNOWN, _("FPING UNKNOWN - failed system call\n"));
    }

  }

  printf ("FPING %s - %s\n", state_text (status), server_name);

  return status;
}
예제 #5
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;
}
예제 #6
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;

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

	/* get the start time */
	gettimeofday (&tv, NULL);

	/* initialize ldap */
#ifdef HAVE_LDAP_INIT
	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
	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, 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;
	}

	/* 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;

	/* print out the result */
	printf (_("LDAP %s - %.3f seconds response time|%s\n"),
	        state_text (status),
	        elapsed_time,
	        fperfdata ("time", elapsed_time, "s",
	                  (int)warn_time, warn_time,
	                  (int)crit_time, crit_time,
	                  TRUE, 0, FALSE, 0));

	return status;
}
int main(int argc, char ** argv)
{
  struct memcached_st *mc;
  memcached_return_t  rc;
  char                key[32];
  u_int32_t           keylen;
  char               *val;
  size_t              value_len;
  uint32_t            flags;
  struct timeval      tv;
  long                microsec;
  double              elapsed_time;

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

  TRACE("%s",">>main");

  // initialize
  gettimeofday(&tv, NULL);
  mc = memcached_create(NULL);
  if (mc == NULL) {
    printf("MEMCACHED %s: failed to memcached_create\n", _("CRITICAL"));
    exit(EXIT_CRITICAL);
  }
  TRACE("[server]%s:%d", mc_host, (int)mc_port);
  rc = memcached_server_add(mc, mc_host, (in_port_t)mc_port);
  TRACE("[mc_server_add rv]%d", rc);
  if (rc != MEMCACHED_SUCCESS) {
    printf("MEMCACHED %s: failed to memcached_server_add (%d)\n", _("CRITICAL"), rc);
    exit(EXIT_CRITICAL);
  }

  memcached_behavior_set(mc, MEMCACHED_BEHAVIOR_TCP_NODELAY, 1);

  srand(time(NULL) & getpid());
  sprintf(key, "%d_%s", rand(), mc_host);
  keylen = strlen(key);
  TRACE("[key]%s[keylen]%d", key, keylen);

  val = (char *)calloc(1, strlen(TEST_VAL)+1);
  sprintf(val, "%s", TEST_VAL);
  TRACE("[val]%s", val);

  // set
  TRACE("[expire]%d", mc_expire);
  rc = memcached_set(mc, key, keylen, val, strlen(val), mc_expire, 0);
  TRACE("[set rv]%d", rc);
  if (rc != MEMCACHED_SUCCESS) {
    printf("MEMCACHED %s: failed to set (%d)\n", _("CRITICAL"), rc);
    exit(EXIT_CRITICAL);
  }
  free(val);

  // get
  val = (char *)memcached_get(mc, key, keylen, &value_len, &flags, &rc);
  TRACE("[val]%s", val);
  if (rc != MEMCACHED_SUCCESS) {
    printf("MEMCACHED %s: failed to get after set\n", _("CRITICAL"));
    exit(EXIT_CRITICAL);
  }
  free(val);

  // delete
  rc = memcached_delete(mc, key, keylen, 0);
  TRACE("[delete rv]%d", rc);
  if (rc != MEMCACHED_SUCCESS) {
    printf("MEMCACHED %s: failed to delete (%d)\n", _("CRITICAL"), rc);
    exit(EXIT_CRITICAL);
  }

  // get
  val = (char *)memcached_get(mc, key, keylen, &value_len, &flags, &rc);
  TRACE("[val]%s", val);
  if (rc != MEMCACHED_NOTFOUND) {
    printf("MEMCACHED %s: failed to get after delete\n", _("CRITICAL"));
    exit(EXIT_CRITICAL);
  }
  free(val);

  memcached_free(mc);

  microsec = deltime(tv);
  elapsed_time = (double)microsec / 1.0e6;
  printf("MEMCACHED %s: %.3f seconds\n", _("OK"), elapsed_time);

  return 0;
}
예제 #8
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);

	/* 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 (verbose)
		printf("Connecting to database:\n DB: %s\n User: %s\n Host: %s\n Port: %d\n", dbName,
		(pguser != NULL) ? pguser : "******",
		(pghost != NULL) ? pghost : "unspecified",
		(pgport != NULL) ? atoi(pgport) : DEFAULT_PORT);

	/* 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);
	if (verbose)
		printf("Time elapsed: %d\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)
		printf("Closing connection\n");
	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;
}
예제 #9
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 -p %d %s -t %s %s %s +tries=%d +time=%d",
            PATH_TO_DIG, dns_server, server_port, query_address, record_type, dig_args, query_transport, 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;
}
예제 #10
0
int
main (int argc, char **argv)
{
	int sd;
	int result = STATE_UNKNOWN;
	char buffer[MAX_INPUT_BUFFER];
	char *status_line = NULL;

	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);
	time (&start_time);

	/* try to connect to the host at the given port number */
	if (my_tcp_connect (server_address, server_port, &sd) != STATE_OK)
		die (STATE_CRITICAL, _("Unable to connect to %s on port %d\n"),
							 server_address, server_port);

	/* Part I - Server Check */

	/* send the OPTIONS request */
	sprintf (buffer, "OPTIONS rtsp://%s:%d RTSP/1.0\r\n", host_name, server_port);
	result = send (sd, buffer, strlen (buffer), 0);

	/* send the header sync */
	sprintf (buffer, "CSeq: 1\r\n");
	result = send (sd, buffer, strlen (buffer), 0);

	/* send a newline so the server knows we're done with the request */
	sprintf (buffer, "\r\n");
	result = send (sd, buffer, strlen (buffer), 0);

	/* watch for the REAL connection string */
	result = recv (sd, buffer, MAX_INPUT_BUFFER - 1, 0);

	/* return a CRITICAL status if we couldn't read any data */
	if (result == -1)
		die (STATE_CRITICAL, _("No data received from %s\n"), host_name);

	/* make sure we find the response we are looking for */
	if (!strstr (buffer, server_expect)) {
		if (server_port == PORT)
			printf ("%s\n", _("Invalid REAL response received from host"));
		else
			printf (_("Invalid REAL response received from host on port %d\n"),
							server_port);
	}
	else {
		/* else we got the REAL string, so check the return code */

		time (&end_time);

		result = STATE_OK;

		status_line = (char *) strtok (buffer, "\n");

		if (strstr (status_line, "200"))
			result = STATE_OK;

		/* client errors result in a warning state */
		else if (strstr (status_line, "400"))
			result = STATE_WARNING;
		else if (strstr (status_line, "401"))
			result = STATE_WARNING;
		else if (strstr (status_line, "402"))
			result = STATE_WARNING;
		else if (strstr (status_line, "403"))
			result = STATE_WARNING;
		else if (strstr (status_line, "404"))
			result = STATE_WARNING;

		/* server errors result in a critical state */
		else if (strstr (status_line, "500"))
			result = STATE_CRITICAL;
		else if (strstr (status_line, "501"))
			result = STATE_CRITICAL;
		else if (strstr (status_line, "502"))
			result = STATE_CRITICAL;
		else if (strstr (status_line, "503"))
			result = STATE_CRITICAL;

		else
			result = STATE_UNKNOWN;
	}

	/* Part II - Check stream exists and is ok */
	if ((result == STATE_OK )&& (server_url != NULL) ) {

		/* Part I - Server Check */

		/* send the OPTIONS request */
		sprintf (buffer, "DESCRIBE rtsp://%s:%d%s RTSP/1.0\n", host_name,
						 server_port, server_url);
		result = send (sd, buffer, strlen (buffer), 0);

		/* send the header sync */
		sprintf (buffer, "CSeq: 2\n");
		result = send (sd, buffer, strlen (buffer), 0);

		/* send a newline so the server knows we're done with the request */
		sprintf (buffer, "\n");
		result = send (sd, buffer, strlen (buffer), 0);

		/* watch for the REAL connection string */
		result = recv (sd, buffer, MAX_INPUT_BUFFER - 1, 0);

		/* return a CRITICAL status if we couldn't read any data */
		if (result == -1) {
			printf (_("No data received from host\n"));
			result = STATE_CRITICAL;
		}
		else {
			/* make sure we find the response we are looking for */
			if (!strstr (buffer, server_expect)) {
				if (server_port == PORT)
					printf ("%s\n", _("Invalid REAL response received from host"));
				else
					printf (_("Invalid REAL response received from host on port %d\n"),
									server_port);
			}
			else {

				/* else we got the REAL string, so check the return code */

				time (&end_time);

				result = STATE_OK;

				status_line = (char *) strtok (buffer, "\n");

				if (strstr (status_line, "200"))
					result = STATE_OK;

				/* client errors result in a warning state */
				else if (strstr (status_line, "400"))
					result = STATE_WARNING;
				else if (strstr (status_line, "401"))
					result = STATE_WARNING;
				else if (strstr (status_line, "402"))
					result = STATE_WARNING;
				else if (strstr (status_line, "403"))
					result = STATE_WARNING;
				else if (strstr (status_line, "404"))
					result = STATE_WARNING;

				/* server errors result in a critical state */
				else if (strstr (status_line, "500"))
					result = STATE_CRITICAL;
				else if (strstr (status_line, "501"))
					result = STATE_CRITICAL;
				else if (strstr (status_line, "502"))
					result = STATE_CRITICAL;
				else if (strstr (status_line, "503"))
					result = STATE_CRITICAL;

				else
					result = STATE_UNKNOWN;
			}
		}
	}

	/* Return results */
	if (result == STATE_OK) {

		if (check_critical_time == TRUE
				&& (end_time - start_time) > critical_time) result = STATE_CRITICAL;
		else if (check_warning_time == TRUE
						 && (end_time - start_time) > warning_time) result =
				STATE_WARNING;

		/* Put some HTML in here to create a dynamic link */
		printf (_("REAL %s - %d second response time\n"),
						state_text (result),
						(int) (end_time - start_time));
	}
	else
		printf ("%s\n", status_line);

	/* close the connection */
	close (sd);

	/* reset the alarm */
	alarm (0);

	return result;
}
예제 #11
0
int
main (int argc, char **argv)
{
	char command_line[1024];
	int result = STATE_UNKNOWN;
	int line;
	char input_buffer[MAX_INPUT_BUFFER];
	char query_string[512];
	char *errmsg;
	char *temp_buffer;
	int line_status = ONLINE;
	int paper_status = 0;
	int intervention_required = 0;
	int peripheral_error = 0;
	int paper_jam = 0;
	int paper_out = 0;
	int toner_low = 0;
	int page_punt = 0;
	int memory_out = 0;
	int door_open = 0;
	int paper_output = 0;
	char display_message[MAX_INPUT_BUFFER];

	errmsg = malloc(MAX_INPUT_BUFFER);

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

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

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

	/* removed ' 2>1' at end of command 10/27/1999 - EG */
	/* create the query string */
	sprintf
		(query_string,
		 "%s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0",
		 HPJD_LINE_STATUS,
		 HPJD_PAPER_STATUS,
		 HPJD_INTERVENTION_REQUIRED,
		 HPJD_GD_PERIPHERAL_ERROR,
		 HPJD_GD_PAPER_JAM,
		 HPJD_GD_PAPER_OUT,
		 HPJD_GD_TONER_LOW,
		 HPJD_GD_PAGE_PUNT,
		 HPJD_GD_MEMORY_OUT,
		 HPJD_GD_DOOR_OPEN, HPJD_GD_PAPER_OUTPUT, HPJD_GD_STATUS_DISPLAY);

	/* get the command to run */
	sprintf (command_line, "%s -OQa -m : -v 1 -c %s %s %s", PATH_TO_SNMPGET, community,
									address, query_string);

	/* run the command */
	child_process = spopen (command_line);
	if (child_process == NULL) {
		printf (_("Could not open pipe: %s\n"), command_line);
		return STATE_UNKNOWN;
	}

	child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r");
	if (child_stderr == NULL) {
		printf (_("Could not open stderr for %s\n"), command_line);
	}

	result = STATE_OK;

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

		/* strip the newline character from the end of the input */
		if (input_buffer[strlen (input_buffer) - 1] == '\n')
			input_buffer[strlen (input_buffer) - 1] = 0;

		line++;

		temp_buffer = strtok (input_buffer, "=");
		temp_buffer = strtok (NULL, "=");

		if (temp_buffer == NULL && line < 13) {

				result = STATE_UNKNOWN;
				strcpy (errmsg, input_buffer);

		} else {

			switch (line) {

			case 1:										/* 1st line should contain the line status */
				line_status = atoi (temp_buffer);
				break;
			case 2:										/* 2nd line should contain the paper status */
				paper_status = atoi (temp_buffer);
				break;
			case 3:										/* 3rd line should be intervention required */
				intervention_required = atoi (temp_buffer);
				break;
			case 4:										/* 4th line should be peripheral error */
				peripheral_error = atoi (temp_buffer);
				break;
			case 5:										/* 5th line should contain the paper jam status */
				paper_jam = atoi (temp_buffer);
				break;
			case 6:										/* 6th line should contain the paper out status */
				paper_out = atoi (temp_buffer);
				break;
			case 7:										/* 7th line should contain the toner low status */
				toner_low = atoi (temp_buffer);
				break;
			case 8:										/* did data come too slow for engine */
				page_punt = atoi (temp_buffer);
				break;
			case 9:										/* did we run out of memory */
				memory_out = atoi (temp_buffer);
				break;
			case 10:										/* is there a door open */
				door_open = atoi (temp_buffer);
				break;
			case 11:										/* is output tray full */
				paper_output = atoi (temp_buffer);
				break;
			case 12:										/* display panel message */
				strcpy (display_message, temp_buffer + 1);
				break;
			default:										/* fold multiline message */
				strncat (display_message, input_buffer,
						sizeof (display_message) - strlen (display_message) - 1);
			}

		}

		/* break out of the read loop if we encounter an error */
		if (result != STATE_OK)
			break;
	}

	/* WARNING if output found on stderr */
	if (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_stderr)) {
		result = max_state (result, STATE_WARNING);
		/* remove CRLF */
		if (input_buffer[strlen (input_buffer) - 1] == '\n')
			input_buffer[strlen (input_buffer) - 1] = 0;
		sprintf (errmsg, "%s", input_buffer );

	}

	/* close stderr */
	(void) fclose (child_stderr);

	/* close the pipe */
	if (spclose (child_process))
		result = max_state (result, STATE_WARNING);

	/* if there wasn't any output, display an error */
	if (line == 0) {

		/* might not be the problem, but most likely is. */
		result = STATE_UNKNOWN ;
		xasprintf (&errmsg, "%s : Timeout from host %s\n", errmsg, address );

	}

	/* if we had no read errors, check the printer status results... */
	if (result == STATE_OK) {

		if (paper_jam) {
			result = STATE_WARNING;
			strcpy (errmsg, _("Paper Jam"));
		}
		else if (paper_out) {
			result = STATE_WARNING;
			strcpy (errmsg, _("Out of Paper"));
		}
		else if (line_status == OFFLINE) {
			if (strcmp (errmsg, "POWERSAVE ON") != 0) {
				result = STATE_WARNING;
				strcpy (errmsg, _("Printer Offline"));
			}
		}
		else if (peripheral_error) {
			result = STATE_WARNING;
			strcpy (errmsg, _("Peripheral Error"));
		}
		else if (intervention_required) {
			result = STATE_WARNING;
			strcpy (errmsg, _("Intervention Required"));
		}
		else if (toner_low) {
			result = STATE_WARNING;
			strcpy (errmsg, _("Toner Low"));
		}
		else if (memory_out) {
			result = STATE_WARNING;
			strcpy (errmsg, _("Insufficient Memory"));
		}
		else if (door_open) {
			result = STATE_WARNING;
			strcpy (errmsg, _("A Door is Open"));
		}
		else if (paper_output) {
			result = STATE_WARNING;
			strcpy (errmsg, _("Output Tray is Full"));
		}
		else if (page_punt) {
			result = STATE_WARNING;
			strcpy (errmsg, _("Data too Slow for Engine"));
		}
		else if (paper_status) {
			result = STATE_WARNING;
			strcpy (errmsg, _("Unknown Paper Error"));
		}
	}

	if (result == STATE_OK)
		printf (_("Printer ok - (%s)\n"), display_message);

	else if (result == STATE_UNKNOWN) {

		printf ("%s\n", errmsg);

		/* if printer could not be reached, escalate to critical */
		if (strstr (errmsg, "Timeout"))
			result = STATE_CRITICAL;
	}

	else if (result == STATE_WARNING)
		printf ("%s (%s)\n", errmsg, display_message);

	return result;
}
int
main (int argc, char *argv[]) 
{
	char *device = NULL;
	int o, longindex;
	int retval = 0;

	thresholds_t thresholds;
	values_t values;
	int fd;

	static struct option longopts[] = { 
		{"device", required_argument, 0, 'd'}, 
		{"immediate", no_argument, 0, 'i'}, 
		{"quiet-check", no_argument, 0, 'q'}, 
		{"auto-on", no_argument, 0, '1'}, 
		{"auto-off", no_argument, 0, '0'}, 
		{"nagios", no_argument, 0, 'n'}, /* DEPRECATED, but we still accept it */
		{"help", no_argument, 0, 'h'}, 
		{"version", no_argument, 0, 'V'},
		{0, 0, 0, 0}
	};

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

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

	while (1) {
		
		o = getopt_long (argc, argv, "+d:iq10nhVv", longopts, &longindex);

		if (o == -1 || o == EOF || o == 1)
			break;

		switch (o) {
		case 'd':
			device = optarg;
			break;
		case 'q':
			fprintf (stderr, "%s\n", _("DEPRECATION WARNING: the -q switch (quiet output) is no longer \"quiet\"."));
			fprintf (stderr, "%s\n", _("Nagios-compatible output is now always returned."));
			break;
		case 'i':
		case '1':
		case '0':
			printf ("%s\n", _("SMART commands are broken and have been disabled (See Notes in --help)."));
			return STATE_CRITICAL;
			break;
		case 'n':
			fprintf (stderr, "%s\n", _("DEPRECATION WARNING: the -n switch (Nagios-compatible output) is now the"));
			fprintf (stderr, "%s\n", _("default and will be removed from future releases."));
			break;
		case 'v': /* verbose */
			verbose = TRUE;
			break;
		case 'h':
			print_help ();
			return STATE_OK;
		case 'V':
			print_revision (progname, NP_VERSION);
			return STATE_OK;
		default:
			usage5 ();
		}
	}

	if (optind < argc) {
		device = argv[optind];
	}

	if (!device) {
		print_help ();
		return STATE_OK;
	}

	fd = open (device, OPEN_MODE);

	if (fd < 0) {
		printf (_("CRITICAL - Couldn't open device %s: %s\n"), device, strerror (errno));
		return STATE_CRITICAL;
	}

	if (smart_cmd_simple (fd, SMART_CMD_ENABLE, 0, FALSE)) {
		printf (_("CRITICAL - SMART_CMD_ENABLE\n"));
		return STATE_CRITICAL;
	}

	smart_read_values (fd, &values);
	smart_read_thresholds (fd, &thresholds);
	retval = nagios (&values, &thresholds);
	if (verbose) print_values (&values, &thresholds);

	close (fd);
	return retval;
}
예제 #13
0
int
main (int argc, char **argv)
{
/* normaly should be  int result = STATE_UNKNOWN; */

  int status = STATE_UNKNOWN;
  char *server = NULL;
  char *command_line = NULL;
  char *input_buffer = NULL;
  char *option_string = "";
  input_buffer = malloc (MAX_INPUT_BUFFER);

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

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

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

  server = strscpy (server, server_name);

  /* compose the command */
  if (target_timeout)
    asprintf(&option_string, "%s-t %d ", option_string, target_timeout);
  if (packet_interval)
    asprintf(&option_string, "%s-p %d ", option_string, packet_interval);

  asprintf (&command_line, "%s %s-b %d -c %d %s", PATH_TO_FPING,
            option_string, packet_size, packet_count, server);

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

  /* run the command */
  child_process = spopen (command_line);
  if (child_process == NULL) {
    printf (_("Could not open pipe: %s\n"), command_line);
    return STATE_UNKNOWN;
  }

  child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r");
  if (child_stderr == NULL) {
    printf (_("Could not open stderr for %s\n"), command_line);
  }

  while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process)) {
    if (verbose)
      printf ("%s", input_buffer);
    status = max_state (status, textscan (input_buffer));
  }

  /* If we get anything on STDERR, at least set warning */
  while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_stderr)) {
    status = max_state (status, STATE_WARNING);
    if (verbose)
      printf ("%s", input_buffer);
    status = max_state (status, textscan (input_buffer));
  }
  (void) fclose (child_stderr);

  /* close the pipe */
  if (spclose (child_process))
    /* need to use max_state not max */
    status = max_state (status, STATE_WARNING);

  printf ("FPING %s - %s\n", state_text (status), server_name);

  return status;
}
예제 #14
0
int
main (int argc, char **argv)
{

	char *status_text;
	int cresult;
	int result = STATE_UNKNOWN;
	int i;
	time_t local_time;
	FILE *fp = NULL;
	output chld_out, chld_err;

	remotecmd = "";
	comm_append(SSH_COMMAND);

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

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

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

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

	/* run the command */
	if (verbose) {
		printf ("Command: %s\n", commargv[0]);
		for (i=1; i<commargc; i++)
			printf ("Argument %i: %s\n", i, commargv[i]);
	}

	result = cmd_run_array (commargv, &chld_out, &chld_err, 0);

	if (verbose) {
		for(i = 0; i < chld_out.lines; i++)
			printf("stdout: %s\n", chld_out.line[i]);
		for(i = 0; i < chld_err.lines; i++)
			printf("stderr: %s\n", chld_err.line[i]);
	}

	if (skip_stdout == -1) /* --skip-stdout specified without argument */
		skip_stdout = chld_out.lines;
	if (skip_stderr == -1) /* --skip-stderr specified without argument */
		skip_stderr = chld_err.lines;

	/* UNKNOWN or worse if (non-skipped) output found on stderr */
	if(chld_err.lines > skip_stderr) {
		printf (_("Remote command execution failed: %s\n"),
		        chld_err.line[skip_stderr]);
		return max_state_alt(result, STATE_UNKNOWN);
	}

	/* this is simple if we're not supposed to be passive.
	 * Wrap up quickly and keep the tricks below */
	if(!passive) {
		if (chld_out.lines > skip_stdout)
			for (i = skip_stdout; i < chld_out.lines; i++)
				puts (chld_out.line[i]);
		else
			printf (_("%s - check_by_ssh: Remote command '%s' returned status %d\n"),
			        state_text(result), remotecmd, result);
		return result; 	/* return error status from remote command */
	}


	/*
	 * Passive mode
	 */

	/* process output */
	if (!(fp = fopen (outputfile, "a"))) {
		printf (_("SSH WARNING: could not open %s\n"), outputfile);
		exit (STATE_UNKNOWN);
	}

	local_time = time (NULL);
	commands = 0;
	for(i = skip_stdout; i < chld_out.lines; i++) {
		status_text = chld_out.line[i++];
		if (i == chld_out.lines || strstr (chld_out.line[i], "STATUS CODE: ") == NULL)
			die (STATE_UNKNOWN, _("%s: Error parsing output\n"), progname);

		if (service[commands] && status_text
			&& sscanf (chld_out.line[i], "STATUS CODE: %d", &cresult) == 1)
		{
			fprintf (fp, "[%d] PROCESS_SERVICE_CHECK_RESULT;%s;%s;%d;%s\n",
			         (int) local_time, host_shortname, service[commands++],
			         cresult, status_text);
		}
	}
	
	/* Multiple commands and passive checking should always return OK */
	return result;
}
예제 #15
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;
}
예제 #16
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, popen_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 */
  asprintf (&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;
      asprintf(&temp_buffer, "%s%s; ", temp_buffer, expected_address[i]);
    }
    if (result == STATE_CRITICAL) {
      /* Strip off last semicolon... */
      temp_buffer[strlen(temp_buffer)-2] = '\0';
      asprintf(&msg, _("expected '%s' but got '%s'"), temp_buffer, address);
    }
  }

  /* check if authoritative */
  if (result == STATE_OK && expect_authority && non_authoritative) {
    result = STATE_CRITICAL;
    asprintf(&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;
}
int main(int argc, char ** argv)
{
  struct memcached_st *mc;
  struct memcached_stat_st *stats;
  memcached_return_t rc;
  long             cur_conn = -1;
  int              status;
  char*            status_msg;
  struct timeval   tv;
  long             microsec;
  double           elapsed_time;

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

  TRACE("%s",">>main");

  // initialize
  gettimeofday(&tv, NULL);
  mc = memcached_create(NULL);
  if (mc == NULL) {
    printf("MEMCACHED %s: failed to memcached_create\n", _("CRITICAL"));
    exit(EXIT_CRITICAL);
  }
  TRACE("[server]%s:%s", mc_host, mc_port);
  rc = memcached_server_add(mc, mc_host, (in_port_t)mc_port);
  TRACE("[mc_server_add rv]%d", rc);
  if (rc != MEMCACHED_SUCCESS) {
    printf("MEMCACHED %s: failed to memcached_server_add (%d)\n", _("CRITICAL"), rc);
    exit(EXIT_CRITICAL);
  }

  memcached_behavior_set(mc, MEMCACHED_BEHAVIOR_TCP_NODELAY, 1);

  stats = memcached_stat(mc, NULL, &rc);
  if (! stats) {
    printf("MEMCACHED %s: failed to memcached_stats\n", _("CRITICAL"));
    exit(EXIT_CRITICAL);
  }

  cur_conn = stats->curr_connections;

  memcached_stat_free(mc, stats);
  memcached_free(mc);

  status = get_status(cur_conn, my_thresholds);

  status_msg = _("CRITICAL");
  if (status == STATE_OK) {
      status_msg = _("OK");
  } else if (status == STATE_WARNING) {
      status_msg = _("WARNING");
  } else if (status == STATE_CRITICAL) {
      status_msg = _("CRITICAL");
  }

  microsec = deltime(tv);
  elapsed_time = (double)microsec / 1.0e6;
  printf("MEMCACHED %s: conn %ld, %.3f seconds\n", status_msg, cur_conn, elapsed_time);

  return status;
}
예제 #18
0
int main(int argc, char *argv[]){
	int result, offset_result, jitter_result;
	double offset=0, jitter=0;
	char *result_line, *perfdata_line;

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

	result = offset_result = jitter_result = STATE_OK;

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

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

	set_thresholds(&offset_thresholds, owarn, ocrit);
	set_thresholds(&jitter_thresholds, jwarn, jcrit);

	/* initialize alarm signal handling */
	signal (SIGALRM, socket_timeout_alarm_handler);

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

	offset = offset_request(server_address, &offset_result);
	/* check_ntp used to always return CRITICAL if offset_result == STATE_UNKNOWN.
	 * Now we'll only do that is the offset thresholds were set */
	if (do_offset && offset_result == STATE_UNKNOWN) {
		result = STATE_CRITICAL;
	} else {
		result = get_status(fabs(offset), offset_thresholds);
	}

	/* If not told to check the jitter, we don't even send packets.
	 * jitter is checked using NTP control packets, which not all
	 * servers recognize.  Trying to check the jitter on OpenNTPD
	 * (for example) will result in an error
	 */
	if(do_jitter){
		jitter=jitter_request(server_address, &jitter_result);
		result = max_state_alt(result, get_status(jitter, jitter_thresholds));
		/* -1 indicates that we couldn't calculate the jitter
		 * Only overrides STATE_OK from the offset */
		if(jitter == -1.0 && result == STATE_OK)
			result = STATE_UNKNOWN;
	}
	result = max_state_alt(result, jitter_result);

	switch (result) {
		case STATE_CRITICAL :
			xasprintf(&result_line, _("NTP CRITICAL:"));
			break;
		case STATE_WARNING :
			xasprintf(&result_line, _("NTP WARNING:"));
			break;
		case STATE_OK :
			xasprintf(&result_line, _("NTP OK:"));
			break;
		default :
			xasprintf(&result_line, _("NTP UNKNOWN:"));
			break;
	}
	if(offset_result == STATE_UNKNOWN){
		xasprintf(&result_line, "%s %s", result_line, _("Offset unknown"));
		xasprintf(&perfdata_line, "");
	} else {
		xasprintf(&result_line, "%s %s %.10g secs", result_line, _("Offset"), offset);
		xasprintf(&perfdata_line, "%s", perfd_offset(offset));
	}
	if (do_jitter) {
		xasprintf(&result_line, "%s, jitter=%f", result_line, jitter);
		xasprintf(&perfdata_line, "%s %s", perfdata_line,  perfd_jitter(jitter));
	}
	printf("%s|%s\n", result_line, perfdata_line);

	if(server_address!=NULL) free(server_address);
	return result;
}
예제 #19
0
int
main (int argc, char *argv[]) 
{
	char *device = NULL;
	int command = -1;
	int o, longindex;
	int retval = 0;

	thresholds_t thresholds;
	values_t values;
	int fd;

	static struct option longopts[] = { 
		{"device", required_argument, 0, 'd'}, 
		{"immediate", no_argument, 0, 'i'}, 
		{"quiet-check", no_argument, 0, 'q'}, 
		{"auto-on", no_argument, 0, '1'}, 
		{"auto-off", no_argument, 0, '0'}, 
		{"nagios", no_argument, 0, 'n'}, 
		{"help", no_argument, 0, 'h'}, 
		{"version", no_argument, 0, 'V'},
		{0, 0, 0, 0}
	};

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

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

	while (1) {
		
		o = getopt_long (argc, argv, "+d:iq10nhV", longopts, &longindex);

		if (o == -1 || o == EOF || o == 1)
			break;

		switch (o) {
		case 'd':
			device = optarg;
			break;
		case 'q':
			command = 3;
			break;
		case 'i':
			command = 2;
			break;
		case '1':
			command = 1;
			break;
		case '0':
			command = 0;
			break;
		case 'n':
			command = 4;
			break;
		case 'h':
			print_help ();
			return STATE_OK;
		case 'V':
			print_revision (progname, NP_VERSION);
			return STATE_OK;
		default:
			usage5 ();
		}
	}

	if (optind < argc) {
		device = argv[optind];
	}

	if (!device) {
		print_help ();
		return STATE_OK;
	}

	fd = open (device, O_RDONLY);

	if (fd < 0) {
		printf (_("CRITICAL - Couldn't open device %s: %s\n"), device, strerror (errno));
		return STATE_CRITICAL;
	}

	if (smart_cmd_simple (fd, SMART_CMD_ENABLE, 0, TRUE)) {
		printf (_("CRITICAL - SMART_CMD_ENABLE\n"));
		return STATE_CRITICAL;
	}

	switch (command) {
	case 0:
		retval = smart_cmd_simple (fd, SMART_CMD_AUTO_OFFLINE, 0, TRUE);
		break;
	case 1:
		retval = smart_cmd_simple (fd, SMART_CMD_AUTO_OFFLINE, 0xF8, TRUE);
		break;
	case 2:
		retval = smart_cmd_simple (fd, SMART_CMD_IMMEDIATE_OFFLINE, 0, TRUE);
		break;
	case 3:
		smart_read_values (fd, &values);
		smart_read_thresholds (fd, &thresholds);
		retval = values_not_passed (&values, &thresholds);
		break;
	case 4:
		smart_read_values (fd, &values);
		smart_read_thresholds (fd, &thresholds);
		retval = nagios (&values, &thresholds);
		break;
	default:
		smart_read_values (fd, &values);
		smart_read_thresholds (fd, &thresholds);
		print_values (&values, &thresholds);
		break;
	}
	close (fd);
	return retval;
}
예제 #20
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;
}
예제 #21
0
int
main (int argc, char **argv)
{
	int users = -1;
	int result = STATE_UNKNOWN;
	char *perf;
#if HAVE_WTSAPI32_H
	WTS_SESSION_INFO *wtsinfo;
	DWORD wtscount;
	DWORD index;
#elif HAVE_UTMPX_H
	struct utmpx *putmpx;
#else
	char input_buffer[MAX_INPUT_BUFFER];
#endif

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

	perf = strdup ("");

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

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

	users = 0;

#if HAVE_WTSAPI32_H
	if (!WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE,
	  0, 1, &wtsinfo, &wtscount)) {
		printf(_("Could not enumerate RD sessions: %d\n"), GetLastError());
		return STATE_UNKNOWN;
	}

	for (index = 0; index < wtscount; index++) {
		LPTSTR username;
		DWORD size;
		int len;

		if (!WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE,
		  wtsinfo[index].SessionId, WTSUserName, &username, &size))
			continue;

		len = lstrlen(username);

		WTSFreeMemory(username);

		if (len == 0)
			continue;

		if (wtsinfo[index].State == WTSActive ||
		  wtsinfo[index].State == WTSDisconnected)
			users++;
	}

	WTSFreeMemory(wtsinfo);
#elif HAVE_UTMPX_H
	/* get currently logged users from utmpx */
	setutxent ();

	while ((putmpx = getutxent ()) != NULL)
		if (putmpx->ut_type == USER_PROCESS)
			users++;

	endutxent ();
#else
	/* run the command */
	child_process = spopen (WHO_COMMAND);
	if (child_process == NULL) {
		printf (_("Could not open pipe: %s\n"), WHO_COMMAND);
		return STATE_UNKNOWN;
	}

	child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r");
	if (child_stderr == NULL)
		printf (_("Could not open stderr for %s\n"), WHO_COMMAND);

	while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process)) {
		/* increment 'users' on all lines except total user count */
		if (input_buffer[0] != '#') {
			users++;
			continue;
		}

		/* get total logged in users */
		if (sscanf (input_buffer, _("# users=%d"), &users) == 1)
			break;
	}

	/* check STDERR */
	if (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_stderr))
		result = possibly_set (result, STATE_UNKNOWN);
	(void) fclose (child_stderr);

	/* close the pipe */
	if (spclose (child_process))
		result = possibly_set (result, STATE_UNKNOWN);
#endif

	/* check the user count against warning and critical thresholds */
	if (users > cusers)
		result = STATE_CRITICAL;
	else if (users > wusers)
		result = STATE_WARNING;
	else if (users >= 0)
		result = STATE_OK;

	if (result == STATE_UNKNOWN)
		printf ("%s\n", _("Unable to read output"));
	else {
		xasprintf (&perf, "%s", perfdata ("users", users, "",
		  TRUE, wusers,
		  TRUE, cusers,
		  TRUE, 0,
		  FALSE, 0));
		printf (_("USERS %s - %d users currently logged in |%s\n"), state_text (result),
		  users, perf);
	}

	return result;
}
예제 #22
0
int
main (int argc, char **argv)
{
  int result = STATE_UNKNOWN;
  int disk_result = STATE_UNKNOWN;
  char *output;
  char *details;
  char *perf;
  char *preamble;
  double inode_space_pct;
  double warning_high_tide;
  double critical_high_tide;
  int temp_result;

  struct mount_entry *me;
  struct fs_usage fsp, tmpfsp;
  struct parameter_list *temp_list, *path;

  preamble = strdup (" - free space:");
  output = strdup ("");
  details = strdup ("");
  perf = strdup ("");
  stat_buf = malloc(sizeof *stat_buf);

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

  mount_list = read_file_system_list (0);

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

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

  /* If a list of paths has not been selected, find entire
     mount list and create list of paths
   */
  if (path_selected == FALSE) {
    for (me = mount_list; me; me = me->me_next) {
      if (! (path = np_find_parameter(path_select_list, me->me_mountdir))) {
        path = np_add_parameter(&path_select_list, me->me_mountdir);
      }
      path->best_match = me;
      path->group = group;
      set_all_thresholds(path);
    }
  }
  np_set_best_match(path_select_list, mount_list, exact_match);

  /* Error if no match found for specified paths */
  temp_list = path_select_list;

  while (temp_list) {
    if (! temp_list->best_match) {
      die (STATE_CRITICAL, _("DISK %s: %s not found\n"), _("CRITICAL"), temp_list->name);
    }

    temp_list = temp_list->name_next;
  }

  /* Process for every path in list */
  for (path = path_select_list; path; path=path->name_next) {

    if (verbose >= 3 && path->freespace_percent->warning != NULL && path->freespace_percent->critical != NULL)
      printf("Thresholds(pct) for %s warn: %f crit %f\n",path->name, path->freespace_percent->warning->end,
                                                         path->freespace_percent->critical->end);

    if (verbose >= 3 && path->group != NULL)
      printf("Group of %s: %s\n",path->name,path->group);

    /* reset disk result */
    disk_result = STATE_UNKNOWN;

    me = path->best_match;

    /* Filters */

    /* Remove filesystems already seen */
    if (np_seen_name(seen, me->me_mountdir)) {
      continue;
    } 
    np_add_name(&seen, me->me_mountdir);

    if (path->group == NULL) {
      /* Skip remote filesystems if we're not interested in them */
      if (me->me_remote && show_local_fs) {
        if (stat_remote_fs)
          stat_path(path);
        continue;
      /* Skip pseudo fs's if we haven't asked for all fs's */
      } else if (me->me_dummy && !show_all_fs) {
        continue;
      /* Skip excluded fstypes */
      } else if (fs_exclude_list && np_find_name (fs_exclude_list, me->me_type)) {
        continue;
      /* Skip excluded fs's */
      } else if (dp_exclude_list &&
               (np_find_name (dp_exclude_list, me->me_devname) ||
                np_find_name (dp_exclude_list, me->me_mountdir))) {
        continue;
      /* Skip not included fstypes */
      } else if (fs_include_list && !np_find_name (fs_include_list, me->me_type)) {
        continue;
      }

      stat_path(path);
      get_fs_usage (me->me_mountdir, me->me_devname, &fsp);
    }

    if (fsp.fsu_blocks && strcmp ("none", me->me_mountdir)) {
      get_stats (path, &fsp);

      if (verbose >= 3) {
        printf ("For %s, used_pct=%g free_pct=%g used_units=%g free_units=%g total_units=%g used_inodes_pct=%g free_inodes_pct=%g fsp.fsu_blocksize=%llu mult=%llu\n",
          me->me_mountdir, path->dused_pct, path->dfree_pct, path->dused_units, path->dfree_units, path->dtotal_units, path->dused_inodes_percent, path->dfree_inodes_percent, fsp.fsu_blocksize, mult);
      }

      /* Threshold comparisons */

      temp_result = get_status(path->dfree_units, path->freespace_units);
      if (verbose >=3) printf("Freespace_units result=%d\n", temp_result);
      disk_result = max_state( disk_result, temp_result );

      temp_result = get_status(path->dfree_pct, path->freespace_percent);
      if (verbose >=3) printf("Freespace%% result=%d\n", temp_result);
      disk_result = max_state( disk_result, temp_result );

      temp_result = get_status(path->dused_units, path->usedspace_units);
      if (verbose >=3) printf("Usedspace_units result=%d\n", temp_result);
      disk_result = max_state( disk_result, temp_result );

      temp_result = get_status(path->dused_pct, path->usedspace_percent);
      if (verbose >=3) printf("Usedspace_percent result=%d\n", temp_result);
      disk_result = max_state( disk_result, temp_result );

      temp_result = get_status(path->dused_inodes_percent, path->usedinodes_percent);
      if (verbose >=3) printf("Usedinodes_percent result=%d\n", temp_result);
      disk_result = max_state( disk_result, temp_result );

      temp_result = get_status(path->dfree_inodes_percent, path->freeinodes_percent);
      if (verbose >=3) printf("Freeinodes_percent result=%d\n", temp_result);
      disk_result = max_state( disk_result, temp_result );

      result = max_state(result, disk_result);

      /* What a mess of units. The output shows free space, the perf data shows used space. Yikes!
         Hack here. Trying to get warn/crit levels from freespace_(units|percent) for perf
         data. Assumption that start=0. Roll on new syntax...
      */

      /* *_high_tide must be reinitialized at each run */
      warning_high_tide = UINT_MAX;
      critical_high_tide = UINT_MAX;

      if (path->freespace_units->warning != NULL) {
        warning_high_tide = path->dtotal_units - path->freespace_units->warning->end;
      }
      if (path->freespace_percent->warning != NULL) {
        warning_high_tide = abs( min( (double) warning_high_tide, (double) (1.0 - path->freespace_percent->warning->end/100)*path->dtotal_units ));
      }
      if (path->freespace_units->critical != NULL) {
        critical_high_tide = path->dtotal_units - path->freespace_units->critical->end;
      }
      if (path->freespace_percent->critical != NULL) {
        critical_high_tide = abs( min( (double) critical_high_tide, (double) (1.0 - path->freespace_percent->critical->end/100)*path->dtotal_units ));
      }

      /* Nb: *_high_tide are unset when == UINT_MAX */
      xasprintf (&perf, "%s %s", perf,
                perfdata ((!strcmp(me->me_mountdir, "none") || display_mntp) ? me->me_devname : me->me_mountdir,
                          path->dused_units, units,
                          (warning_high_tide != UINT_MAX ? TRUE : FALSE), warning_high_tide,
                          (critical_high_tide != UINT_MAX ? TRUE : FALSE), critical_high_tide,
                          TRUE, 0,
                          TRUE, path->dtotal_units));

      if (disk_result==STATE_OK && erronly && !verbose)
        continue;

      xasprintf (&output, "%s %s %.0f %s (%.0f%%",
                output,
                (!strcmp(me->me_mountdir, "none") || display_mntp) ? me->me_devname : me->me_mountdir,
                path->dfree_units,
                units,
                path->dfree_pct);
      if (path->dused_inodes_percent < 0) {
        xasprintf(&output, "%s inode=-);", output);
      } else {
        xasprintf(&output, "%s inode=%.0f%%);", output, path->dfree_inodes_percent );
      }

      /* TODO: Need to do a similar debug line
      xasprintf (&details, _("%s\n\
%.0f of %.0f %s (%.0f%% inode=%.0f%%) free on %s (type %s mounted on %s) warn:%lu crit:%lu warn%%:%.0f%% crit%%:%.0f%%"),
                details, dfree_units, dtotal_units, units, dfree_pct, inode_space_pct,
                me->me_devname, me->me_type, me->me_mountdir,
                (unsigned long)w_df, (unsigned long)c_df, w_dfp, c_dfp);
      */

    }

  }

  if (verbose >= 2)
    xasprintf (&output, "%s%s", output, details);


  printf ("DISK %s%s%s|%s\n", state_text (result), (erronly && result==STATE_OK) ? "" : preamble, output, perf);
  return result;
}
예제 #23
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)
		asprintf (&helocmd, "%s%s%s", SMTP_EHLO, localhostname, "\r\n");
	else
		asprintf (&helocmd, "%s%s%s", SMTP_HELO, localhostname, "\r\n");

	if (verbose)
		printf("HELOCMD: %s", helocmd);

	/* initialize the MAIL command with optional FROM command  */
	asprintf (&cmd_str, "%sFROM: %s%s", mail_command, from_arg, "\r\n");

	if (verbose && smtp_use_dummycmd)
		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

		/* sendmail will syslog a "NOQUEUE" error if session does not attempt
		 * to do something useful. This can be prevented by giving a command
		 * even if syntax is illegal (MAIL requires a FROM:<...> argument)
		 *
		 * According to rfc821 you can include a null reversepath in the from command
		 * - but a log message is generated on the smtp server.
		 *
		 * Use the -f option to provide a FROM address
		 */
		if (smtp_use_dummycmd) {
		  my_send(cmd_str, strlen(cmd_str));
		  if (recvlines(buffer, MAX_INPUT_BUFFER) >= 1 && verbose)
		    printf("%s", buffer);
		}

		while (n < ncommands) {
			asprintf (&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;
						asprintf(&error_msg, _("no authuser specified, "));
						break;
					}
					if (authpass == NULL) {
						result = STATE_CRITICAL;
						asprintf(&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) {
						asprintf(&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;
						asprintf(&error_msg, _("invalid response received after AUTH LOGIN, "));
						break;
					}

					/* encode authuser with base64 */
					base64_encode_alloc (authuser, strlen(authuser), &abuf);
					/* FIXME: abuf shouldn't have enough space to strcat a '\r\n' into it. */
					strcat (abuf, "\r\n");
					my_send(abuf, strlen(abuf));
					if (verbose)
						printf (_("sent %s\n"), abuf);

					if ((ret = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) {
						result = STATE_CRITICAL;
						asprintf(&error_msg, _("recv() failed after sending authuser, "));
						break;
					}
					if (verbose) {
						printf (_("received %s\n"), buffer);
					}
					if (strncmp (buffer, "334", 3) != 0) {
						result = STATE_CRITICAL;
						asprintf(&error_msg, _("invalid response received after authuser, "));
						break;
					}
					/* encode authpass with base64 */
					base64_encode_alloc (authpass, strlen(authpass), &abuf);
					/* FIXME: abuf shouldn't have enough space to strcat a '\r\n' into it. */
					strcat (abuf, "\r\n");
					my_send(abuf, strlen(abuf));
					if (verbose) {
						printf (_("sent %s\n"), abuf);
					}
					if ((ret = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) {
						result = STATE_CRITICAL;
						asprintf(&error_msg, _("recv() failed after sending authpass, "));
						break;
					}
					if (verbose) {
						printf (_("received %s\n"), buffer);
					}
					if (strncmp (buffer, "235", 3) != 0) {
						result = STATE_CRITICAL;
						asprintf(&error_msg, _("invalid response received after authpass, "));
						break;
					}
					break;
				} while (0);
			} else {
				result = STATE_CRITICAL;
				asprintf(&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 > (double) critical_time)
			result = STATE_CRITICAL;
		else if (check_warning_time && elapsed_time > (double) 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;
}
예제 #24
0
int
main (int argc, char **argv)
{
  int result = STATE_UNKNOWN;
  int disk_result = STATE_UNKNOWN;
  char *output;
  char *details;
  char *perf;
  char *preamble;
  double inode_space_pct;
  uintmax_t total, available, available_to_root, used;
  double dfree_pct = -1, dused_pct = -1;
  double dused_units, dfree_units, dtotal_units;
  double dused_inodes_percent, dfree_inodes_percent;
  double warning_high_tide;
  double critical_high_tide;
  int temp_result;

  struct mount_entry *me;
  struct fs_usage fsp, tmpfsp;
  struct parameter_list *temp_list, *path;
  struct name_list *seen = NULL;

  preamble = strdup (" - free space:");
  output = strdup ("");
  details = strdup ("");
  perf = strdup ("");
  stat_buf = malloc(sizeof *stat_buf);

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

  mount_list = read_file_system_list (0);

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

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

  /* If a list of paths has not been selected, find entire
     mount list and create list of paths
   */
  if (path_selected == FALSE) {
    for (me = mount_list; me; me = me->me_next) {
      if (! (path = np_find_parameter(path_select_list, me->me_mountdir))) {
        path = np_add_parameter(&path_select_list, me->me_mountdir);
      }
      path->best_match = me;
      path->group = group;
      set_all_thresholds(path);
    }
  }
  np_set_best_match(path_select_list, mount_list, exact_match);

  /* Error if no match found for specified paths */
  temp_list = path_select_list;

  while (temp_list) {
    if (! temp_list->best_match) {
      die (STATE_CRITICAL, _("DISK %s: %s not found\n"), _("CRITICAL"), temp_list->name);
    }

    temp_list = temp_list->name_next;
  }

  /* Process for every path in list */
  for (path = path_select_list; path; path=path->name_next) {

    if (verbose >= 3 && path->freespace_percent->warning != NULL && path->freespace_percent->critical != NULL)
      printf("Thresholds(pct) for %s warn: %f crit %f\n",path->name, path->freespace_percent->warning->end,
                                                         path->freespace_percent->critical->end);

    if (verbose >= 3 && path->group != NULL)
      printf("Group of %s: %s\n",path->name,path->group);

    /* reset disk result */
    disk_result = STATE_UNKNOWN;

    me = path->best_match;

    /* Filters */

    /* Remove filesystems already seen */
    if (np_seen_name(seen, me->me_mountdir)) {
      continue;
    } else {
      if (path->group != NULL) {
        /* find all group members */
        fsp.fsu_blocksize = 0;
        fsp.fsu_blocks    = 0;
        fsp.fsu_bfree     = 0;
        fsp.fsu_bavail    = 0;
        fsp.fsu_files     = 0;
        fsp.fsu_ffree     = 0;


        for (temp_list = path_select_list; temp_list; temp_list=temp_list->name_next) {
          if (temp_list->group && ! (strcmp(temp_list->group, path->group))) {

            stat_path(path);
            get_fs_usage (temp_list->best_match->me_mountdir, temp_list->best_match->me_devname, &tmpfsp);

            /* possibly differing blocksizes if disks are grouped. Calculating average */
            fsp.fsu_blocksize = (fsp.fsu_blocksize * fsp.fsu_blocks + tmpfsp.fsu_blocksize * tmpfsp.fsu_blocks) / \
                                (fsp.fsu_blocks + tmpfsp.fsu_blocks);  /* Size of a block.  */
            fsp.fsu_blocks    += tmpfsp.fsu_blocks;     /* Total blocks. */
            fsp.fsu_bfree     += tmpfsp.fsu_bfree;      /* Free blocks available to superuser. */
            /* Gnulib workaround - see comment about it a few lines below */
            fsp.fsu_bavail    += (tmpfsp.fsu_bavail > tmpfsp.fsu_bfree ? 0 : tmpfsp.fsu_bavail); /* Free blocks available to non-superuser. */
            fsp.fsu_files     += tmpfsp.fsu_files;      /* Total file nodes. */
            fsp.fsu_ffree     += tmpfsp.fsu_ffree;      /* Free file nodes. */

            if (verbose >= 3)
              printf("Group %s: add %llu blocks (%s) \n", path->group, tmpfsp.fsu_bavail, temp_list->name);
             /* printf("Group %s: add %u blocks (%s)\n", temp_list->name); *//* path->group, tmpfsp.fsu_bavail, temp_list->name); */

            np_add_name(&seen, temp_list->best_match->me_mountdir);
          }
        }
        /* modify devname and mountdir for output */
        me->me_mountdir = me->me_devname = path->group;
      } else
        np_add_name(&seen, me->me_mountdir);
    }

    if (path->group == NULL) {
      /* Skip remote filesystems if we're not interested in them */
      if (me->me_remote && show_local_fs) {
        if (stat_remote_fs)
          stat_path(path);
        continue;
      /* Skip pseudo fs's if we haven't asked for all fs's */
      } else if (me->me_dummy && !show_all_fs) {
        continue;
      /* Skip excluded fstypes */
      } else if (fs_exclude_list && np_find_name (fs_exclude_list, me->me_type)) {
        continue;
      /* Skip excluded fs's */
      } else if (dp_exclude_list &&
               (np_find_name (dp_exclude_list, me->me_devname) ||
                np_find_name (dp_exclude_list, me->me_mountdir))) {
        continue;
      }

      stat_path(path);
      get_fs_usage (me->me_mountdir, me->me_devname, &fsp);
    }

    if (fsp.fsu_blocks && strcmp ("none", me->me_mountdir)) {
      total = fsp.fsu_blocks;
      /* 2007-12-08 - Workaround for Gnulib reporting insanely high available
       * space on BSD (the actual value should be negative but fsp.fsu_bavail
       * is unsigned) */
      available = fsp.fsu_bavail > fsp.fsu_bfree ? 0 : fsp.fsu_bavail;
      available_to_root = fsp.fsu_bfree;
      used = total - available_to_root;

      if (verbose >= 3)
        printf ("For %s, total=%llu, available=%llu, available_to_root=%llu, used=%llu, fsp.fsu_files=%llu, fsp.fsu_ffree=%llu\n",
        me->me_mountdir, total, available, available_to_root, used, fsp.fsu_files, fsp.fsu_ffree);

      dused_pct = calculate_percent( used, used + available );	/* used + available can never be > uintmax */

      dfree_pct = 100 - dused_pct;
      dused_units = used*fsp.fsu_blocksize/mult;
      dfree_units = available*fsp.fsu_blocksize/mult;
      dtotal_units = total*fsp.fsu_blocksize/mult;
      dused_inodes_percent = calculate_percent(fsp.fsu_files - fsp.fsu_ffree, fsp.fsu_files);
      dfree_inodes_percent = 100 - dused_inodes_percent;

      if (verbose >= 3) {
        printf ("For %s, used_pct=%g free_pct=%g used_units=%g free_units=%g total_units=%g used_inodes_pct=%g free_inodes_pct=%g fsp.fsu_blocksize=%llu mult=%llu\n",
          me->me_mountdir, dused_pct, dfree_pct, dused_units, dfree_units, dtotal_units, dused_inodes_percent, dfree_inodes_percent, fsp.fsu_blocksize, mult);
      }

      /* Threshold comparisons */

      temp_result = get_status(dfree_units, path->freespace_units);
      if (verbose >=3) printf("Freespace_units result=%d\n", temp_result);
      disk_result = max_state( disk_result, temp_result );

      temp_result = get_status(dfree_pct, path->freespace_percent);
      if (verbose >=3) printf("Freespace%% result=%d\n", temp_result);
      disk_result = max_state( disk_result, temp_result );

      temp_result = get_status(dused_units, path->usedspace_units);
      if (verbose >=3) printf("Usedspace_units result=%d\n", temp_result);
      disk_result = max_state( disk_result, temp_result );

      temp_result = get_status(dused_pct, path->usedspace_percent);
      if (verbose >=3) printf("Usedspace_percent result=%d\n", temp_result);
      disk_result = max_state( disk_result, temp_result );

      temp_result = get_status(dused_inodes_percent, path->usedinodes_percent);
      if (verbose >=3) printf("Usedinodes_percent result=%d\n", temp_result);
      disk_result = max_state( disk_result, temp_result );

      temp_result = get_status(dfree_inodes_percent, path->freeinodes_percent);
      if (verbose >=3) printf("Freeinodes_percent result=%d\n", temp_result);
      disk_result = max_state( disk_result, temp_result );

      result = max_state(result, disk_result);

      /* What a mess of units. The output shows free space, the perf data shows used space. Yikes!
         Hack here. Trying to get warn/crit levels from freespace_(units|percent) for perf
         data. Assumption that start=0. Roll on new syntax...
      */

      /* *_high_tide must be reinitialized at each run */
      warning_high_tide = UINT_MAX;
      critical_high_tide = UINT_MAX;

      if (path->freespace_units->warning != NULL) {
        warning_high_tide = dtotal_units - path->freespace_units->warning->end;
      }
      if (path->freespace_percent->warning != NULL) {
        warning_high_tide = abs( min( (double) warning_high_tide, (double) (1.0 - path->freespace_percent->warning->end/100)*dtotal_units ));
      }
      if (path->freespace_units->critical != NULL) {
        critical_high_tide = dtotal_units - path->freespace_units->critical->end;
      }
      if (path->freespace_percent->critical != NULL) {
        critical_high_tide = abs( min( (double) critical_high_tide, (double) (1.0 - path->freespace_percent->critical->end/100)*dtotal_units ));
      }

      /* Nb: *_high_tide are unset when == UINT_MAX */
      asprintf (&perf, "%s %s", perf,
                perfdata ((!strcmp(me->me_mountdir, "none") || display_mntp) ? me->me_devname : me->me_mountdir,
                          dused_units, units,
                          (warning_high_tide != UINT_MAX ? TRUE : FALSE), warning_high_tide,
                          (critical_high_tide != UINT_MAX ? TRUE : FALSE), critical_high_tide,
                          TRUE, 0,
                          TRUE, dtotal_units));

      if (disk_result==STATE_OK && erronly && !verbose)
        continue;

      asprintf (&output, "%s %s %.0f %s (%.0f%%",
                output,
                (!strcmp(me->me_mountdir, "none") || display_mntp) ? me->me_devname : me->me_mountdir,
                dfree_units,
                units,
                dfree_pct);
      if (dused_inodes_percent < 0) {
        asprintf(&output, "%s inode=-);", output);
      } else {
        asprintf(&output, "%s inode=%.0f%%);", output, dfree_inodes_percent );
      }

      /* TODO: Need to do a similar debug line
      asprintf (&details, _("%s\n\
%.0f of %.0f %s (%.0f%% inode=%.0f%%) free on %s (type %s mounted on %s) warn:%lu crit:%lu warn%%:%.0f%% crit%%:%.0f%%"),
                details, dfree_units, dtotal_units, units, dfree_pct, inode_space_pct,
                me->me_devname, me->me_type, me->me_mountdir,
                (unsigned long)w_df, (unsigned long)c_df, w_dfp, c_dfp);
      */

    }

  }

  if (verbose >= 2)
    asprintf (&output, "%s%s", output, details);


  printf ("DISK %s%s%s|%s\n", state_text (result), (erronly && result==STATE_OK) ? "" : preamble, output, perf);
  return result;
}
int
main (int argc, char **argv)
{

	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;
}
예제 #26
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];

	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, "%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));
	}

	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 */
			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;
				}
			}

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

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

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

				if (status == STATE_WARNING) {
					printf("SLOW_SLAVE %s: %s\n", _("WARNING"), slaveresult);
					exit(STATE_WARNING);
				} else if (status == STATE_CRITICAL) {
					printf("SLOW_SLAVE %s: %s\n", _("CRITICAL"), slaveresult);
					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\n", result, slaveresult);
	} else {
		printf ("%s\n", result);
	}

	return STATE_OK;
}
예제 #27
0
int
main (int argc, char **argv)
{
	int sd;
	int result = STATE_UNKNOWN;
	time_t conntime;

	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);
	time (&start_time);

	/* try to connect to the host at the given port number */
	if (use_udp) {
		result = my_udp_connect (server_address, server_port, &sd);
	} else {
		result = my_tcp_connect (server_address, server_port, &sd);
	}

	if (result != STATE_OK) {
		if (check_critical_time == TRUE)
			result = STATE_CRITICAL;
		else if (check_warning_time == TRUE)
			result = STATE_WARNING;
		else
			result = STATE_UNKNOWN;
		die (result,
		           _("TIME UNKNOWN - could not connect to server %s, port %d\n"),
		           server_address, server_port);
	}

	if (use_udp) {
		if (send (sd, "", 0, 0) < 0) {
			if (check_critical_time == TRUE)
				result = STATE_CRITICAL;
			else if (check_warning_time == TRUE)
				result = STATE_WARNING;
			else
				result = STATE_UNKNOWN;
			die (result,
			  _("TIME UNKNOWN - could not send UDP request to server %s, port %d\n"),
			  server_address, server_port);
		}
	}

	/* watch for the connection string */
	result = recv (sd, (void *)&raw_server_time, sizeof (raw_server_time), 0);

	/* close the connection */
	close (sd);

	/* reset the alarm */
	time (&end_time);
	alarm (0);

	/* return a WARNING status if we couldn't read any data */
	if (result <= 0) {
		if (check_critical_time == TRUE)
			result = STATE_CRITICAL;
		else if (check_warning_time == TRUE)
			result = STATE_WARNING;
		else
			result = STATE_UNKNOWN;
		die (result,
							 _("TIME UNKNOWN - no data received from server %s, port %d\n"),
							 server_address, server_port);
	}

	result = STATE_OK;

	conntime = (end_time - start_time);
	if (check_critical_time == TRUE && conntime > critical_time)
		result = STATE_CRITICAL;
	else if (check_warning_time == TRUE && conntime > warning_time)
		result = STATE_WARNING;

	if (result != STATE_OK)
		die (result, _("TIME %s - %d second response time|%s\n"),
		     state_text (result), (int)conntime,
		     perfdata ("time", (long)conntime, "s",
		               check_warning_time, (long)warning_time,
		               check_critical_time, (long)critical_time,
		               TRUE, 0, FALSE, 0));

	server_time = ntohl (raw_server_time) - UNIX_EPOCH;
	if (server_time > (unsigned long)end_time)
		diff_time = server_time - (unsigned long)end_time;
	else
		diff_time = (unsigned long)end_time - server_time;

	if (check_critical_diff == TRUE && diff_time > critical_diff)
		result = STATE_CRITICAL;
	else if (check_warning_diff == TRUE && diff_time > warning_diff)
		result = STATE_WARNING;

	printf (_("TIME %s - %lu second time difference|%s %s\n"),
	        state_text (result), diff_time,
	        perfdata ("time", (long)conntime, "s",
	                  check_warning_time, (long)warning_time,
	                  check_critical_time, (long)critical_time,
	                  TRUE, 0, FALSE, 0),
	        perfdata ("offset", diff_time, "s",
	                  check_warning_diff, warning_diff,
	                  check_critical_diff, critical_diff,
	                  TRUE, 0, FALSE, 0));
	return result;
}
예제 #28
0
int main(int argc, char **argv){
	char *ptr;
	int data_val;
	int return_code=STATE_OK;
	thresholds *thresholds = NULL;

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

	/* Initialize the thresholds */
	set_thresholds(&thresholds, warn_threshold, crit_threshold);
	if(verbose)
		print_thresholds("check_cluster", thresholds);

	/* check the data values */
	for(ptr=strtok(data_vals,",");ptr!=NULL;ptr=strtok(NULL,",")){

		data_val=atoi(ptr);

		if(check_type==CHECK_SERVICES){
			switch(data_val){
			case 0:
				total_services_ok++;
				break;
			case 1:
				total_services_warning++;
				break;
			case 2:
				total_services_critical++;
				break;
			case 3:
				total_services_unknown++;
				break;
			default:
				break;
		        }
	        }
		else{
			switch(data_val){
			case 0:
				total_hosts_up++;
				break;
			case 1:
				total_hosts_down++;
				break;
			case 2:
				total_hosts_unreachable++;
				break;
			default:
				break;
		        }
	        }
        }


	/* return the status of the cluster */
	if(check_type==CHECK_SERVICES){
		return_code=get_status(total_services_warning+total_services_unknown+total_services_critical, thresholds);
		printf("CLUSTER %s: %s: %d ok, %d warning, %d unknown, %d critical\n",
			state_text(return_code), (label==NULL)?"Service cluster":label,
			total_services_ok,total_services_warning,
			total_services_unknown,total_services_critical);
	}
	else{
		return_code=get_status(total_hosts_down+total_hosts_unreachable, thresholds);
		printf("CLUSTER %s: %s: %d up, %d down, %d unreachable\n",
			state_text(return_code), (label==NULL)?"Host cluster":label,
			total_hosts_up,total_hosts_down,total_hosts_unreachable);
	}

	return return_code;
}
예제 #29
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;
}
예제 #30
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;
}