int get_prefs(void)
{
    HKEY hKey;
    LONG result;
    CHAR keypath[MAX_PATH];
    int got_any_p = 0;

    if (text_mode == NULL || *text_mode == '\0')
    {
        saver_name = get_saver_name();
        if (saver_name && *saver_name)
        {
            if (verbose)
                fprintf(stderr, "%s: saver:   %s\n", saver_name);

            sprintf(keypath, saver_key, saver_name);
            result = RegOpenKeyExA(HKEY_CURRENT_USER, keypath, 0, KEY_READ, &hKey);
            if (result == ERROR_SUCCESS)
            {
                got_any_p = load_values(hKey);
                RegCloseKey(hKey);
            }
        }
    }

    if (verbose > 1)
    {
        fprintf(stderr, "%s: mode:    %s\n", text_mode);
        fprintf(stderr, "%s: literal: %s\n", text_literal);
        fprintf(stderr, "%s: file:    %s\n", text_file);
        fprintf(stderr, "%s: program: %s\n", text_program);
    }

    _strlwr(text_mode);
    text_literal = _strdup(text_literal);
    escape_newlines(text_literal);

    return got_any_p;
}
Пример #2
0
void display_notifications(void) {
	char *temp_buffer;
	char *error_text = NULL;
	char date_time[MAX_DATETIME_LENGTH];
	char alert_level[MAX_INPUT_BUFFER];
	char alert_level_class[MAX_INPUT_BUFFER];
	char contact_name[MAX_INPUT_BUFFER];
	char service_name[MAX_INPUT_BUFFER];
	char host_name[MAX_INPUT_BUFFER];
	char method_name[MAX_INPUT_BUFFER];
	char displayed_host_name[MAX_INPUT_BUFFER];
	char displayed_service_desc[MAX_INPUT_BUFFER];
	int show_entry;
	int total_notifications = 0;
	int displayed_entries = 0;
	int notification_detail_type = NOTIFICATION_SERVICE_CRITICAL;
	int status = READLOG_OK;
	int odd = 0;
	int json_start = TRUE;
	host *temp_host = NULL;
	service *temp_service = NULL;
	hostgroup *temp_hostgroup = NULL;
	servicegroup *temp_servicegroup = NULL;
	logentry *temp_entry = NULL;
	logentry *entry_list = NULL;
	logfilter *filter_list = NULL;

	if (query_type == DISPLAY_HOSTGROUPS) {

		temp_hostgroup = find_hostgroup(query_hostgroup_name);

		if (temp_hostgroup == NULL) {
			print_generic_error_message("There are no host groups with this name defined.", NULL, 0);
			return;
		}
		/* make sure the user is authorized to view this hostgroup */
		if (show_partial_hostgroups == FALSE && is_authorized_for_hostgroup(temp_hostgroup, &current_authdata) == FALSE) {
			print_generic_error_message("It appears as though you do not have permission to view information for the host group you requested...", "If you believe this is an error, check the HTTP server authentication requirements for accessing this CGI and check the authorization options in your CGI configuration file.", 0);
			return;
		}
	}

	if (query_type == DISPLAY_SERVICEGROUPS) {

		temp_servicegroup = find_servicegroup(query_servicegroup_name);

		if (temp_servicegroup == NULL) {
			print_generic_error_message("There are no service groups with this name defined.", NULL, 0);
			return;
		}
		/* make sure the user is authorized to view this servicegroup */
		if (show_partial_servicegroups == FALSE && is_authorized_for_servicegroup(temp_servicegroup, &current_authdata) == FALSE) {
			print_generic_error_message("It appears as though you do not have permission to view information for the service group you requested...", "If you believe this is an error, check the HTTP server authentication requirements for accessing this CGI and check the authorization options in your CGI configuration file.", 0);
			return;
		}
	}

	add_log_filter(&filter_list, LOGENTRY_HOST_NOTIFICATION, LOGFILTER_INCLUDE);
	add_log_filter(&filter_list, LOGENTRY_SERVICE_NOTIFICATION, LOGFILTER_INCLUDE);

	/* scan the log file for notification data */
	status = get_log_entries(&entry_list, &filter_list, &error_text, NULL, reverse, ts_start, ts_end);

	free_log_filters(&filter_list);

	/* dealing with errors */
	if (status == READLOG_ERROR_WARNING) {
		if (error_text != NULL) {
			print_generic_error_message(error_text, NULL, 0);
			my_free(error_text);
		} else
			print_generic_error_message("Unkown error!", NULL, 0);
	}

	if (status == READLOG_ERROR_MEMORY)
			print_generic_error_message("Out of memory...", "showing all I could get!", 0);

	if (status == READLOG_ERROR_FATAL) {
		if (error_text != NULL) {
			print_generic_error_message(error_text, NULL, 0);
			my_free(error_text);
		}

		return;

	/* now we start displaying the notification entries */
	} else {
		if (content_type == JSON_CONTENT) {
			if (status != READLOG_OK)
				printf(",\n");
			printf("\"notifications\": [\n");
		} else if (content_type == CSV_CONTENT) {
			printf("%sHOST%s%s", csv_data_enclosure, csv_data_enclosure, csv_delimiter);
			printf("%sSERVICE%s%s", csv_data_enclosure, csv_data_enclosure, csv_delimiter);
			printf("%sTYPE%s%s", csv_data_enclosure, csv_data_enclosure, csv_delimiter);
			printf("%sTIME%s%s", csv_data_enclosure, csv_data_enclosure, csv_delimiter);
			printf("%sCONTACT%s%s", csv_data_enclosure, csv_data_enclosure, csv_delimiter);
			printf("%sNOTIFICATION_COMMAND%s%s", csv_data_enclosure, csv_data_enclosure, csv_delimiter);
			printf("%sINFORMATION%s\n", csv_data_enclosure, csv_data_enclosure);
		} else {
			printf("<table border='0' class='notifications' align='center'>\n");

			/* add export to csv, json, link */
			printf("<tr><td colspan='7'>");
			printf("<table width='100%%' cellspacing='0' cellpadding='0'><tr><td width='33%%'></td><td width='33%%' nowrap>");
			printf("<div class='page_selector'>\n");
			printf("<div id='page_navigation_copy'></div>");
			page_limit_selector(result_start);
			printf("</div>\n");
			printf("</td><td width='33%%' align='right' style='padding-right:2px'>\n");
			printf("<div class='csv_export_link'>");
			print_export_link(CSV_CONTENT, NOTIFICATIONS_CGI, NULL);
			print_export_link(JSON_CONTENT, NOTIFICATIONS_CGI, NULL);
			print_export_link(HTML_CONTENT, NOTIFICATIONS_CGI, NULL);
			printf("</div></td></tr></table>");

			printf("<tr>\n");
			printf("<th class='notifications'>Host</th>\n");
			printf("<th class='notifications'>Service</th>\n");
			printf("<th class='notifications'>Type</th>\n");
			printf("<th class='notifications'>Time</th>\n");
			printf("<th class='notifications'>Contact</th>\n");
			printf("<th class='notifications'>Notification Command</th>\n");
			printf("<th class='notifications'>Information</th>\n");
			printf("</tr>\n");
		}

		/* check all entries */
		for (temp_entry = entry_list; temp_entry != NULL; temp_entry = temp_entry->next) {

			/* get the date/time */
			get_time_string(&temp_entry->timestamp, date_time, (int)sizeof(date_time), SHORT_DATE_TIME);
			strip(date_time);

			/* get the contact name */
			temp_buffer = (char *)strtok(temp_entry->entry_text, ":");
			temp_buffer = (char *)strtok(NULL, ";");
			snprintf(contact_name, sizeof(contact_name), "%s", (temp_buffer == NULL) ? "" : temp_buffer + 1);
			contact_name[sizeof(contact_name) - 1] = '\x0';

			/* get the host name */
			temp_buffer = (char *)strtok(NULL, ";");
			snprintf(host_name, sizeof(host_name), "%s", (temp_buffer == NULL) ? "" : temp_buffer);
			host_name[sizeof(host_name) - 1] = '\x0';

			/* get the service name */
			service_name[0] = '\x0';
			if (temp_entry->type == LOGENTRY_SERVICE_NOTIFICATION) {
				temp_buffer = (char *)strtok(NULL, ";");
				snprintf(service_name, sizeof(service_name), "%s", (temp_buffer == NULL) ? "" : temp_buffer);
				service_name[sizeof(service_name) - 1] = '\x0';
			}

			/* get the alert level */
			temp_buffer = (char *)strtok(NULL, ";");
			snprintf(alert_level, sizeof(alert_level), "%s", (temp_buffer == NULL) ? "" : temp_buffer);
			alert_level[sizeof(alert_level) - 1] = '\x0';

			if (temp_entry->type == LOGENTRY_SERVICE_NOTIFICATION) {

				if (!strcmp(alert_level, "CRITICAL")) {
					notification_detail_type = NOTIFICATION_SERVICE_CRITICAL;
					strcpy(alert_level_class, "CRITICAL");
				} else if (!strcmp(alert_level, "WARNING")) {
					notification_detail_type = NOTIFICATION_SERVICE_WARNING;
					strcpy(alert_level_class, "WARNING");
				} else if (!strcmp(alert_level, "RECOVERY") || !strcmp(alert_level, "OK")) {
					strcpy(alert_level, "OK");
					notification_detail_type = NOTIFICATION_SERVICE_RECOVERY;
					strcpy(alert_level_class, "OK");
				} else if (strstr(alert_level, "CUSTOM (")) {
					notification_detail_type = NOTIFICATION_SERVICE_CUSTOM;
					strcpy(alert_level_class, "CUSTOM");
				} else if (strstr(alert_level, "ACKNOWLEDGEMENT (")) {
					notification_detail_type = NOTIFICATION_SERVICE_ACK;
					strcpy(alert_level_class, "ACKNOWLEDGEMENT");
				} else if (strstr(alert_level, "FLAPPINGSTART (")) {
					strcpy(alert_level, "FLAPPING START");
					notification_detail_type = NOTIFICATION_SERVICE_FLAP;
					strcpy(alert_level_class, "UNKNOWN");
				} else if (strstr(alert_level, "FLAPPINGSTOP (")) {
					strcpy(alert_level, "FLAPPING STOP");
					notification_detail_type = NOTIFICATION_SERVICE_FLAP;
					strcpy(alert_level_class, "UNKNOWN");
				} else {
					strcpy(alert_level, "UNKNOWN");
					notification_detail_type = NOTIFICATION_SERVICE_UNKNOWN;
					strcpy(alert_level_class, "UNKNOWN");
				}
			} else {

				if (!strcmp(alert_level, "DOWN")) {
					strncpy(alert_level, "HOST DOWN", sizeof(alert_level));
					strcpy(alert_level_class, "HOSTDOWN");
					notification_detail_type = NOTIFICATION_HOST_DOWN;
				} else if (!strcmp(alert_level, "UNREACHABLE")) {
					strncpy(alert_level, "HOST UNREACHABLE", sizeof(alert_level));
					strcpy(alert_level_class, "HOSTUNREACHABLE");
					notification_detail_type = NOTIFICATION_HOST_UNREACHABLE;
				} else if (!strcmp(alert_level, "RECOVERY") || !strcmp(alert_level, "UP")) {
					strncpy(alert_level, "HOST UP", sizeof(alert_level));
					strcpy(alert_level_class, "HOSTUP");
					notification_detail_type = NOTIFICATION_HOST_RECOVERY;
				} else if (strstr(alert_level, "CUSTOM (")) {
					strcpy(alert_level_class, "HOSTCUSTOM");
					notification_detail_type = NOTIFICATION_HOST_CUSTOM;
				} else if (strstr(alert_level, "ACKNOWLEDGEMENT (")) {
					strcpy(alert_level_class, "HOSTACKNOWLEDGEMENT");
					notification_detail_type = NOTIFICATION_HOST_ACK;
				} else if (strstr(alert_level, "FLAPPINGSTART (")) {
					strcpy(alert_level, "FLAPPING START");
					strcpy(alert_level_class, "UNKNOWN");
					notification_detail_type = NOTIFICATION_HOST_FLAP;
				} else if (strstr(alert_level, "FLAPPINGSTOP (")) {
					strcpy(alert_level, "FLAPPING STOP");
					strcpy(alert_level_class, "UNKNOWN");
					notification_detail_type = NOTIFICATION_HOST_FLAP;
				}
			}

			/* get the method name */
			temp_buffer = (char *)strtok(NULL, ";");
			snprintf(method_name, sizeof(method_name), "%s", (temp_buffer == NULL) ? "" : temp_buffer);
			method_name[sizeof(method_name) - 1] = '\x0';

			/* move to the informational message */
			temp_buffer = strtok(NULL, ";");

			show_entry = FALSE;

			/* if we're searching by contact, filter out unwanted contact */
			if (query_type == DISPLAY_CONTACTS) {
				if (find_all == TRUE)
					show_entry = TRUE;
				else if (!strcmp(query_contact_name, contact_name))
					show_entry = TRUE;
			}

			/* search host */
			else if (query_type == DISPLAY_HOSTS) {
				if (find_all == TRUE)
					show_entry = TRUE;
				else if (!strcmp(query_host_name, host_name))
					show_entry = TRUE;
			}

			/* searching service */
			else if (query_type == DISPLAY_SERVICES) {
				if (!strcmp(query_host_name, host_name) && !strcmp(query_svc_description, service_name))
					show_entry = TRUE;
			}

			/* Set TRUE here, get's checked later on */
			else if (query_type == DISPLAY_HOSTGROUPS || query_type == DISPLAY_SERVICEGROUPS) {
				show_entry = TRUE;
			}

			if (show_entry == TRUE) {
				if (notification_options == NOTIFICATION_ALL)
					show_entry = TRUE;
				else if (notification_options == NOTIFICATION_HOST_ALL && temp_entry->type == LOGENTRY_HOST_NOTIFICATION)
					show_entry = TRUE;
				else if (notification_options == NOTIFICATION_SERVICE_ALL && temp_entry->type == LOGENTRY_SERVICE_NOTIFICATION)
					show_entry = TRUE;
				else if (notification_detail_type & notification_options)
					show_entry = TRUE;
				else
					show_entry = FALSE;
			}

			/* make sure user has authorization to view this notification */
			temp_host = find_host(host_name);
			if (temp_entry->type == LOGENTRY_SERVICE_NOTIFICATION)
				temp_service = find_service(host_name, service_name);

			if (temp_host != NULL) {
				snprintf(displayed_host_name, sizeof(displayed_host_name), "%s", (temp_host->display_name != NULL && content_type == HTML_CONTENT) ? temp_host->display_name : temp_host->name);
				displayed_host_name[sizeof(displayed_host_name) - 1] = '\x0';

				if (temp_entry->type == LOGENTRY_HOST_NOTIFICATION) {
					if (is_authorized_for_host(temp_host, &current_authdata) == FALSE)
						show_entry = FALSE;
					else if (query_type == DISPLAY_HOSTGROUPS && is_host_member_of_hostgroup(temp_hostgroup, temp_host) == FALSE)
						show_entry = FALSE;
					else if (query_type == DISPLAY_SERVICEGROUPS && is_host_member_of_servicegroup(temp_servicegroup, temp_host) == FALSE)
						show_entry = FALSE;
				} else {
					if (temp_service != NULL) {
						snprintf(displayed_service_desc, sizeof(displayed_service_desc), "%s", (temp_service->display_name != NULL && content_type == HTML_CONTENT) ? temp_service->display_name : temp_service->description);
						displayed_service_desc[sizeof(displayed_service_desc) - 1] = '\x0';

						if (is_authorized_for_service(temp_service, &current_authdata) == FALSE)
							show_entry = FALSE;
						else if (query_type == DISPLAY_HOSTGROUPS && is_host_member_of_hostgroup(temp_hostgroup, temp_host) == FALSE)
							show_entry = FALSE;
						else if (query_type == DISPLAY_SERVICEGROUPS && is_service_member_of_servicegroup(temp_servicegroup, temp_service) == FALSE)
							show_entry = FALSE;
					} else {
						if (is_authorized_for_all_services(&current_authdata) == FALSE)
							show_entry = FALSE;

						snprintf(displayed_service_desc, sizeof(displayed_service_desc), "%s", service_name);
						displayed_service_desc[sizeof(displayed_service_desc) - 1] = '\x0';
					}
				}
			} else {
				if (temp_entry->type == LOGENTRY_HOST_NOTIFICATION) {
					if (is_authorized_for_all_hosts(&current_authdata) == FALSE)
						show_entry = FALSE;
				} else {
					if (is_authorized_for_all_services(&current_authdata) == FALSE)
						show_entry = FALSE;

					snprintf(displayed_service_desc, sizeof(displayed_service_desc), "%s", service_name);
					displayed_service_desc[sizeof(displayed_service_desc) - 1] = '\x0';
				}

				snprintf(displayed_host_name, sizeof(displayed_host_name), "%s", host_name);
				displayed_host_name[sizeof(displayed_host_name) - 1] = '\x0';
			}

			if (show_entry == TRUE) {

				if (result_limit != 0  && (((total_notifications + 1) < result_start) || (total_notifications >= ((result_start + result_limit) - 1)))) {
					total_notifications++;
					continue;
				}

				displayed_entries++;
				total_notifications++;

				if (odd)
					odd = 0;
				else
					odd = 1;

				if (content_type == JSON_CONTENT) {
					if (json_start == FALSE)
						printf(",\n");
					printf("{\"host_name\": \"%s\", ", json_encode(temp_host->name));
					printf("\"host_display_name\": \"%s\", ", (temp_host->display_name != NULL) ? json_encode(temp_host->display_name) : json_encode(temp_host->name));
					if (temp_entry->type == LOGENTRY_SERVICE_NOTIFICATION) {
						printf("\"service_description\": \"%s\", ", json_encode(temp_service->description));
						printf("\"service_display_name\": \"%s\", ", (temp_service->display_name != NULL) ? json_encode(temp_service->display_name) : json_encode(temp_service->description));
					} else {
						printf("\"service_description\": null, ");
						printf("\"service_display_name\": null, ");
					}
					printf("\"type\": \"%s\", ", alert_level);
					printf("\"time\": \"%s\", ", date_time);
					printf("\"contact\": \"%s\", ", json_encode(contact_name));
					printf("\"notification_command\": \"%s\", ", json_encode(method_name));
					printf("\"information\": \"%s\"}", json_encode(escape_newlines(temp_buffer)));
				} else if (content_type == CSV_CONTENT) {
					printf("%s%s%s%s", csv_data_enclosure, displayed_host_name, csv_data_enclosure, csv_delimiter);
					if (temp_entry->type == LOGENTRY_SERVICE_NOTIFICATION)
						printf("%s%s%s%s", csv_data_enclosure, displayed_service_desc, csv_data_enclosure, csv_delimiter);
					else
						printf("%sN/A%s%s", csv_data_enclosure, csv_data_enclosure, csv_delimiter);
					printf("%s%s%s%s", csv_data_enclosure, alert_level, csv_data_enclosure, csv_delimiter);
					printf("%s%s%s%s", csv_data_enclosure, date_time, csv_data_enclosure, csv_delimiter);
					printf("%s%s%s%s", csv_data_enclosure, contact_name, csv_data_enclosure, csv_delimiter);
					printf("%s%s%s%s", csv_data_enclosure, method_name, csv_data_enclosure, csv_delimiter);
					printf("%s%s%s\n", csv_data_enclosure, escape_newlines(temp_buffer), csv_data_enclosure);
				} else {
					printf("<tr class='notifications%s'>\n", (odd) ? "Even" : "Odd");
					if (temp_host != NULL)
						printf("<td class='notifications%s'><a href='%s?type=%d&amp;host=%s'>%s</a></td>\n", (odd) ? "Even" : "Odd", EXTINFO_CGI, DISPLAY_HOST_INFO, url_encode(host_name), displayed_host_name);
					else
						printf("<td class='notifications%s'>%s</td>\n", (odd) ? "Even" : "Odd", displayed_host_name);
					if (temp_entry->type == LOGENTRY_SERVICE_NOTIFICATION) {
						if (temp_service != NULL) {
							printf("<td class='notifications%s'><a href='%s?type=%d&amp;host=%s", (odd) ? "Even" : "Odd", EXTINFO_CGI, DISPLAY_SERVICE_INFO, url_encode(host_name));
							printf("&amp;service=%s'>%s</a></td>\n", url_encode(service_name), displayed_service_desc);
						} else
							printf("<td class='notifications%s'>%s</td>\n", (odd) ? "Even" : "Odd", displayed_service_desc);

					} else
						printf("<td class='notifications%s'>N/A</td>\n", (odd) ? "Even" : "Odd");
					printf("<td class='notifications%s'>%s</td>\n", alert_level_class, alert_level);
					printf("<td class='notifications%s'>%s</td>\n", (odd) ? "Even" : "Odd", date_time);
					printf("<td class='notifications%s'><a href='%s?type=contacts#%s'>%s</a></td>\n", (odd) ? "Even" : "Odd", CONFIG_CGI, url_encode(contact_name), contact_name);
					printf("<td class='notifications%s'><a href='%s?type=commands#%s'>%s</a></td>\n", (odd) ? "Even" : "Odd", CONFIG_CGI, url_encode(method_name), method_name);
					printf("<td class='notifications%s'>%s</td>\n", (odd) ? "Even" : "Odd", html_encode(temp_buffer, FALSE));
					printf("</tr>\n");
				}
				if (json_start == TRUE)
					json_start = FALSE;
			}
		}
	}

	free_log_entries(&entry_list);

	if (content_type != CSV_CONTENT && content_type != JSON_CONTENT) {
		printf("</table>\n");

		if (total_notifications == 0) {
			printf("<div class='errorMessage' style='text-align:center;'>No notifications have been recorded");
			if (find_all == FALSE) {
				if (query_type == DISPLAY_SERVICES)
					printf(" for this service");
				else if (query_type == DISPLAY_CONTACTS)
					printf(" for this contact");
				else
					printf(" for this host");
			}
			printf(" in log files for selected date.</div>");
		}

		page_num_selector(result_start, total_notifications, displayed_entries);

	} else if (content_type == JSON_CONTENT) {
		printf("\n]\n");
	}

	return;
}
Пример #3
0
/* OS_CustomLog: v0.1, 2012/10/10*/
void OS_CustomLog(Eventinfo *lf,char* format)
{
  char *log;
  char *tmp_log;
  char tmp_buffer[1024];
  //Replace all the tokens:
  os_strdup(format,log);

  snprintf(tmp_buffer, 1024, "%d", lf->time);
  tmp_log = searchAndReplace(log, CustomAlertTokenName[CUSTOM_ALERT_TOKEN_TIMESTAMP], tmp_buffer);
  if(log)
  {
    os_free(log);
    log=NULL;
  }
  snprintf(tmp_buffer, 1024, "%ld", __crt_ftell);
  log = searchAndReplace(tmp_log, CustomAlertTokenName[CUSTOM_ALERT_TOKEN_FTELL], tmp_buffer);
  if (tmp_log)
  {
    os_free(tmp_log);
    tmp_log=NULL;
  }


  snprintf(tmp_buffer, 1024, "%s", (lf->generated_rule->alert_opts & DO_MAILALERT)?"mail " : "");
  tmp_log = searchAndReplace(log, CustomAlertTokenName[CUSTOM_ALERT_TOKEN_RULE_ALERT_OPTIONS], tmp_buffer);
  if(log)
  {
    os_free(log);
    log=NULL;
  }


  snprintf(tmp_buffer, 1024, "%s",lf->hostname?lf->hostname:"None");
  log = searchAndReplace(tmp_log, CustomAlertTokenName[CUSTOM_ALERT_TOKEN_HOSTNAME], tmp_buffer);
  if (tmp_log)
  {
    os_free(tmp_log);
    tmp_log=NULL;
  }

  snprintf(tmp_buffer, 1024, "%s",lf->location?lf->location:"None");
  tmp_log = searchAndReplace(log, CustomAlertTokenName[CUSTOM_ALERT_TOKEN_LOCATION], tmp_buffer);
  if(log)
  {
    os_free(log);
    log=NULL;
  }


  snprintf(tmp_buffer, 1024, "%d", lf->generated_rule->sigid);
  log = searchAndReplace(tmp_log, CustomAlertTokenName[CUSTOM_ALERT_TOKEN_RULE_ID], tmp_buffer);
  if (tmp_log)
  {
    os_free(tmp_log);
    tmp_log=NULL;
  }

  snprintf(tmp_buffer, 1024, "%d", lf->generated_rule->level);
  tmp_log = searchAndReplace(log, CustomAlertTokenName[CUSTOM_ALERT_TOKEN_RULE_LEVEL], tmp_buffer);
  if(log)
  {
    os_free(log);
    log=NULL;
  }

  snprintf(tmp_buffer, 1024, "%s",lf->srcip?lf->srcip:"None");
  log = searchAndReplace(tmp_log, CustomAlertTokenName[CUSTOM_ALERT_TOKEN_SRC_IP], tmp_buffer);
  if (tmp_log)
  {
    os_free(tmp_log);
    tmp_log=NULL;
  }

  snprintf(tmp_buffer, 1024, "%s",lf->srcuser?lf->srcuser:"******");

  tmp_log = searchAndReplace(log, CustomAlertTokenName[CUSTOM_ALERT_TOKEN_DST_USER], tmp_buffer);
  if(log)
  {
    os_free(log);
    log=NULL;
  }
  char * escaped_log;
  escaped_log = escape_newlines(lf->full_log);

  log = searchAndReplace(tmp_log, CustomAlertTokenName[CUSTOM_ALERT_TOKEN_FULL_LOG],escaped_log );
  if (tmp_log)
  {
    os_free(tmp_log);
    tmp_log=NULL;
  }

  if(escaped_log)
  {
    os_free(escaped_log);
    escaped_log=NULL;
  }

  snprintf(tmp_buffer, 1024, "%s",lf->generated_rule->comment?lf->generated_rule->comment:"");
  tmp_log = searchAndReplace(log, CustomAlertTokenName[CUSTOM_ALERT_TOKEN_RULE_COMMENT], tmp_buffer);
  if(log)
  {
    os_free(log);
    log=NULL;
  }

  snprintf(tmp_buffer, 1024, "%s",lf->generated_rule->group?lf->generated_rule->group:"");
  log = searchAndReplace(tmp_log, CustomAlertTokenName[CUSTOM_ALERT_TOKEN_RULE_GROUP], tmp_buffer);
  if (tmp_log)
  {
    os_free(tmp_log);
    tmp_log=NULL;
  }


  fprintf(_aflog,log);
  fprintf(_aflog,"\n");
  fflush(_aflog);

  if(log)
  {
    os_free(log);
    log=NULL;
  }

  return;
}
Пример #4
0
int main(int argc, char **argv) {
	int sd;
	int rc;
	int result;
	data_packet send_packet;
	int bytes_to_send;
	char input[MAX_INPUT_BUFFER];
	char input_buffer[MAX_INPUT_BUFFER];
	char *temp_ptr;
	char host_name[MAX_HOSTNAME_LENGTH];
	char svc_description[MAX_DESCRIPTION_LENGTH];
	char plugin_output[MAX_PLUGINOUTPUT_LENGTH];
	int total_packets = 0;
	int16_t return_code;
	u_int32_t calculated_crc32;
	char *inputptr, *ptr1, *ptr2, *ptr3, *ptr4;


	/* process command-line arguments */
	result = process_arguments(argc, argv);

	if (result != OK || show_help == TRUE || show_license == TRUE || show_version == TRUE) {

		if (result != OK)
			printf("Incorrect command line arguments supplied\n");
		printf("\n");
		printf("NSCA Client %s\n", PROGRAM_VERSION);
		printf("Copyright (c) 2010-2012 Icinga Development Team and Community Contributors (http://www.icinga.org)\n");
		printf("Copyright (c) 2000-2007 Ethan Galstad (www.nagios.org)\n");
		printf("Last Modified: %s\n", MODIFICATION_DATE);
		printf("License: GPL v2\n");
		printf("Encryption Routines: ");
#ifdef HAVE_LIBMCRYPT
		printf("AVAILABLE");
#else
		printf("NOT AVAILABLE");
#endif
		printf("\n");
		printf("\n");
	}

	if (result != OK || show_help == TRUE) {
		printf("Usage: %s -H <host_address> [-p port] [-to to_sec] [-d delim] [-c config_file]\n", argv[0]);
		printf("\n");
		printf("Options:\n");
		printf(" <host_address> = The IP address of the host running the NSCA daemon\n");
		printf(" [port]         = The port on which the daemon is running - default is %s\n", DEFAULT_SERVER_PORT);
		printf(" [to_sec]       = Number of seconds before connection attempt times out.\n");
		printf("                  (default timeout is %d seconds)\n", DEFAULT_SOCKET_TIMEOUT);
		printf(" [delim]        = Delimiter to use when parsing input (defaults to a tab)\n");
		printf(" [config_file]  = Name of config file to use\n");
		printf("\n");
		printf("Note:\n");
		printf("This utility is used to send passive check results to the NSCA daemon.  Host and\n");
		printf("Service check data that is to be sent to the NSCA daemon is read from standard\n");
		printf("input. Input should be provided in the following format (tab-delimited unless\n");
		printf("overriden with -d command line argument, one entry per line):\n");
		printf("\n");
		printf("Service Checks:\n");
		printf("<host_name>[tab]<svc_description>[tab]<return_code>[tab]<plugin_output>[newline]\n\n");
		printf("Host Checks:\n");
		printf("<host_name>[tab]<return_code>[tab]<plugin_output>[newline]\n\n");
		printf("When submitting multiple simultaneous results, separate each set with the ETB\n");
		printf("character (^W or 0x17)\n");
		printf("\n");
	}

	if (show_license == TRUE)
		display_license();

	if (result != OK || show_help == TRUE || show_license == TRUE || show_version == TRUE)
		do_exit(STATE_UNKNOWN);



	/* read the config file */
	result = read_config_file(config_file);

	/* exit if there are errors... */
	if (result == ERROR) {
		printf("Error: Config file '%s' contained errors...\n", config_file);
		do_exit(STATE_CRITICAL);
	}

	/* generate the CRC 32 table */
	generate_crc32_table();

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

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

	time(&start_time);

	/* try to connect to the host at the given port number */
	result = my_tcp_connect(server_name, server_port, &sd);

	/* we couldn't connect */
	if (result != STATE_OK) {
		printf("Error: Could not connect to host %s on port %s\n", server_name, server_port);
		do_exit(STATE_CRITICAL);
	}

#ifdef DEBUG
	printf("Connected okay...\n");
#endif

	/* read the initialization packet containing the IV and timestamp */
	result = read_init_packet(sd);
	if (result != OK) {
		printf("Error: Could not read init packet from server\n");
		close(sd);
		do_exit(STATE_CRITICAL);
	}

#ifdef DEBUG
	printf("Got init packet from server\n");
#endif

	/* initialize encryption/decryption routines with the IV we received from the server */
	if (encrypt_init(password, encryption_method, received_iv, &CI) != OK) {
		printf("Error: Failed to initialize encryption libraries for method %d\n", encryption_method);
		close(sd);
		do_exit(STATE_CRITICAL);
	}

#ifdef DEBUG
	printf("Initialized encryption routines\n");
#endif


	/**** WE'RE CONNECTED AND READY TO SEND ****/

	/* read all data from STDIN until there isn't anymore */
	while (!feof(stdin)) {
		int c = getc(stdin);
		if (c == -1) {
			break;
		}
		int pos = 0;
		while (c != 23) {
			if (c == -1) { // in case we don't terminate properly, or are in single-input mode.
				break;
			}
			input_buffer[pos] = c;
			c = getc(stdin);
			pos++;
		}
		input_buffer[pos] = 0;

		strip(input_buffer);

		if (!strcmp(input_buffer, ""))
			continue;

		/* get the host name */
		ptr1 = strtok(input_buffer, delimiter);
		if (ptr1 == NULL)
			continue;

		/* get the service description or return code */
		ptr2 = strtok(NULL, delimiter);
		if (ptr2 == NULL)
			continue;

		/* get the return code or plugin output */
		ptr3 = strtok(NULL, delimiter);
		if (ptr3 == NULL)
			continue;

		/* get the plugin output - if NULL, this is a host check result */
		ptr4 = strtok(NULL, "\x0");

		strncpy(host_name, ptr1, sizeof(host_name) - 1);
		host_name[sizeof(host_name) - 1] = '\x0';
		if (ptr4 == NULL) {
			strcpy(svc_description, "");
			return_code = atoi(ptr2);
			ptr3 = escape_newlines(ptr3);
			strncpy(plugin_output, ptr3, sizeof(plugin_output) - 1);
		} else {
			strncpy(svc_description, ptr2, sizeof(svc_description) - 1);
			return_code = atoi(ptr3);
			ptr4 = escape_newlines(ptr4);
			strncpy(plugin_output, ptr4, sizeof(plugin_output) - 1);
		}
		svc_description[sizeof(svc_description) - 1] = '\x0';
		plugin_output[sizeof(plugin_output) - 1] = '\x0';

		/* increment count of packets we're sending */
		total_packets++;

		/* clear the packet buffer */
		bzero(&send_packet, sizeof(send_packet));

		/* fill the packet with semi-random data */
		randomize_buffer((char *)&send_packet, sizeof(send_packet));

		/* copy the data we want to send into the packet */
		send_packet.packet_version = (int16_t)htons(NSCA_PACKET_VERSION_3);
		send_packet.return_code = (int16_t)htons(return_code);
		strcpy(&send_packet.host_name[0], host_name);
		strcpy(&send_packet.svc_description[0], svc_description);
		strcpy(&send_packet.plugin_output[0], plugin_output);

		/* use timestamp provided by the server */
		send_packet.timestamp = (u_int32_t)htonl(packet_timestamp);

		/* calculate the crc 32 value of the packet */
		send_packet.crc32_value = (u_int32_t)0L;
		calculated_crc32 = calculate_crc32((char *)&send_packet, sizeof(send_packet));
		send_packet.crc32_value = (u_int32_t)htonl(calculated_crc32);

		/* encrypt the packet */
		encrypt_buffer((char *)&send_packet, sizeof(send_packet), password, encryption_method, CI);

		/* send the packet */
		bytes_to_send = sizeof(send_packet);
		rc = sendall(sd, (char *)&send_packet, &bytes_to_send);

		/* there was an error sending the packet */
		if (rc == -1) {
			printf("Error: Could not send data to host\n");
			close(sd);
			do_exit(STATE_UNKNOWN);
		}

		/* for some reason we didn't send all the bytes we were supposed to */
		else if (bytes_to_send < sizeof(send_packet)) {
			printf("Warning: Sent only %d of %d bytes to host\n", rc, sizeof(send_packet));
			close(sd);
			return STATE_UNKNOWN;
		}
	}

#ifdef DEBUG
	printf("Done sending data\n");
#endif

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

	printf("%d data packet(s) sent to host successfully.\n", total_packets);

	/* exit cleanly */
	do_exit(STATE_OK);

	/* no compiler complaints here... */
	return STATE_OK;
}
Пример #5
0
/** Post job result information to Nagios 3.x.
 *
 * Nagios 3.x uses a filesystem-based method of posting results. Results are
 * written to a temporary file. Once the temp file is closed, it's moved into
 * the Nagios results queue directory, and a marker file of the same name, but
 * with a ".ok" suffice, is created. This marker file tells Nagios that the 
 * results file is complete and ready to be processed.
 *
 * Nagios writes the first half of the results file in a temporary directory, 
 * and allows the child check process to finish it and move it to the results
 * queue directory. DNX foregoes the temporarly file and writes the results 
 * file directly into the queue directory, and then creates the marker file.
 *
 * SECURITY NOTE: Nagios creates the results file in a secure manner by 
 * setting the umask to mask off ALL rights from anyone but the owner of the 
 * file (Nagios). DNX doesn't have the luxury of being able to manipulate the
 * umask because DNX check results are posted in a secondary thread, which is
 * not allowed to manipulate the umask because it would cause a race condition
 * with the main thread in Nagios.
 *
 * @param[in] svc - the nagios service to which the results belong.
 * @param[in] check_type - nagios 3.x check type value.
 * @param[in] check_options - nagios 3.x bit-wise check options.
 * @param[in] schedule - boolean; nagios 3.x schedule flag.
 * @param[in] reschedule - boolean; nagios 3.x reschedule flag.
 * @param[in] start_time - the check start time in seconds.
 * @param[in] finish_time - the check finish time in seconds.
 * @param[in] early_timeout - boolean; true (!0) means the service timed out.
 * @param[in] exited_ok - boolean; true (!0) if the external check exited ok.
 * @param[in] res_code - the check result code.
 * @param[in] res_data - the check result data.
 *
 * @return Zero on success, or a non-zero error value.
 *
 * @todo This routine should be in nagios code.
 */
static int nagios3xPostResult(service * svc, int check_type,
      int check_options, int schedule, int reschedule,
      time_t start_time, time_t finish_time, int early_timeout,
      int exited_ok, int res_code, char * res_data)
{
   char * escaped_res_data;
   char * filename;
   FILE * fp = 0;
   int fd;

   // a nagios 3.x global variable
   extern char * temp_path;

   // a nagios 3.x core function
   if ((escaped_res_data = escape_newlines(res_data)) == 0)
      return DNX_ERR_MEMORY;

   // open a file in the check results path for storing check results
   // path length + 'checkXXXXXX' (11) + '/' (1) + '.ok' (3) + null (1)
   if ((filename = (char *)xmalloc(strlen(temp_path) 
         + 11 + 1 + 3 + 1)) == 0)
   {
      free(escaped_res_data); // allocated by nagios - use free
      return DNX_ERR_MEMORY;
   }
   sprintf(filename, "%s/checkXXXXXX", temp_path);
   if ((fd = mkstemp(filename)) < 0
         || (fp = fdopen(fd, "w")) == 0)
   {
      xfree(filename);
      free(escaped_res_data); // allocated by nagios - use free
      if (fd >= 0) close(fd);
      return DNX_ERR_OPEN;
   }

   // write check results to the queue file
   fprintf(fp, "### Active Check Result File ###\n");
   fprintf(fp, "file_time=%lu\n\n", (unsigned long)start_time);
   fprintf(fp, "### Nagios Service Check Result ###\n");
   fprintf(fp, "# Time: %s", ctime(&start_time));
   fprintf(fp, "host_name=%s\n", svc->host_name);
   fprintf(fp, "service_description=%s\n", svc->description);
   fprintf(fp, "check_type=%d\n", check_type);
   fprintf(fp, "check_options=%d\n", check_options);
   fprintf(fp, "scheduled_check=%d\n", schedule);
   fprintf(fp, "reschedule_check=%d\n", reschedule);
   fprintf(fp, "latency=%f\n", svc->latency);
   fprintf(fp, "start_time=%lu.0\n", (unsigned long)start_time);
   fprintf(fp, "finish_time=%lu.%lu\n", (unsigned long)finish_time);
   fprintf(fp, "early_timeout=%d\n", early_timeout);
   fprintf(fp, "exited_ok=%d\n", exited_ok);
   fprintf(fp, "return_code=%d\n", res_code);
   fprintf(fp, "output=%s\n", escaped_res_data);

   fclose(fp);

   free(escaped_res_data); // allocated by nagios - use free

   nagios3xMoveCheckResultToQueue(filename);

   xfree(filename);

   return 0;
}