Пример #1
0
static int conf_choice(struct menu *menu)
{
	struct symbol *sym, *def_sym;
	struct menu *child;
	int type;
	bool is_new;

	sym = menu->sym;
	type = sym_get_type(sym);
	is_new = !sym_has_value(sym);
	if (sym_is_changable(sym)) {
		conf_sym(menu);
		sym_calc_value(sym);
		switch (sym_get_tristate_value(sym)) {
		case no:
			return 1;
		case mod:
			return 0;
		case yes:
			break;
		}
	} else {
		switch (sym_get_tristate_value(sym)) {
		case no:
			return 1;
		case mod:
			printf("%*s%s\n", indent - 1, "", menu_get_prompt(menu));
			return 0;
		case yes:
			break;
		}
	}

	while (1) {
		int cnt, def;

		printf("%*s%s\n", indent - 1, "", menu_get_prompt(menu));
		def_sym = sym_get_choice_value(sym);
		cnt = def = 0;
		line[0] = '0';
		line[1] = 0;
		for (child = menu->list; child; child = child->next) {
			if (!menu_is_visible(child))
				continue;
			if (!child->sym) {
				printf("%*c %s\n", indent, '*', menu_get_prompt(child));
				continue;
			}
			cnt++;
			if (child->sym == def_sym) {
				def = cnt;
				printf("%*c", indent, '>');
			} else
				printf("%*c", indent, ' ');
			printf(" %d. %s", cnt, menu_get_prompt(child));
			if (child->sym->name)
				printf(" (%s)", child->sym->name);
			if (!sym_has_value(child->sym))
				printf(" (NEW)");
			printf("\n");
		}
		printf("%*schoice", indent - 1, "");
		if (cnt == 1) {
			printf("[1]: 1\n");
			goto conf_childs;
		}
		printf("[1-%d", cnt);
		if (sym->help)
			printf("?");
		printf("]: ");
		switch (input_mode) {
		case ask_new:
		case ask_silent:
			if (!is_new) {
				cnt = def;
				printf("%d\n", cnt);
				break;
			}
			check_stdin();
		case ask_all:
			fflush(stdout);
			fgets(line, 128, stdin);
			strip(line);
			if (line[0] == '?') {
				printf("\n%s\n", menu->sym->help ?
					menu->sym->help : nohelp_text);
				continue;
			}
			if (!line[0])
				cnt = def;
			else if (isdigit(line[0]))
				cnt = atoi(line);
			else
				continue;
			break;
		case set_random:
			def = (random() % cnt) + 1;
		case set_default:
		case set_yes:
		case set_mod:
		case set_no:
			cnt = def;
			printf("%d\n", cnt);
			break;
		}

	conf_childs:
		for (child = menu->list; child; child = child->next) {
			if (!child->sym || !menu_is_visible(child))
				continue;
			if (!--cnt)
				break;
		}
		if (!child)
			continue;
		if (line[strlen(line) - 1] == '?') {
			printf("\n%s\n", child->sym->help ?
				child->sym->help : nohelp_text);
			continue;
		}
		sym_set_choice_value(sym, child->sym);
		if (child->list) {
			indent += 2;
			conf(child->list);
			indent -= 2;
		}
		return 1;
	}
}
Пример #2
0
int main(int argc, char *argv[])
{
    int indent = 0;
    size_t flags = 0;

    json_t *json;
    json_error_t error;
    FILE* file = stdin;

    if(argc > 2) {
        fprintf(stderr, "usage: %s\n", argv[0]);
        return 2;
    }

    if(argc == 2) {
       file = fopen(argv[1], "r");
    }

    if( !file ) {
        perror("invalid file");
        return 2;
    }

    indent = getenv_int("JSON_INDENT");
    if(indent < 0 || indent > 255) {
        fprintf(stderr, "invalid value for JSON_INDENT: %d\n", indent);
        return 2;
    }

    if(indent > 0)
        flags |= JSON_INDENT(indent);

    if(getenv_int("JSON_COMPACT") > 0)
        flags |= JSON_COMPACT;

    if(getenv_int("JSON_ENSURE_ASCII"))
        flags |= JSON_ENSURE_ASCII;

    if(getenv_int("JSON_PRESERVE_ORDER"))
        flags |= JSON_PRESERVE_ORDER;

    if(getenv_int("JSON_SORT_KEYS"))
        flags |= JSON_SORT_KEYS;

    if(getenv_int("JSON_ASSUME_OBJECT"))
        flags |= JSON_ASSUME_OBJECT;

    if(getenv_int("JSON_ALLOW_EQUAL_SIGN"))
        flags |= JSON_ALLOW_EQUAL_SIGN;

    if(getenv_int("JSON_QUOTELESS_KEYS"))
        flags |= JSON_QUOTELESS_KEYS;

    if(getenv_int("STRIP")) {
        /* Load to memory, strip leading and trailing whitespace */
        size_t size = 0, used = 0;
        char *buffer = NULL;

        while(1) {
            int count;

            size = (size == 0 ? 128 : size * 2);
            buffer = realloc(buffer, size);
            if(!buffer) {
                fprintf(stderr, "Unable to allocate %d bytes\n", (int)size);
                return 1;
            }

            count = fread(buffer + used, 1, size - used, stdin);
            if(count < size - used) {
                buffer[used + count] = '\0';
                break;
            }
            used += count;
        }

        json = json_loads(strip(buffer), flags, &error);
        free(buffer);
    }
    else
        json = json_loadf(file, flags, &error);

    if(!json) {
        fprintf(stderr, "%d %d %d\n%s\n",
                error.line, error.column, error.position,
                error.text);
        return 1;
    }

    json_dumpf(json, stdout, flags);
    json_decref(json);

    return 0;
}
Пример #3
0
/*
 * Connection handling. Implements 'get' and 'set'.
 */
void *handle_conn(void *void_param) {//int conn, struct hsearch_data *htab) {

    thdata *param = (thdata *)void_param;
    int conn = param->conn;
    struct hsearch_data *htab = param->htab;

    char *cmd, *key, *val, *msg, *line;
    int len, curr_len, space;
    ENTRY entry, *result;

    FILE *f = fdopen(conn, "rw");
    line = malloc(128);

    while (1) {
        memset(line, 0, 128);

        fgets(line, 128, f);

        if (strlen(line) == 0) {        // Client has closed connection

            fclose(f);
            close(conn);
            free(line);
            break;
        }

        cmd = strtok(line, " ");

        if (strcmp(cmd, "get") == 0) {

            key = strtok(NULL, " ");
            strip(key);

            entry.key = key;
            hsearch_r(entry, FIND, &result, htab);
            if (result != NULL) {

                val = (char *) result->data;

                msg = malloc(strlen(key) + strlen(val) + 20);
                sprintf(msg, "VALUE %s 0 %d\r\n%s\r\nEND\r\n",
                        key, strlen(val), val);
                send(conn, msg, strlen(msg), 0);
                free(msg);

            } else {

                send(conn, "END\r\n", 5, 0);
            }

        } else if (strcmp(cmd, "set") == 0) {

            key = strtok(NULL, " ");

            strtok(NULL, " ");  // skip exp
            strtok(NULL, " ");  // skip flags

            // Length of string to read
            len = atoi(strtok(NULL, " ")) + 2;  // + 2 for \r\n

            // How much space to allocate. + 1 for \0
            space = len + 1;

            val = calloc(1, space);

            curr_len = 0;
            do {
                fgets(val + curr_len, space - curr_len, f);
                curr_len = strlen(val);
            } while (curr_len < len);

            strip(val);

            entry.key = strdup(key);
            entry.data = strdup(val);
            hsearch_r(entry, ENTER, &result, htab);

            send(conn, "STORED\r\n", 8, 0);
            free(val);
        }
    }

    return NULL;
}
Пример #4
0
internal_function
_nl_find_locale (const char *locale_path, size_t locale_path_len,
		 int category, const char **name)
{
  int mask;
  /* Name of the locale for this category.  */
  char *loc_name;
  const char *language;
  const char *modifier;
  const char *territory;
  const char *codeset;
  const char *normalized_codeset;
  struct loaded_l10nfile *locale_file;

  if ((*name)[0] == '\0')
    {
      /* The user decides which locale to use by setting environment
	 variables.  */
      *name = getenv ("LC_ALL");
      if (*name == NULL || (*name)[0] == '\0')
	*name = getenv (_nl_category_names.str
			+ _nl_category_name_idxs[category]);
      if (*name == NULL || (*name)[0] == '\0')
	*name = getenv ("LANG");
    }

  if (*name == NULL || (*name)[0] == '\0'
      || (__builtin_expect (__libc_enable_secure, 0)
	  && strchr (*name, '/') != NULL))
    *name = (char *) _nl_C_name;

  if (__builtin_expect (strcmp (*name, _nl_C_name), 1) == 0
      || __builtin_expect (strcmp (*name, _nl_POSIX_name), 1) == 0)
    {
      /* We need not load anything.  The needed data is contained in
	 the library itself.  */
      *name = (char *) _nl_C_name;
      return _nl_C[category];
    }

  /* We really have to load some data.  First we try the archive,
     but only if there was no LOCPATH environment variable specified.  */
  if (__builtin_expect (locale_path == NULL, 1))
    {
      struct __locale_data *data
	= _nl_load_locale_from_archive (category, name);
      if (__builtin_expect (data != NULL, 1))
	return data;

      /* Nothing in the archive.  Set the default path to search below.  */
      locale_path = _nl_default_locale_path;
      locale_path_len = sizeof _nl_default_locale_path;
    }

  /* We really have to load some data.  First see whether the name is
     an alias.  Please note that this makes it impossible to have "C"
     or "POSIX" as aliases.  */
  loc_name = (char *) _nl_expand_alias (*name);
  if (loc_name == NULL)
    /* It is no alias.  */
    loc_name = (char *) *name;

  /* Make a writable copy of the locale name.  */
  loc_name = strdupa (loc_name);

  /* LOCALE can consist of up to four recognized parts for the XPG syntax:

		language[_territory[.codeset]][@modifier]

     Beside the first all of them are allowed to be missing.  If the
     full specified locale is not found, the less specific one are
     looked for.  The various part will be stripped off according to
     the following order:
		(1) codeset
		(2) normalized codeset
		(3) territory
		(4) modifier
   */
  mask = _nl_explode_name (loc_name, &language, &modifier, &territory,
			   &codeset, &normalized_codeset);
  if (mask == -1)
    /* Memory allocate problem.  */
    return NULL;

  /* If exactly this locale was already asked for we have an entry with
     the complete name.  */
  locale_file = _nl_make_l10nflist (&_nl_locale_file_list[category],
				    locale_path, locale_path_len, mask,
				    language, territory, codeset,
				    normalized_codeset, modifier,
				    _nl_category_names.str
				    + _nl_category_name_idxs[category], 0);

  if (locale_file == NULL)
    {
      /* Find status record for addressed locale file.  We have to search
	 through all directories in the locale path.  */
      locale_file = _nl_make_l10nflist (&_nl_locale_file_list[category],
					locale_path, locale_path_len, mask,
					language, territory, codeset,
					normalized_codeset, modifier,
					_nl_category_names.str
					+ _nl_category_name_idxs[category], 1);
      if (locale_file == NULL)
	/* This means we are out of core.  */
	return NULL;
    }

  /* The space for normalized_codeset is dynamically allocated.  Free it.  */
  if (mask & XPG_NORM_CODESET)
    free ((void *) normalized_codeset);

  if (locale_file->decided == 0)
    _nl_load_locale (locale_file, category);

  if (locale_file->data == NULL)
    {
      int cnt;
      for (cnt = 0; locale_file->successor[cnt] != NULL; ++cnt)
	{
	  if (locale_file->successor[cnt]->decided == 0)
	    _nl_load_locale (locale_file->successor[cnt], category);
	  if (locale_file->successor[cnt]->data != NULL)
	    break;
	}
      /* Move the entry we found (or NULL) to the first place of
	 successors.  */
      locale_file->successor[0] = locale_file->successor[cnt];
      locale_file = locale_file->successor[cnt];

      if (locale_file == NULL)
	return NULL;
    }

  /* The LC_CTYPE category allows to check whether a locale is really
     usable.  If the locale name contains a charset name and the
     charset name used in the locale (present in the LC_CTYPE data) is
     not the same (after resolving aliases etc) we reject the locale
     since using it would irritate users expecting the charset named
     in the locale name.  */
  if (codeset != NULL)
    {
      /* Get the codeset information from the locale file.  */
      static const int codeset_idx[] =
	{
	  [__LC_CTYPE] = _NL_ITEM_INDEX (CODESET),
	  [__LC_NUMERIC] = _NL_ITEM_INDEX (_NL_NUMERIC_CODESET),
	  [__LC_TIME] = _NL_ITEM_INDEX (_NL_TIME_CODESET),
	  [__LC_COLLATE] = _NL_ITEM_INDEX (_NL_COLLATE_CODESET),
	  [__LC_MONETARY] = _NL_ITEM_INDEX (_NL_MONETARY_CODESET),
	  [__LC_MESSAGES] = _NL_ITEM_INDEX (_NL_MESSAGES_CODESET),
	  [__LC_PAPER] = _NL_ITEM_INDEX (_NL_PAPER_CODESET),
	  [__LC_NAME] = _NL_ITEM_INDEX (_NL_NAME_CODESET),
	  [__LC_ADDRESS] = _NL_ITEM_INDEX (_NL_ADDRESS_CODESET),
	  [__LC_TELEPHONE] = _NL_ITEM_INDEX (_NL_TELEPHONE_CODESET),
	  [__LC_MEASUREMENT] = _NL_ITEM_INDEX (_NL_MEASUREMENT_CODESET),
	  [__LC_IDENTIFICATION] = _NL_ITEM_INDEX (_NL_IDENTIFICATION_CODESET)
	};
      const struct __locale_data *data;
      const char *locale_codeset;
      char *clocale_codeset;
      char *ccodeset;

      data = (const struct __locale_data *) locale_file->data;
      locale_codeset =
	(const char *) data->values[codeset_idx[category]].string;
      assert (locale_codeset != NULL);
      /* Note the length of the allocated memory: +3 for up to two slashes
	 and the NUL byte.  */
      clocale_codeset = (char *) alloca (strlen (locale_codeset) + 3);
      strip (clocale_codeset, locale_codeset);

      ccodeset = (char *) alloca (strlen (codeset) + 3);
      strip (ccodeset, codeset);

      if (__gconv_compare_alias (upstr (ccodeset, ccodeset),
				 upstr (clocale_codeset,
					clocale_codeset)) != 0)
	/* The codesets are not identical, don't use the locale.  */
	return NULL;
    }
Пример #5
0
/* read all program, host, and service status information */
int xsddefault_read_status_data(char *config_file, int options) {
#ifdef NO_MMAP
	char input[MAX_PLUGIN_OUTPUT_LENGTH] = "";
	FILE *fp = NULL;
#else
	char *input = NULL;
	mmapfile *thefile = NULL;
#endif
	int data_type = XSDDEFAULT_NO_DATA;
	hoststatus *temp_hoststatus = NULL;
	servicestatus *temp_servicestatus = NULL;
	char *var = NULL;
	char *val = NULL;
	char *ptr = NULL;
	int result = 0;
	/* comment and downtime vars */
	unsigned long comment_id = 0;
	int persistent = FALSE;
	int expires = FALSE;
	time_t expire_time = 0L;
	int entry_type = USER_COMMENT;
	int source = COMMENTSOURCE_INTERNAL;
	time_t entry_time = 0L;
	char *host_name = NULL;
	char *service_description = NULL;
	char *author = NULL;
	char *comment_data = NULL;
	unsigned long downtime_id = 0;
	time_t start_time = 0L;
	time_t flex_downtime_start = 0L;
	time_t end_time = 0L;
	int fixed = FALSE;
	unsigned long triggered_by = 0;
	unsigned long duration = 0L;
	int x = 0;
	int is_in_effect = FALSE;


	/* initialize some vars */
	for(x = 0; x < MAX_CHECK_STATS_TYPES; x++) {
		program_stats[x][0] = 0;
		program_stats[x][1] = 0;
		program_stats[x][2] = 0;
		}

	/* grab configuration data */
	result = xsddefault_grab_config_info(config_file);
	if(result == ERROR)
		return ERROR;

	/* open the status file for reading */
#ifdef NO_MMAP
	if((fp = fopen(xsddefault_status_log, "r")) == NULL)
		return ERROR;
#else
	if((thefile = mmap_fopen(xsddefault_status_log)) == NULL)
		return ERROR;
#endif

	/* Big speedup when reading status.dat in bulk */
	defer_downtime_sorting = 1;
	defer_comment_sorting = 1;

	/* read all lines in the status file */
	while(1) {

#ifdef NO_MMAP
		strcpy(input, "");
		if(fgets(input, sizeof(input), fp) == NULL)
			break;
#else
		/* free memory */
		my_free(input);

		/* read the next line */
		if((input = mmap_fgets(thefile)) == NULL)
			break;
#endif

		strip(input);

		/* skip blank lines and comments */
		if(input[0] == '#' || input[0] == '\x0')
			continue;

		else if(!strcmp(input, "info {"))
			data_type = XSDDEFAULT_INFO_DATA;
		else if(!strcmp(input, "programstatus {"))
			data_type = XSDDEFAULT_PROGRAMSTATUS_DATA;
		else if(!strcmp(input, "hoststatus {")) {
			data_type = XSDDEFAULT_HOSTSTATUS_DATA;
			temp_hoststatus = (hoststatus *)calloc(1, sizeof(hoststatus));
			}
		else if(!strcmp(input, "servicestatus {")) {
			data_type = XSDDEFAULT_SERVICESTATUS_DATA;
			temp_servicestatus = (servicestatus *)calloc(1, sizeof(servicestatus));
			}
		else if(!strcmp(input, "contactstatus {")) {
			data_type = XSDDEFAULT_CONTACTSTATUS_DATA;
			/* unimplemented */
			}
		else if(!strcmp(input, "hostcomment {"))
			data_type = XSDDEFAULT_HOSTCOMMENT_DATA;
		else if(!strcmp(input, "servicecomment {"))
			data_type = XSDDEFAULT_SERVICECOMMENT_DATA;
		else if(!strcmp(input, "hostdowntime {"))
			data_type = XSDDEFAULT_HOSTDOWNTIME_DATA;
		else if(!strcmp(input, "servicedowntime {"))
			data_type = XSDDEFAULT_SERVICEDOWNTIME_DATA;

		else if(!strcmp(input, "}")) {

			switch(data_type) {

				case XSDDEFAULT_INFO_DATA:
					break;

				case XSDDEFAULT_PROGRAMSTATUS_DATA:
					break;

				case XSDDEFAULT_HOSTSTATUS_DATA:
					add_host_status(temp_hoststatus);
					temp_hoststatus = NULL;
					break;

				case XSDDEFAULT_SERVICESTATUS_DATA:
					add_service_status(temp_servicestatus);
					temp_servicestatus = NULL;
					break;

				case XSDDEFAULT_CONTACTSTATUS_DATA:
					/* unimplemented */
					break;

				case XSDDEFAULT_HOSTCOMMENT_DATA:
				case XSDDEFAULT_SERVICECOMMENT_DATA:

					/* add the comment */
					add_comment((data_type == XSDDEFAULT_HOSTCOMMENT_DATA) ? HOST_COMMENT : SERVICE_COMMENT, entry_type, host_name, service_description, entry_time, author, comment_data, comment_id, persistent, expires, expire_time, source);

					/* free temp memory */
					my_free(host_name);
					my_free(service_description);
					my_free(author);
					my_free(comment_data);

					/* reset defaults */
					entry_type = USER_COMMENT;
					comment_id = 0;
					source = COMMENTSOURCE_INTERNAL;
					persistent = FALSE;
					entry_time = 0L;
					expires = FALSE;
					expire_time = 0L;

					break;

				case XSDDEFAULT_HOSTDOWNTIME_DATA:
				case XSDDEFAULT_SERVICEDOWNTIME_DATA:

					/* add the downtime */
					if(data_type == XSDDEFAULT_HOSTDOWNTIME_DATA)
						add_host_downtime(host_name, entry_time, author, comment_data, start_time, flex_downtime_start, end_time, fixed, triggered_by, duration, downtime_id, is_in_effect);
					else
						add_service_downtime(host_name, service_description, entry_time, author, comment_data, start_time, flex_downtime_start, end_time, fixed, triggered_by, duration, downtime_id, is_in_effect);

					/* free temp memory */
					my_free(host_name);
					my_free(service_description);
					my_free(author);
					my_free(comment_data);

					/* reset defaults */
					downtime_id = 0;
					entry_time = 0L;
					start_time = 0L;
					end_time = 0L;
					fixed = FALSE;
					triggered_by = 0;
					duration = 0L;
					is_in_effect = FALSE;

					break;

				default:
					break;
				}

			data_type = XSDDEFAULT_NO_DATA;
			}

		else if(data_type != XSDDEFAULT_NO_DATA) {

			var = strtok(input, "=");
			val = strtok(NULL, "\n");
			if(val == NULL)
				continue;

			switch(data_type) {

				case XSDDEFAULT_INFO_DATA:
					break;

				case XSDDEFAULT_PROGRAMSTATUS_DATA:
					/* NOTE: some vars are not read, as they are not used by the CGIs (modified attributes, event handler commands, etc.) */
					if(!strcmp(var, "nagios_pid"))
						nagios_pid = atoi(val);
					else if(!strcmp(var, "daemon_mode"))
						daemon_mode = (atoi(val) > 0) ? TRUE : FALSE;
					else if(!strcmp(var, "program_start"))
						program_start = strtoul(val, NULL, 10);
					else if(!strcmp(var, "last_log_rotation"))
						last_log_rotation = strtoul(val, NULL, 10);
					else if(!strcmp(var, "enable_notifications"))
						enable_notifications = (atoi(val) > 0) ? TRUE : FALSE;
					else if(!strcmp(var, "active_service_checks_enabled"))
						execute_service_checks = (atoi(val) > 0) ? TRUE : FALSE;
					else if(!strcmp(var, "passive_service_checks_enabled"))
						accept_passive_service_checks = (atoi(val) > 0) ? TRUE : FALSE;
					else if(!strcmp(var, "active_host_checks_enabled"))
						execute_host_checks = (atoi(val) > 0) ? TRUE : FALSE;
					else if(!strcmp(var, "passive_host_checks_enabled"))
						accept_passive_host_checks = (atoi(val) > 0) ? TRUE : FALSE;
					else if(!strcmp(var, "enable_event_handlers"))
						enable_event_handlers = (atoi(val) > 0) ? TRUE : FALSE;
					else if(!strcmp(var, "obsess_over_services"))
						obsess_over_services = (atoi(val) > 0) ? TRUE : FALSE;
					else if(!strcmp(var, "obsess_over_hosts"))
						obsess_over_hosts = (atoi(val) > 0) ? TRUE : FALSE;
					else if(!strcmp(var, "check_service_freshness"))
						check_service_freshness = (atoi(val) > 0) ? TRUE : FALSE;
					else if(!strcmp(var, "check_host_freshness"))
						check_host_freshness = (atoi(val) > 0) ? TRUE : FALSE;
					else if(!strcmp(var, "enable_flap_detection"))
						enable_flap_detection = (atoi(val) > 0) ? TRUE : FALSE;
					else if(!strcmp(var, "process_performance_data"))
						process_performance_data = (atoi(val) > 0) ? TRUE : FALSE;

					else if(strstr(var, "_stats")) {

						x = -1;
						if(!strcmp(var, "active_scheduled_host_check_stats"))
							x = ACTIVE_SCHEDULED_HOST_CHECK_STATS;
						if(!strcmp(var, "active_ondemand_host_check_stats"))
							x = ACTIVE_ONDEMAND_HOST_CHECK_STATS;
						if(!strcmp(var, "passive_host_check_stats"))
							x = PASSIVE_HOST_CHECK_STATS;
						if(!strcmp(var, "active_scheduled_service_check_stats"))
							x = ACTIVE_SCHEDULED_SERVICE_CHECK_STATS;
						if(!strcmp(var, "active_ondemand_service_check_stats"))
							x = ACTIVE_ONDEMAND_SERVICE_CHECK_STATS;
						if(!strcmp(var, "passive_service_check_stats"))
							x = PASSIVE_SERVICE_CHECK_STATS;
						if(!strcmp(var, "cached_host_check_stats"))
							x = ACTIVE_CACHED_HOST_CHECK_STATS;
						if(!strcmp(var, "cached_service_check_stats"))
							x = ACTIVE_CACHED_SERVICE_CHECK_STATS;
						if(!strcmp(var, "external_command_stats"))
							x = EXTERNAL_COMMAND_STATS;
						if(!strcmp(var, "parallel_host_check_stats"))
							x = PARALLEL_HOST_CHECK_STATS;
						if(!strcmp(var, "serial_host_check_stats"))
							x = SERIAL_HOST_CHECK_STATS;

						if(x >= 0) {
							if((ptr = strtok(val, ","))) {
								program_stats[x][0] = atoi(ptr);
								if((ptr = strtok(NULL, ","))) {
									program_stats[x][1] = atoi(ptr);
									if((ptr = strtok(NULL, "\n")))
										program_stats[x][2] = atoi(ptr);
									}
								}
							}
						}
					break;

				case XSDDEFAULT_HOSTSTATUS_DATA:
					/* NOTE: some vars are not read, as they are not used by the CGIs (modified attributes, event handler commands, etc.) */
					if(temp_hoststatus != NULL) {
						if(!strcmp(var, "host_name"))
							temp_hoststatus->host_name = (char *)strdup(val);
						else if(!strcmp(var, "has_been_checked"))
							temp_hoststatus->has_been_checked = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "should_be_scheduled"))
							temp_hoststatus->should_be_scheduled = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "check_execution_time"))
							temp_hoststatus->execution_time = strtod(val, NULL);
						else if(!strcmp(var, "check_latency"))
							temp_hoststatus->latency = strtod(val, NULL);
						else if(!strcmp(var, "check_type"))
							temp_hoststatus->check_type = atoi(val);
						else if(!strcmp(var, "current_state"))
							temp_hoststatus->status = atoi(val);
						else if(!strcmp(var, "last_hard_state"))
							temp_hoststatus->last_hard_state = atoi(val);
						else if(!strcmp(var, "plugin_output")) {
							temp_hoststatus->plugin_output = (char *)strdup(val);
							unescape_newlines(temp_hoststatus->plugin_output);
							}
						else if(!strcmp(var, "long_plugin_output")) {
							temp_hoststatus->long_plugin_output = (char *)strdup(val);
							unescape_newlines(temp_hoststatus->long_plugin_output);
							}
						else if(!strcmp(var, "performance_data"))
							temp_hoststatus->perf_data = (char *)strdup(val);
						else if(!strcmp(var, "current_attempt"))
							temp_hoststatus->current_attempt = atoi(val);
						else if(!strcmp(var, "max_attempts"))
							temp_hoststatus->max_attempts = atoi(val);
						else if(!strcmp(var, "last_check"))
							temp_hoststatus->last_check = strtoul(val, NULL, 10);
						else if(!strcmp(var, "next_check"))
							temp_hoststatus->next_check = strtoul(val, NULL, 10);
						else if(!strcmp(var, "check_options"))
							temp_hoststatus->check_options = atoi(val);
						else if(!strcmp(var, "current_attempt"))
							temp_hoststatus->current_attempt = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "state_type"))
							temp_hoststatus->state_type = atoi(val);
						else if(!strcmp(var, "last_state_change"))
							temp_hoststatus->last_state_change = strtoul(val, NULL, 10);
						else if(!strcmp(var, "last_hard_state_change"))
							temp_hoststatus->last_hard_state_change = strtoul(val, NULL, 10);
						else if(!strcmp(var, "last_time_up"))
							temp_hoststatus->last_time_up = strtoul(val, NULL, 10);
						else if(!strcmp(var, "last_time_down"))
							temp_hoststatus->last_time_down = strtoul(val, NULL, 10);
						else if(!strcmp(var, "last_time_unreachable"))
							temp_hoststatus->last_time_unreachable = strtoul(val, NULL, 10);
						else if(!strcmp(var, "last_notification"))
							temp_hoststatus->last_notification = strtoul(val, NULL, 10);
						else if(!strcmp(var, "next_notification"))
							temp_hoststatus->next_notification = strtoul(val, NULL, 10);
						else if(!strcmp(var, "no_more_notifications"))
							temp_hoststatus->no_more_notifications = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "current_notification_number"))
							temp_hoststatus->current_notification_number = atoi(val);
						else if(!strcmp(var, "notifications_enabled"))
							temp_hoststatus->notifications_enabled = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "problem_has_been_acknowledged"))
							temp_hoststatus->problem_has_been_acknowledged = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "acknowledgement_type"))
							temp_hoststatus->acknowledgement_type = atoi(val);
						else if(!strcmp(var, "active_checks_enabled"))
							temp_hoststatus->checks_enabled = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "passive_checks_enabled"))
							temp_hoststatus->accept_passive_checks = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "event_handler_enabled"))
							temp_hoststatus->event_handler_enabled = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "flap_detection_enabled"))
							temp_hoststatus->flap_detection_enabled = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "process_performance_data"))
							temp_hoststatus->process_performance_data = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "obsess_over_host") || !strcmp(var, "obsess"))
							temp_hoststatus->obsess = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "last_update"))
							temp_hoststatus->last_update = strtoul(val, NULL, 10);
						else if(!strcmp(var, "is_flapping"))
							temp_hoststatus->is_flapping = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "percent_state_change"))
							temp_hoststatus->percent_state_change = strtod(val, NULL);
						else if(!strcmp(var, "scheduled_downtime_depth"))
							temp_hoststatus->scheduled_downtime_depth = atoi(val);
						}
					break;

				case XSDDEFAULT_SERVICESTATUS_DATA:
					/* NOTE: some vars are not read, as they are not used by the CGIs (modified attributes, event handler commands, etc.) */
					if(temp_servicestatus != NULL) {
						if(!strcmp(var, "host_name"))
							temp_servicestatus->host_name = (char *)strdup(val);
						else if(!strcmp(var, "service_description"))
							temp_servicestatus->description = (char *)strdup(val);
						else if(!strcmp(var, "has_been_checked"))
							temp_servicestatus->has_been_checked = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "should_be_scheduled"))
							temp_servicestatus->should_be_scheduled = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "check_execution_time"))
							temp_servicestatus->execution_time = strtod(val, NULL);
						else if(!strcmp(var, "check_latency"))
							temp_servicestatus->latency = strtod(val, NULL);
						else if(!strcmp(var, "check_type"))
							temp_servicestatus->check_type = atoi(val);
						else if(!strcmp(var, "current_state"))
							temp_servicestatus->status = atoi(val);
						else if(!strcmp(var, "last_hard_state"))
							temp_servicestatus->last_hard_state = atoi(val);
						else if(!strcmp(var, "current_attempt"))
							temp_servicestatus->current_attempt = atoi(val);
						else if(!strcmp(var, "max_attempts"))
							temp_servicestatus->max_attempts = atoi(val);
						else if(!strcmp(var, "state_type"))
							temp_servicestatus->state_type = atoi(val);
						else if(!strcmp(var, "last_state_change"))
							temp_servicestatus->last_state_change = strtoul(val, NULL, 10);
						else if(!strcmp(var, "last_hard_state_change"))
							temp_servicestatus->last_hard_state_change = strtoul(val, NULL, 10);
						else if(!strcmp(var, "last_time_ok"))
							temp_servicestatus->last_time_ok = strtoul(val, NULL, 10);
						else if(!strcmp(var, "last_time_warning"))
							temp_servicestatus->last_time_warning = strtoul(val, NULL, 10);
						else if(!strcmp(var, "last_time_unknown"))
							temp_servicestatus->last_time_unknown = strtoul(val, NULL, 10);
						else if(!strcmp(var, "last_time_critical"))
							temp_servicestatus->last_time_critical = strtoul(val, NULL, 10);
						else if(!strcmp(var, "plugin_output")) {
							temp_servicestatus->plugin_output = (char *)strdup(val);
							unescape_newlines(temp_servicestatus->plugin_output);
							}
						else if(!strcmp(var, "long_plugin_output")) {
							temp_servicestatus->long_plugin_output = (char *)strdup(val);
							unescape_newlines(temp_servicestatus->long_plugin_output);
							}
						else if(!strcmp(var, "performance_data"))
							temp_servicestatus->perf_data = (char *)strdup(val);
						else if(!strcmp(var, "last_check"))
							temp_servicestatus->last_check = strtoul(val, NULL, 10);
						else if(!strcmp(var, "next_check"))
							temp_servicestatus->next_check = strtoul(val, NULL, 10);
						else if(!strcmp(var, "check_options"))
							temp_servicestatus->check_options = atoi(val);
						else if(!strcmp(var, "current_notification_number"))
							temp_servicestatus->current_notification_number = atoi(val);
						else if(!strcmp(var, "last_notification"))
							temp_servicestatus->last_notification = strtoul(val, NULL, 10);
						else if(!strcmp(var, "next_notification"))
							temp_servicestatus->next_notification = strtoul(val, NULL, 10);
						else if(!strcmp(var, "no_more_notifications"))
							temp_servicestatus->no_more_notifications = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "notifications_enabled"))
							temp_servicestatus->notifications_enabled = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "active_checks_enabled"))
							temp_servicestatus->checks_enabled = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "passive_checks_enabled"))
							temp_servicestatus->accept_passive_checks = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "event_handler_enabled"))
							temp_servicestatus->event_handler_enabled = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "problem_has_been_acknowledged"))
							temp_servicestatus->problem_has_been_acknowledged = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "acknowledgement_type"))
							temp_servicestatus->acknowledgement_type = atoi(val);
						else if(!strcmp(var, "flap_detection_enabled"))
							temp_servicestatus->flap_detection_enabled = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "process_performance_data"))
							temp_servicestatus->process_performance_data = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "obsess_over_service") || !strcmp(var, "obsess"))
							temp_servicestatus->obsess = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "last_update"))
							temp_servicestatus->last_update = strtoul(val, NULL, 10);
						else if(!strcmp(var, "is_flapping"))
							temp_servicestatus->is_flapping = (atoi(val) > 0) ? TRUE : FALSE;
						else if(!strcmp(var, "percent_state_change"))
							temp_servicestatus->percent_state_change = strtod(val, NULL);
						else if(!strcmp(var, "scheduled_downtime_depth"))
							temp_servicestatus->scheduled_downtime_depth = atoi(val);
						}
					break;

				case XSDDEFAULT_CONTACTSTATUS_DATA:
					/* unimplemented */
					break;

				case XSDDEFAULT_HOSTCOMMENT_DATA:
				case XSDDEFAULT_SERVICECOMMENT_DATA:
					if(!strcmp(var, "host_name"))
						host_name = (char *)strdup(val);
					else if(!strcmp(var, "service_description"))
						service_description = (char *)strdup(val);
					else if(!strcmp(var, "entry_type"))
						entry_type = atoi(val);
					else if(!strcmp(var, "comment_id"))
						comment_id = strtoul(val, NULL, 10);
					else if(!strcmp(var, "source"))
						source = atoi(val);
					else if(!strcmp(var, "persistent"))
						persistent = (atoi(val) > 0) ? TRUE : FALSE;
					else if(!strcmp(var, "entry_time"))
						entry_time = strtoul(val, NULL, 10);
					else if(!strcmp(var, "expires"))
						expires = (atoi(val) > 0) ? TRUE : FALSE;
					else if(!strcmp(var, "expire_time"))
						expire_time = strtoul(val, NULL, 10);
					else if(!strcmp(var, "author"))
						author = (char *)strdup(val);
					else if(!strcmp(var, "comment_data"))
						comment_data = (char *)strdup(val);
					break;

				case XSDDEFAULT_HOSTDOWNTIME_DATA:
				case XSDDEFAULT_SERVICEDOWNTIME_DATA:
					if(!strcmp(var, "host_name"))
						host_name = (char *)strdup(val);
					else if(!strcmp(var, "service_description"))
						service_description = (char *)strdup(val);
					else if(!strcmp(var, "downtime_id"))
						downtime_id = strtoul(val, NULL, 10);
					else if(!strcmp(var, "comment_id"))
						comment_id = strtoul(val, NULL, 10);
					else if(!strcmp(var, "entry_time"))
						entry_time = strtoul(val, NULL, 10);
					else if(!strcmp(var, "start_time"))
						start_time = strtoul(val, NULL, 10);
					else if(!strcmp(var, "flex_downtime_start"))
						flex_downtime_start = strtoul(val, NULL, 10);
					else if(!strcmp(var, "end_time"))
						end_time = strtoul(val, NULL, 10);
					else if(!strcmp(var, "fixed"))
						fixed = (atoi(val) > 0) ? TRUE : FALSE;
					else if(!strcmp(var, "triggered_by"))
						triggered_by = strtoul(val, NULL, 10);
					else if(!strcmp(var, "duration"))
						duration = strtoul(val, NULL, 10);
					else if(!strcmp(var, "is_in_effect"))
						is_in_effect = (atoi(val) > 0) ? TRUE : FALSE;
					else if(!strcmp(var, "author"))
						author = (char *)strdup(val);
					else if(!strcmp(var, "comment"))
						comment_data = (char *)strdup(val);
					break;

				default:
					break;
				}

			}
		}

	/* free memory and close the file */
#ifdef NO_MMAP
	fclose(fp);
#else
	my_free(input);
	mmap_fclose(thefile);
#endif

	/* free memory */
	my_free(xsddefault_status_log);
	my_free(xsddefault_temp_file);

	if(sort_downtime() != OK)
		return ERROR;
	if(sort_comments() != OK)
		return ERROR;

	return OK;
	}
Пример #6
0
/** @brief Read's log data for defined timerange and stores the entries into entry_list struct
 *  @param [out] entry_list returns a filled entry list of requested log data
 *  @param [in] filter_list a list of filters of type logfilter struct
 *  @param [out] error_text returns a error string in case of an error execpt on READLOG_ERROR_MEMORY
 *  @param [in] search_string a string you are searching for
 *		Set to NULL to disable search function
 *  @param [in] reverse this bool defines which order the log entries should return
 *  @param [in] ts_start defines the start timestamp for log entries
 *	@arg >=0 means unix timestamp
 *  @param [in] ts_end defines the end timestamp for log entries
 *	@arg >=0 means unix timestamp
 *  @return
 *	@retval READLOG_OK
 *	@retval READLOG_ERROR_WARNING
 *	@retval READLOG_ERROR_FATAL
 *	@retval READLOG_ERROR_MEMORY
 *	@retval READLOG_ERROR_FILTER
 *  @author Ricardo Bartels
 *
 *  This functions reads a  \c log_file and and try's (if set) to filter for a search string.
 *  This search string uses regular expressions. The reverse option defines if you want
 *  have your log entries returned in normal or revers order. Normal order for returning
 *  would be from the newest entry to the oldest. You can also set a time "window". This
 *  defines if you want to exclude entries which are outside of these "window". Then only
 *  entries will be returned which are between start and end. Very useful if user has all
 *  entries in one log file.
**/
int get_log_entries(logentry **entry_list, logfilter **filter_list, char **error_text, char *search_string, int reverse, time_t ts_start, time_t ts_end) {
	char *input = NULL;
	char *temp_buffer = NULL;
	char *search_regex = NULL;
	char log_file_name[MAX_FILENAME_LENGTH];
	char ts_buffer[16];
	int type = 0;
	int regex_i = 0, i = 0, len = 0;
	int file_num = 1;
	int file = 0;
	int in_range = FALSE;
	int return_val = READLOG_OK;
	int data_found = FALSE;
	int open_read_failed = FALSE;
	short keep_entry = TRUE;
	time_t timestamp = 0L;
	time_t last_timestamp = 0L;
	mmapfile *thefile = NULL;
	logentry *temp_entry = NULL;
	logentry *last_entry = NULL;
	regex_t preg;
	logfilter *temp_filter;
	DIR *dirp;
	struct dirent *dptr;
	struct file_data files[10000];
#ifdef HAVE_ZLIB_H
	gzFile gzfile = NULL;
	char gz_buffer[MAX_COMMAND_BUFFER * 2];
#else
	read_gzip_logs = FALSE;
#endif

	/* empty error_text */
	if (*error_text != NULL)
		my_free(*error_text);

	/* bail out if one timestamp is negative */
	if (ts_start < 0 || ts_end < 0) {
		*error_text = strdup("start or end timestamp are invalid. Check submited date information");
		return READLOG_ERROR_FATAL;
	}

	/* check if search_string is set */
	if (search_string != NULL) {

		/* allocate for 3 extra chars, ^, $ and \0 */
		search_regex = malloc(sizeof(char) * (strlen(search_string) * 2 + 3));
		len = strlen(search_string);
		for (i = 0; i < len; i++, regex_i++) {
			if (search_string[i] == '*') {
				search_regex[regex_i++] = '.';
				search_regex[regex_i] = '*';
			} else
				search_regex[regex_i] = search_string[i];
		}

		search_regex[regex_i] = '\0';

		/* check and compile regex, return error on failure */
		if (regcomp(&preg, search_regex, REG_ICASE | REG_NOSUB) != 0) {
			regfree(&preg);
			my_free(search_regex);
			*error_text = strdup("It seems like that reagular expressions don't like what you searched for. Please change your search string.");
			return READLOG_ERROR_FATAL;
		}

		my_free(search_regex);
	}

	/* initialize file data array */
	for (i=0;i<10000;i++)
		files[i].file_name = NULL;

	/* try to open log_archive_path, return if it fails */
	if ((dirp=opendir(log_archive_path)) == NULL){

		if (search_string != NULL)
			regfree(&preg);

		asprintf(&temp_buffer, "Unable to open \"log_archive_path\" -> \"%s\"!!!", log_archive_path);
		*error_text = strdup(temp_buffer);
		my_free(temp_buffer);

		return READLOG_ERROR_FATAL;

	} else {

		/* read every dir entry */
		while ((dptr=readdir(dirp)) != NULL) {

			/* filter dir for icinga / nagios log files */
			if ((strncmp("icinga-",dptr->d_name,7) == 0 || strncmp("nagios-",dptr->d_name,7) == 0 ) &&
			    ((strstr(dptr->d_name, ".log") && strlen(dptr->d_name) == 24 ) ||
			    (read_gzip_logs == TRUE && strstr(dptr->d_name, ".log.gz") && strlen(dptr->d_name) == 27 )))
				files[file_num++].file_name = strdup(dptr->d_name);
		}
		closedir(dirp);
	}

	/* sort log files, newest first */
	qsort((void *)files, file_num, sizeof(struct file_data), sort_icinga_logfiles_by_name);

	/* define which log files to use */
	for (i=0; i< file_num; i++) {

		/* first log file is always the current log file */
		if (i == 0) {
			strncpy(log_file_name, log_file, sizeof(log_file_name) -1);
			log_file_name[sizeof(log_file_name)-1] = '\x0';

		/* return full path of logfile and store first timestamp of last file */
		} else {
			snprintf(log_file_name, sizeof(log_file_name) -1, "%s%s",log_archive_path, files[i].file_name);
			log_file_name[sizeof(log_file_name)-1] = '\x0';

			last_timestamp = timestamp;
		}

		/* free file entry and set to NULL. if valid file is found, entry gets refilled */
		my_free(files[i].file_name);

		/* we found data and we are out of range again, file must be older then ts_start. stop checking files */
		if (data_found == TRUE && in_range == FALSE)
			continue;

		/* try to open log file, or throw error and try next log file */
		open_read_failed = FALSE;
		if (read_gzip_logs == TRUE && strstr(log_file_name, ".log.gz")) {
#ifdef HAVE_ZLIB_H
			if ((gzfile = gzopen(log_file_name, "r")) == NULL)
#endif
				open_read_failed = TRUE;
		} else {
			if((file=open(log_file_name, O_RDONLY)) < -1)
				open_read_failed = TRUE;
		}
		if(open_read_failed == TRUE) {

			if (*error_text == NULL) {
				asprintf(&temp_buffer, "Unable to open log file \"%s\" !!!", log_file_name);
				*error_text = strdup(temp_buffer);
				my_free(temp_buffer);
			}

			return_val = READLOG_ERROR_WARNING;

			continue;
		}

		/* read first 16 bytes to get first timestamp, or throw error if data is not 16 bytes log (empty file) */
		open_read_failed = FALSE;
		if (read_gzip_logs == TRUE && strstr(log_file_name, ".log.gz")) {
#ifdef HAVE_ZLIB_H
			if(gzread(gzfile,ts_buffer,16) != 16)
#endif
				open_read_failed = TRUE;
		} else {
			if(read(file,ts_buffer,16) != 16)
				open_read_failed = TRUE;
		}
		if(open_read_failed == TRUE) {

			if (*error_text == NULL) {
				asprintf(&temp_buffer, "Log file \"%s\" invalid! No timestamp found within first 16 bytes!", log_file_name);
				*error_text = strdup(temp_buffer);
				my_free(temp_buffer);
			}

			return_val = READLOG_ERROR_WARNING;

#ifdef HAVE_ZLIB_H
			if (read_gzip_logs == TRUE && strstr(log_file_name, ".log.gz"))
				gzclose(gzfile);
			else
#endif
				close(file);
			continue;
		}

#ifdef HAVE_ZLIB_H
		if (read_gzip_logs == TRUE && strstr(log_file_name, ".log.gz"))
			gzclose(gzfile);
		else
#endif
			close(file);

		/* get first timestamp */
		temp_buffer = strtok(ts_buffer, "]");
		timestamp = (temp_buffer == NULL) ? 0L : strtoul(temp_buffer + 1, NULL, 10);


		/* if first (oldest) timestamp in file is newer then ts_end, skip file */
		if (timestamp > ts_end)
			continue;

		in_range = TRUE;

		/* the priviouse file holds range for ts_start */
		if (last_timestamp != 0L && last_timestamp < ts_start)
			in_range = FALSE;

		/* keep file if in range */
		if(in_range == TRUE) {
			files[i].file_name = strdup(log_file_name);
			data_found = TRUE;
		}
	}

	/* read all log files we found earlier in reverse order, starting with the oldest */
	for (i=file_num; i >= 0; i--) {

		/* if file name is empty try next file */
		if (files[i].file_name == NULL)
			continue;

		/* try to open log file */
		if (read_gzip_logs == TRUE && strstr(files[i].file_name, ".log.gz")) {
#ifdef HAVE_ZLIB_H
			if ((gzfile = gzopen(files[i].file_name, "r")) == NULL)
#endif
				continue;
		} else {
			if ((thefile = mmap_fopen(files[i].file_name)) == NULL)
				continue;
		}

		while (1) {

			/* free memory */
			my_free(input);

			if (read_gzip_logs == TRUE && strstr(files[i].file_name, ".log.gz")) {
#ifdef HAVE_ZLIB_H
				if ((gzgets(gzfile, gz_buffer, MAX_COMMAND_BUFFER * 2 + 1)) == NULL)
#endif
					break;
			} else {
				if ((input = mmap_fgets(thefile)) == NULL)
					break;
			}

#ifdef HAVE_ZLIB_H
			if (read_gzip_logs == TRUE && strstr(files[i].file_name, ".log.gz")) {
				gz_buffer[MAX_COMMAND_BUFFER * 2 - 1] = '\0';
				input = strdup(gz_buffer);
			}
#endif
			strip(input);

			if ((int)strlen(input) == 0)
				continue;

			/* get timestamp */
			temp_buffer = strtok(input, "]");

			if (temp_buffer == NULL)
				continue;

			timestamp = strtoul(temp_buffer + 1, NULL, 10);

			/* skip line if out of range */
			if ((ts_end >= 0 && timestamp > ts_end) || (ts_start >= 0 && timestamp < ts_start))
				continue;

			/* get log entry text */
			temp_buffer = strtok(NULL, "\n");

			if (temp_buffer == NULL)
				continue;

			/* if we search for something, check if it entry matches search_string */
			if (search_string != NULL) {
				if (regexec(&preg, temp_buffer, 0, NULL, 0) == REG_NOMATCH)
					continue;
			}

			/* categorize log entry */
			if (strstr(temp_buffer, " starting..."))
				type = LOGENTRY_STARTUP;
			else if (strstr(temp_buffer, " shutting down..."))
				type = LOGENTRY_SHUTDOWN;
			else if (strstr(temp_buffer, "Bailing out"))
				type = LOGENTRY_BAILOUT;
			else if (strstr(temp_buffer, " restarting..."))
				type = LOGENTRY_RESTART;
			else if (strstr(temp_buffer, "HOST ALERT:") && strstr(temp_buffer, ";DOWN;"))
				type = LOGENTRY_HOST_DOWN;
			else if (strstr(temp_buffer, "HOST ALERT:") && strstr(temp_buffer, ";UNREACHABLE;"))
				type = LOGENTRY_HOST_UNREACHABLE;
			else if (strstr(temp_buffer, "HOST ALERT:") && strstr(temp_buffer, ";RECOVERY;"))
				type = LOGENTRY_HOST_RECOVERY;
			else if (strstr(temp_buffer, "HOST ALERT:") && strstr(temp_buffer, ";UP;"))
				type = LOGENTRY_HOST_UP;
			else if (strstr(temp_buffer, "HOST NOTIFICATION:"))
				type = LOGENTRY_HOST_NOTIFICATION;
			else if (strstr(temp_buffer, "SERVICE ALERT:") && strstr(temp_buffer, ";CRITICAL;"))
				type = LOGENTRY_SERVICE_CRITICAL;
			else if (strstr(temp_buffer, "SERVICE ALERT:") && strstr(temp_buffer, ";WARNING;"))
				type = LOGENTRY_SERVICE_WARNING;
			else if (strstr(temp_buffer, "SERVICE ALERT:") && strstr(temp_buffer, ";UNKNOWN;"))
				type = LOGENTRY_SERVICE_UNKNOWN;
			else if (strstr(temp_buffer, "SERVICE ALERT:") && strstr(temp_buffer, ";RECOVERY;"))
				type = LOGENTRY_SERVICE_RECOVERY;
			else if (strstr(temp_buffer, "SERVICE ALERT:") && strstr(temp_buffer, ";OK;"))
				type = LOGENTRY_SERVICE_OK;
			else if (strstr(temp_buffer, "SERVICE NOTIFICATION:"))
				type = LOGENTRY_SERVICE_NOTIFICATION;
			else if (strstr(temp_buffer, "SERVICE EVENT HANDLER:"))
				type = LOGENTRY_SERVICE_EVENT_HANDLER;
			else if (strstr(temp_buffer, "HOST EVENT HANDLER:"))
				type = LOGENTRY_HOST_EVENT_HANDLER;
			else if (strstr(temp_buffer, "EXTERNAL COMMAND:"))
				type = LOGENTRY_EXTERNAL_COMMAND;
			else if (strstr(temp_buffer, "PASSIVE SERVICE CHECK:"))
				type = LOGENTRY_PASSIVE_SERVICE_CHECK;
			else if (strstr(temp_buffer, "PASSIVE HOST CHECK:"))
				type = LOGENTRY_PASSIVE_HOST_CHECK;
			else if (strstr(temp_buffer, "LOG ROTATION:"))
				type = LOGENTRY_LOG_ROTATION;
			else if (strstr(temp_buffer, "active mode..."))
				type = LOGENTRY_ACTIVE_MODE;
			else if (strstr(temp_buffer, "standby mode..."))
				type = LOGENTRY_STANDBY_MODE;
			else if (strstr(temp_buffer, "SERVICE FLAPPING ALERT:") && strstr(temp_buffer, ";STARTED;"))
				type = LOGENTRY_SERVICE_FLAPPING_STARTED;
			else if (strstr(temp_buffer, "SERVICE FLAPPING ALERT:") && strstr(temp_buffer, ";STOPPED;"))
				type = LOGENTRY_SERVICE_FLAPPING_STOPPED;
			else if (strstr(temp_buffer, "SERVICE FLAPPING ALERT:") && strstr(temp_buffer, ";DISABLED;"))
				type = LOGENTRY_SERVICE_FLAPPING_DISABLED;
			else if (strstr(temp_buffer, "HOST FLAPPING ALERT:") && strstr(temp_buffer, ";STARTED;"))
				type = LOGENTRY_HOST_FLAPPING_STARTED;
			else if (strstr(temp_buffer, "HOST FLAPPING ALERT:") && strstr(temp_buffer, ";STOPPED;"))
				type = LOGENTRY_HOST_FLAPPING_STOPPED;
			else if (strstr(temp_buffer, "HOST FLAPPING ALERT:") && strstr(temp_buffer, ";DISABLED;"))
				type = LOGENTRY_HOST_FLAPPING_DISABLED;
			else if (strstr(temp_buffer, "SERVICE DOWNTIME ALERT:") && strstr(temp_buffer, ";STARTED;"))
				type = LOGENTRY_SERVICE_DOWNTIME_STARTED;
			else if (strstr(temp_buffer, "SERVICE DOWNTIME ALERT:") && strstr(temp_buffer, ";STOPPED;"))
				type = LOGENTRY_SERVICE_DOWNTIME_STOPPED;
			else if (strstr(temp_buffer, "SERVICE DOWNTIME ALERT:") && strstr(temp_buffer, ";CANCELLED;"))
				type = LOGENTRY_SERVICE_DOWNTIME_CANCELLED;
			else if (strstr(temp_buffer, "HOST DOWNTIME ALERT:") && strstr(temp_buffer, ";STARTED;"))
				type = LOGENTRY_HOST_DOWNTIME_STARTED;
			else if (strstr(temp_buffer, "HOST DOWNTIME ALERT:") && strstr(temp_buffer, ";STOPPED;"))
				type = LOGENTRY_HOST_DOWNTIME_STOPPED;
			else if (strstr(temp_buffer, "HOST DOWNTIME ALERT:") && strstr(temp_buffer, ";CANCELLED;"))
				type = LOGENTRY_HOST_DOWNTIME_CANCELLED;
			else if (strstr(temp_buffer, "INITIAL SERVICE STATE:"))
				type = LOGENTRY_SERVICE_INITIAL_STATE;
			else if (strstr(temp_buffer, "INITIAL HOST STATE:"))
				type = LOGENTRY_HOST_INITIAL_STATE;
			else if (strstr(temp_buffer, "CURRENT SERVICE STATE:"))
				type = LOGENTRY_SERVICE_CURRENT_STATE;
			else if (strstr(temp_buffer, "CURRENT HOST STATE:"))
				type = LOGENTRY_HOST_CURRENT_STATE;
			else if (strstr(temp_buffer, "error executing command"))
				type = LOGENTRY_ERROR_COMMAND_EXECUTION;
			else if (strstr(temp_buffer, "idomod:"))
				type = LOGENTRY_IDOMOD;
			else if (strstr(temp_buffer, "npcdmod:"))
				type = LOGENTRY_NPCDMOD;
			else if (strstr(temp_buffer, "Auto-save of"))
				type = LOGENTRY_AUTOSAVE;
			else if (strstr(temp_buffer, "Warning:"))
				type = LOGENTRY_SYSTEM_WARNING;
			else
				type = LOGENTRY_UNDEFINED;

			/* apply filters */
			if (*filter_list != NULL) {
				keep_entry = FALSE;
				for (temp_filter = *filter_list; temp_filter != NULL; temp_filter = temp_filter->next) {
					if (temp_filter->include != 0) {
						if (temp_filter->include == type) {
							keep_entry = TRUE;
							break;
						}
					} else if (temp_filter->exclude != 0) {
						if (temp_filter->exclude == type) {
							keep_entry = FALSE;
							break;
						} else
							keep_entry = TRUE;
					}
				}
				if (keep_entry == FALSE)
					continue;
			}

			/* initialzie */
			/* allocate memory for a new log entry */
			temp_entry = (logentry *)malloc(sizeof(logentry));
			if (temp_entry == NULL) {

				mmap_fclose(thefile);
				return READLOG_ERROR_MEMORY;
			}

			temp_entry->timestamp = 0L;
			temp_entry->type = 0;
			temp_entry->entry_text = NULL;
			temp_entry->next = NULL;


			temp_entry->timestamp = timestamp;
			temp_entry->type = type;
			temp_entry->entry_text = strdup(temp_buffer);

			if (reverse == TRUE) {
				if (*entry_list == NULL) {
					*entry_list = temp_entry;
					last_entry = *entry_list;
				} else {
					last_entry->next = temp_entry;
					last_entry = temp_entry;
				}
			} else {
				temp_entry->next = *entry_list;
				*entry_list = temp_entry;
			}
		}

#ifdef HAVE_ZLIB_H
		if (read_gzip_logs == TRUE && strstr(files[i].file_name, ".log.gz"))
			gzclose(gzfile);
		else
#endif
			mmap_fclose(thefile);
	}

	for (i=0; i< file_num;i++)
		my_free(files[i].file_name);

	if (search_string != NULL)
		regfree(&preg);

	return return_val;
}
static int setup_requirement_line(char *name)
{
    char *val[MAX_OPTIONS];
    char *prod = NULL;
    unsigned n, count;
    char *x;
    int invert = 0;

    if (!strncmp(name, "reject ", 7)) {
        name += 7;
        invert = 1;
    } else if (!strncmp(name, "require ", 8)) {
        name += 8;
        invert = 0;
    } else if (!strncmp(name, "require-for-product:", 20)) {
        // Get the product and point name past it
        prod = name + 20;
        name = strchr(name, ' ');
        if (!name) return -1;
        *name = 0;
        name += 1;
        invert = 0;
    }

    x = strchr(name, '=');
    if (x == 0) return 0;
    *x = 0;
    val[0] = x + 1;

    for(count = 1; count < MAX_OPTIONS; count++) {
        x = strchr(val[count - 1],'|');
        if (x == 0) break;
        *x = 0;
        val[count] = x + 1;
    }

    name = strip(name);
    for(n = 0; n < count; n++) val[n] = strip(val[n]);

    name = strip(name);
    if (name == 0) return -1;

    const char* var = name;
    // Work around an unfortunate name mismatch.
    if (!strcmp(name,"board")) var = "product";

    const char** out = reinterpret_cast<const char**>(malloc(sizeof(char*) * count));
    if (out == 0) return -1;

    for(n = 0; n < count; n++) {
        out[n] = strdup(strip(val[n]));
        if (out[n] == 0) {
            for(size_t i = 0; i < n; ++i) {
                free((char*) out[i]);
            }
            free(out);
            return -1;
        }
    }

    fb_queue_require(prod, var, invert, n, out);
    return 0;
}
Пример #8
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;
}
Пример #9
0
void display_notifications(void) {
    mmapfile *thefile=NULL;
    char *input=NULL;
    char *temp_buffer;
    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];
    int show_entry;
    int total_notifications;
    int notification_type=SERVICE_NOTIFICATION;
    int notification_detail_type=NOTIFICATION_SERVICE_CRITICAL;
    int odd=0;
    time_t t;
    host *temp_host;
    service *temp_service;
    int result;

    if(use_lifo==TRUE) {
        result=read_file_into_lifo(log_file_to_use);
        if(result!=LIFO_OK) {
            if(result==LIFO_ERROR_MEMORY) {
                printf("<P><DIV CLASS='warningMessage'>Not enough memory to reverse log file - displaying notifications in natural order...</DIV></P>");
            }
            else if(result==LIFO_ERROR_FILE) {
                printf("<P><DIV CLASS='errorMessage'>Error: Cannot open log file '%s' for reading!</DIV></P>",log_file_to_use);
                return;
            }
            use_lifo=FALSE;
        }
    }

    if(use_lifo==FALSE) {

        if((thefile=mmap_fopen(log_file_to_use))==NULL) {
            printf("<P><DIV CLASS='errorMessage'>Error: Cannot open log file '%s' for reading!</DIV></P>",log_file_to_use);
            return;
        }
    }

    printf("<p>\n");
    printf("<div align='center'>\n");

    printf("<table border=0 CLASS='notifications'>\n");
    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");

    total_notifications=0;

    while(1) {

        free(input);

        if(use_lifo==TRUE) {
            if((input=pop_lifo())==NULL)
                break;
        }
        else {
            if((input=mmap_fgets(thefile))==NULL)
                break;
        }

        strip(input);

        /* see if this line contains the notification event string */
        if(strstr(input,HOST_NOTIFICATION_STRING)||strstr(input,SERVICE_NOTIFICATION_STRING)) {

            if(strstr(input,HOST_NOTIFICATION_STRING))
                notification_type=HOST_NOTIFICATION;
            else
                notification_type=SERVICE_NOTIFICATION;

            /* get the date/time */
            temp_buffer=(char *)strtok(input,"]");
            t=(time_t)(temp_buffer==NULL)?0L:strtoul(temp_buffer+1,NULL,10);
            get_time_string(&t,date_time,(int)sizeof(date_time),SHORT_DATE_TIME);
            strip(date_time);

            /* get the contact name */
            temp_buffer=(char *)strtok(NULL,":");
            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 */
            if(notification_type==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(notification_type==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==FIND_CONTACT) {
                if(find_all==TRUE)
                    show_entry=TRUE;
                else if(!strcmp(query_contact_name,contact_name))
                    show_entry=TRUE;
            }

            else if(query_type==FIND_HOST) {
                if(find_all==TRUE)
                    show_entry=TRUE;
                else if(!strcmp(query_host_name,host_name))
                    show_entry=TRUE;
            }

            else if(query_type==FIND_SERVICE) {
                if(!strcmp(query_host_name,host_name) && !strcmp(query_svc_description,service_name))
                    show_entry=TRUE;
            }

            if(show_entry==TRUE) {
                if(notification_options==NOTIFICATION_ALL)
                    show_entry=TRUE;
                else if(notification_options==NOTIFICATION_HOST_ALL && notification_type==HOST_NOTIFICATION)
                    show_entry=TRUE;
                else if(notification_options==NOTIFICATION_SERVICE_ALL && notification_type==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 */
            if(notification_type==HOST_NOTIFICATION) {
                temp_host=find_host(host_name);
                if(is_authorized_for_host(temp_host,&current_authdata)==FALSE)
                    show_entry=FALSE;
            }
            else {
                temp_service=find_service(host_name,service_name);
                if(is_authorized_for_service(temp_service,&current_authdata)==FALSE)
                    show_entry=FALSE;
            }

            if(show_entry==TRUE) {

                total_notifications++;

                if(odd) {
                    odd=0;
                    printf("<tr CLASS='notificationsOdd'>\n");
                }
                else {
                    odd=1;
                    printf("<tr CLASS='notificationsEven'>\n");
                }
                printf("<td CLASS='notifications%s'><a href='%s?type=%d&host=%s'>%s</a></td>\n",(odd)?"Even":"Odd",EXTINFO_CGI,DISPLAY_HOST_INFO,url_encode(host_name),host_name);
                if(notification_type==SERVICE_NOTIFICATION) {
                    printf("<td CLASS='notifications%s'><a href='%s?type=%d&host=%s",(odd)?"Even":"Odd",EXTINFO_CGI,DISPLAY_SERVICE_INFO,url_encode(host_name));
                    printf("&service=%s'>%s</a></td>\n",url_encode(service_name),service_name);
                }
                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");
            }
        }
    }


    printf("</table>\n");

    printf("</div>\n");
    printf("</p>\n");

    if(total_notifications==0) {
        printf("<P><DIV CLASS='errorMessage'>No notifications have been recorded");
        if(find_all==FALSE) {
            if(query_type==FIND_SERVICE)
                printf(" for this service");
            else if(query_type==FIND_CONTACT)
                printf(" for this contact");
            else
                printf(" for this host");
        }
        printf(" in %s log file</DIV></P>",(log_archive==0)?"the current":"this archived");
    }

    free(input);

    if(use_lifo==TRUE)
        free_lifo_memory();
    else
        mmap_fclose(thefile);

    return;
}
Пример #10
0
   void RinexNavHeader::reallyGetRecord(FFStream& ffs) 
      throw(std::exception, FFStreamError, StringException)
   {
      RinexNavStream& strm = dynamic_cast<RinexNavStream&>(ffs);
      
         // if already read, just return
      if (strm.headerRead == true)
         return;
      
      valid = 0;
      
         // clear out anything that was unsuccessfully read the first
      commentList.clear();
      
      while (! (valid & endValid))
      {
         string line;
         strm.formattedGetLine(line);
         StringUtils::stripTrailing(line);

         if (line.length()==0) continue;
         else if (line.length()<60 || line.length()>80)
         {
            FFStreamError e("Invalid line length");
            GPSTK_THROW(e);
         }
         
         string thisLabel(line, 60, 20);
         
         if (thisLabel == versionString)
         {
            version = asDouble(line.substr(0,20));
            fileType = strip(line.substr(20,20));
            if ( (fileType[0] != 'N') &&
                 (fileType[0] != 'n'))
            {
               FFStreamError e("This isn't a Rinex Nav file");
               GPSTK_THROW(e);
            }
            valid |= versionValid;
         }
         else if (thisLabel == runByString)
         {
            fileProgram = strip(line.substr(0,20));
            fileAgency = strip(line.substr(20,20));
            date = strip(line.substr(40,20));
            valid |= runByValid;
         }
         else if (thisLabel == commentString)
         {
            commentList.push_back(strip(line.substr(0,60)));
            valid |= commentValid;
         }
         else if (thisLabel == ionAlphaString)
         {
            for(int i = 0; i < 4; i++)
               ionAlpha[i] = gpstk::StringUtils::for2doub(line.substr(2 + 12 * i,12));
            valid |= ionAlphaValid;
         }
         else if (thisLabel == ionBetaString)
         {
            for(int i = 0; i < 4; i++)
               ionBeta[i] = gpstk::StringUtils::for2doub(line.substr(2 + 12 * i,12));
            valid |= ionBetaValid;
         }
         else if (thisLabel == deltaUTCString)
         {
            A0 = gpstk::StringUtils::for2doub(line.substr(3,19));
            A1 = gpstk::StringUtils::for2doub(line.substr(22,19));
            UTCRefTime = asInt(line.substr(41,9));
            UTCRefWeek = asInt(line.substr(50,9));
            valid |= deltaUTCValid;
         }
         else if (thisLabel == leapSecondsString)
         {
            leapSeconds = asInt(line.substr(0,6));
            valid |= leapSecondsValid;
         }
         else if (thisLabel == endOfHeader)
         {
            valid |= endValid;
         }
         else
         {
            throw(FFStreamError("Unknown header label at line " + 
                                asString<size_t>(strm.lineNumber)));
         }
      }
      
      unsigned long allValid;
      if      (version == 2.0)      allValid = allValid20;
      else if (version == 2.1)      allValid = allValid21;
      else if (version == 2.11)     allValid = allValid211;
      else
      {
         FFStreamError e("Unknown or unsupported RINEX version " + 
                         asString(version));
         GPSTK_THROW(e);
      }
      
      if ( (allValid & valid) != allValid)
      {
         FFStreamError e("Incomplete or invalid header");
         GPSTK_THROW(e);               
      }            
      
         // we got here, so something must be right...
      strm.header = *this;
      strm.headerRead = true;      
   }
Пример #11
0
uint32_t transfer(char **arguments, assembler *instState,table_t *t){
 int P_Bit;
 char *Rd = arguments[0];
 char *address = arguments[1];
 uint32_t rd = getConst(Rd);
 int addrlen = strlen(address);

 if(*address == '='){
  //numeric constant;
  int val = getConst(address);

  if(val <= 0xFF){
   //mov instruction;
   isMov = 1;
   char **inst = malloc(sizeof(char*)*3);
   for(int i=0; i<3; i++){
	inst[i] = malloc(sizeof(char)*20);
   }
   strcpy(inst[0],"mov");
   strcpy(inst[1],Rd);
   strcpy(inst[2],(address+1));
   inst[2] = prepend(inst[2],'#');
   return ass_data_process(inst,t);

  }else{
   strip(arguments[1]);
   insertExpression(instState->BigVals,arguments[1],val,instState->counter);
   rd <<= 12;
   uint32_t val_mask = 0xE59F0000;
   return val_mask | rd;

  }
 }
 char **splitAddress = tokeniser(address,",");

 if(address[0] == '[' && address[4] != ']' && address[3] != ']'){
  //PRE instruction;
  P_Bit = 1;
  char *pre_address = removeBrackets(address);
  char **expression = tokeniser(pre_address,".");
  uint32_t rn = getConst(expression[0]);
  uint32_t transfer_mask1 = 0xE5900000;
  uint32_t incVal = getConst(expression[1]);
  uint32_t offset = incVal; //TODO: ONCE MOV is fixed replace this with the val generated by mov
  rn <<= 16;
  rd <<= 12;
  return transfer_mask1 | rn | rd | offset;

 }else if(addrlen <= 5){
  //PRE instruction;
  P_Bit = 1;
  char *Rn = removeBrackets(splitAddress[0]);
  uint32_t rn = getConst(Rn);
  uint32_t transfer_mask2 = 0xE5900000;
  rn <<= 16;
  rd <<= 12;
  return transfer_mask2 | rn | rd;

 }else{
  //Post instruction;
  P_Bit = 0;
  uint32_t transfer_mask3 = 0xE6900000;
  char **expression = tokeniser(address,".");
  uint32_t rn = getConst(removeBrackets(expression[0]));
  uint32_t offset = getConst(expression[1]);
  rn <<= 16;
  rd <<= 12;
  return transfer_mask3 | rn | rd | offset;
 }
}
Пример #12
0
/* tw_result():
 *	Return what the completion action should be depending on the
 *	string
 */
static int
tw_result(const Char *act, Char **pat)
{
    int looking;
    static Char* res = NULL;
    Char *p;

    if (res != NULL)
	xfree(res), res = NULL;

    switch (act[0] & ~QUOTE) {
    case 'X':
	looking = TW_COMPLETION;
	break;
    case 'S':
	looking = TW_SIGNAL;
	break;
    case 'a':
	looking = TW_ALIAS;
	break;
    case 'b':
	looking = TW_BINDING;
	break;
    case 'c':
	looking = TW_COMMAND;
	break;
    case 'C':
	looking = TW_PATH | TW_COMMAND;
	break;
    case 'd':
	looking = TW_DIRECTORY;
	break;
    case 'D':
	looking = TW_PATH | TW_DIRECTORY;
	break;
    case 'e':
	looking = TW_ENVVAR;
	break;
    case 'f':
	looking = TW_FILE;
	break;
#ifdef COMPAT
    case 'p':
#endif /* COMPAT */
    case 'F':
	looking = TW_PATH | TW_FILE;
	break;
    case 'g':
	looking = TW_GRPNAME;
	break;
    case 'j':
	looking = TW_JOB;
	break;
    case 'l':
	looking = TW_LIMIT;
	break;
    case 'n':
	looking = TW_NONE;
	break;
    case 's':
	looking = TW_SHELLVAR;
	break;
    case 't':
	looking = TW_TEXT;
	break;
    case 'T':
	looking = TW_PATH | TW_TEXT;
	break;
    case 'v':
	looking = TW_VARIABLE;
	break;
    case 'u':
	looking = TW_USER;
	break;
    case 'x':
	looking = TW_EXPLAIN;
	break;

    case '$':
	*pat = res = Strsave(&act[1]);
	(void) strip(res);
	return(TW_VARLIST);

    case '(':
	*pat = res = Strsave(&act[1]);
	if ((p = Strchr(res, ')')) != NULL)
	    *p = '\0';
	(void) strip(res);
	return TW_WORDLIST;

    case '`':
	res = Strsave(act);
	if ((p = Strchr(&res[1], '`')) != NULL)
	    *++p = '\0';
	
	if (didfds == 0) {
	    /*
	     * Make sure that we have some file descriptors to
	     * play with, so that the processes have at least 0, 1, 2
	     * open
	     */
	    (void) dcopy(SHIN, 0);
	    (void) dcopy(SHOUT, 1);
	    (void) dcopy(SHDIAG, 2);
	}
	if ((p = globone(res, G_APPEND)) != NULL) {
	    xfree(res), res = NULL;
	    *pat = res = Strsave(p);
	    xfree(p);
	    return TW_WORDLIST;
	}
	return TW_ZERO;

    default:
	stderror(ERR_COMPCOM, short2str(act));
	return TW_ZERO;
    }

    switch (act[1] & ~QUOTE) {
    case '\0':
	return looking;

    case ':':
	*pat = res = Strsave(&act[2]);
	(void) strip(res);
	return looking;

    default:
	stderror(ERR_COMPCOM, short2str(act));
	return TW_ZERO;
    }
} /* end tw_result */
Пример #13
0
URI::URI(const QString& other):QString()
   ,m_Parsed(false),m_HeaderType(SchemeType::NONE)
{
   m_Stripped                     = strip(other,m_HeaderType);
   (*static_cast<QString*>(this)) = m_Stripped               ;
}
Пример #14
0
static BOOL loadConfig(char *file, GRABBER **grabbers, int *countGrabbers)
{
	FILE *config;
	config = fopen(file,"r");

	if(config)
	{
		char buffer[512], param[256], value[256], *comment;
		int e;

		e = 0;
		while(fgets(buffer,sizeof(buffer),config))
		{
			uncomment(buffer);
			sscanf(buffer,"%[^=]=%[^=]",param,value);
			strip(param);

			if(!stricmp(param,"grabberid")) e++;
		}

		*grabbers = (GRABBER *) calloc(e, sizeof(GRABBER));

		rewind(config);

		e = -1;
		while(fgets(buffer,sizeof(buffer),config))
		{
			uncomment(buffer);
			sscanf(buffer,"%[^=]=%[^=]",param,value);
			strip(param);
			strip(value);

			if(!stricmp(param,"grabberid"))
			{
				e++;
				strcpy((*grabbers)[e].id, value);
			}
			else if(e >=0)
			{
				if(!stricmp(param,"grabberexe"))
					strcpy((*grabbers)[e].exe, value);
				else if(!stricmp(param,"grabbertype"))
				{
					if(!stricmp(value,"win32os2"))
						(*grabbers)[e].type = WIN32OS2;
					else if(!stricmp(value,"vio"))
						(*grabbers)[e].type = VIO;
					else if(!stricmp(value,"vdm"))
						(*grabbers)[e].type = VDM;
				}
				else if(!stricmp(param,"grabberin"))
					strcpy((*grabbers)[e].input, value);
				else if(!stricmp(param,"grabberout"))
					strcpy((*grabbers)[e].output, value);
				else if(!stricmp(param,"grabbermangling"))
					strcpy((*grabbers)[e].mangling, value);
				else if(!stricmp(param,"grabberbefore"))
					strcpy((*grabbers)[e].before, value);
				else if(!stricmp(param,"grabberafter"))
					strcpy((*grabbers)[e].after, value);
				else if(!stricmp(param,"grabberacceptsoutput"))
				{
					if(!stricmp(value,"true"))
						(*grabbers)[e].acceptsOutput = TRUE;
					else
						(*grabbers)[e].acceptsOutput = FALSE;
				}
				else if(!stricmp(param,"grabbernodrive"))
				{
					if(!stricmp(value,"true"))
						(*grabbers)[e].noDrive = TRUE;
					else
						(*grabbers)[e].noDrive = FALSE;
				}
			}
		}
		*countGrabbers = e+1;

		fclose(config);
		return TRUE;
	}
	return FALSE;
}
Пример #15
0
static int conf_choice(struct menu *menu)
{
	struct symbol *sym, *def_sym;
	struct menu *child;
	bool is_new;

	sym = menu->sym;
	is_new = !sym_has_value(sym);
	if (sym_is_changable(sym)) {
		conf_sym(menu);
		sym_calc_value(sym);
		switch (sym_get_tristate_value(sym)) {
		case no:
			return 1;
		case mod:
			return 0;
		case yes:
			break;
		}
	} else {
		switch (sym_get_tristate_value(sym)) {
		case no:
			return 1;
		case mod:
			printf("%*s%s\n", indent - 1, "", _(menu_get_prompt(menu)));
			return 0;
		case yes:
			break;
		}
	}

	while (1) {
		int cnt, def;

		printf("%*s%s\n", indent - 1, "", _(menu_get_prompt(menu)));
		def_sym = sym_get_choice_value(sym);
		cnt = def = 0;
		line[0] = 0;
		for (child = menu->list; child; child = child->next) {
			if (!menu_is_visible(child))
				continue;
			if (!child->sym) {
				printf("%*c %s\n", indent, '*', _(menu_get_prompt(child)));
				continue;
			}
			cnt++;
			if (child->sym == def_sym) {
				def = cnt;
				printf("%*c", indent, '>');
			} else
				printf("%*c", indent, ' ');
			printf(" %d. %s", cnt, _(menu_get_prompt(child)));
			if (child->sym->name)
				printf(" (%s)", child->sym->name);
			if (!sym_has_value(child->sym))
				printf(_(" (NEW)"));
			printf("\n");
		}
		printf(_("%*schoice"), indent - 1, "");
		if (cnt == 1) {
			printf("[1]: 1\n");
			goto conf_childs;
		}
		printf("[1-%d", cnt);
		if (menu_has_help(menu))
			printf("?");
		printf("]: ");
		switch (input_mode) {
		case oldconfig:
		case silentoldconfig:
			if (!is_new) {
				cnt = def;
				printf("%d\n", cnt);
				break;
			}
			check_stdin();
			/* fall through */
		case oldaskconfig:
			fflush(stdout);
			xfgets(line, 128, stdin);
			strip(line);
			if (line[0] == '?') {
				print_help(menu);
				continue;
			}
			if (!line[0])
				cnt = def;
			else if (isdigit(line[0]))
				cnt = atoi(line);
			else
				continue;
			break;
		default:
			break;
		}

	conf_childs:
		for (child = menu->list; child; child = child->next) {
			if (!child->sym || !menu_is_visible(child))
				continue;
			if (!--cnt)
				break;
		}
		if (!child)
			continue;
		if (line[0] && line[strlen(line) - 1] == '?') {
			print_help(child);
			continue;
		}
		sym_set_choice_value(sym, child->sym);
		for (child = child->list; child; child = child->next) {
			indent += 2;
			conf(child);
			indent -= 2;
		}
		return 1;
	}
}
Пример #16
0
static void
setDolp(Char *cp)
{
    Char *dp;
    size_t i;

    if (dolmod.len == 0 || dolmcnt == 0) {
	dolp = cp;
	return;
    }
    cp = Strsave(cp);
    for (i = 0; i < dolmod.len; i++) {
	int didmod = 0;

	/* handle s// [eichin:19910926.0510EST] */
	if(dolmod.s[i] == 's') {
	    Char delim;
	    Char *lhsub, *rhsub, *np;
	    size_t lhlen = 0, rhlen = 0;

	    delim = dolmod.s[++i];
	    if (!delim || letter(delim)
		|| Isdigit(delim) || any(" \t\n", delim)) {
		seterror(ERR_BADSUBST);
		break;
	    }
	    lhsub = &dolmod.s[++i];
	    while(dolmod.s[i] != delim && dolmod.s[++i]) {
		lhlen++;
	    }
	    dolmod.s[i] = 0;
	    rhsub = &dolmod.s[++i];
	    while(dolmod.s[i] != delim && dolmod.s[++i]) {
		rhlen++;
	    }
	    dolmod.s[i] = 0;

	    strip(lhsub);
	    strip(rhsub);
	    strip(cp);
	    dp = cp;
	    do {
		dp = Strstr(dp, lhsub);
		if (dp) {
		    ptrdiff_t diff = dp - cp;
		    size_t len = (Strlen(cp) + 1 - lhlen + rhlen);
		    np = xmalloc(len * sizeof(Char));
		    (void) Strncpy(np, cp, diff);
		    (void) Strcpy(np + diff, rhsub);
		    (void) Strcpy(np + diff + rhlen, dp + lhlen);

		    xfree(cp);
		    dp = cp = np;
		    cp[--len] = '\0';
		    didmod = 1;
		    if (diff >= (ssize_t)len)
			break;
		} else {
		    /* should this do a seterror? */
		    break;
		}
	    }
	    while (dol_flag_a != 0);
	    /*
	     * restore dolmod for additional words
	     */
	    dolmod.s[i] = rhsub[-1] = (Char) delim;
        } else {

	    do {
		if ((dp = domod(cp, dolmod.s[i])) != NULL) {
		    didmod = 1;
		    if (Strcmp(cp, dp) == 0) {
			xfree(cp);
			cp = dp;
			break;
		    }
		    else {
			xfree(cp);
			cp = dp;
		    }
		}
		else
		    break;
	    }
	    while (dol_flag_a != 0);
	}
	if (didmod && dolmcnt != INT_MAX)
	    dolmcnt--;
#ifdef notdef
	else
	    break;
#endif
    }

    addla(cp);

    dolp = STRNULL;
    if (seterr)
	stderror(ERR_OLD);
}
std::vector< std::string > paranthetical_split(std::string const &val,
        const char separator, std::string const &left,
        std::string const &right,int flags)
{
    std::vector< std::string > res;
    std::vector<char> part;
    bool in_paranthesis = false;

    std::string::const_iterator i1 = val.begin();
    std::string::const_iterator i2 = val.begin();

    std::string lp=left;
    std::string rp=right;

    if(left.size()!=right.size()) {
        ERR_GENERAL << "Left and Right Parenthesis lists not same length\n";
        return res;
    }

    while (i2 != val.end()) {
        if(!in_paranthesis && separator && *i2 == separator) {
            std::string new_val(i1, i2);
            if (flags & STRIP_SPACES)
                strip(new_val);
            if (!(flags & REMOVE_EMPTY) || !new_val.empty())
                res.push_back(new_val);
            ++i2;
            if (flags & STRIP_SPACES) {
                while (i2 != val.end() && *i2 == ' ')
                    ++i2;
            }
            i1=i2;
            continue;
        }
        if(!part.empty() && *i2 == part.back()) {
            part.pop_back();
            if(!separator && part.empty()) {
                std::string new_val(i1, i2);
                if (flags & STRIP_SPACES)
                    strip(new_val);
                res.push_back(new_val);
                ++i2;
                i1=i2;
            } else {
                if (part.empty())
                    in_paranthesis = false;
                ++i2;
            }
            continue;
        }
        bool found=false;
        for(size_t i=0; i < lp.size(); i++) {
            if (*i2 == lp[i]) {
                if (!separator && part.empty()) {
                    std::string new_val(i1, i2);
                    if (flags & STRIP_SPACES)
                        strip(new_val);
                    res.push_back(new_val);
                    ++i2;
                    i1=i2;
                } else {
                    ++i2;
                }
                part.push_back(rp[i]);
                found=true;
                break;
            }
        }
        if(!found) {
            ++i2;
        } else
            in_paranthesis = true;
    }

    std::string new_val(i1, i2);
    if (flags & STRIP_SPACES)
        strip(new_val);
    if (!(flags & REMOVE_EMPTY) || !new_val.empty())
        res.push_back(new_val);

    if(!part.empty()) {
        ERR_GENERAL << "Mismatched paranthesis:\n"<<val<<"\n";;
    }

    return res;
}
Пример #18
0
int main(int argc, char * argv[])
{
  char * filename;
  char * basedir;
  FILE *fd;
  char line[PATH_MAX];

  if (argc < 3) {
    fprintf(stderr, "Usage: trFilelist synclist_filename basedir\n");
    exit(-1);
  }

  filename = argv[1];
  basedir = argv[2];

  init_string_list(&file_list, 10);
  init_uint_list(&ino_list, 10);
  init_string_list(&dir_list, 100);
  init_string_list(&softlink_list, 10);
  init_string_list(&newdir_list, 100);

  get_dir_softlinks(filename, basedir);
  
  if ((fd = fopen(filename, "r")) == NULL) {
    fprintf(stderr, "Cannot open file -- %s \n", filename);
    return -1;
  }

  while (1) { /* for each line in the file */
    char *pc;
    char fn[PATH_MAX];
    struct stat st;
    int newdir_flag;

    if (fgets(line, PATH_MAX, fd)==NULL) break;
    strip(line);
    if (strlen(line) == 0) continue; /* skip blank line */
    if (strcmp(line, ".")==0) continue;
    if (strcmp(line, "./")==0) continue;

    /* first we look for deleting entry */
    if (strncmp(line, "deleting ", 9)==0) {
      /* deleting (directory) file_path */
      char * p1, *p2, *pf;

      p1 = strstr(line, " "); /* the first space */
      p2 = strstr(p1+1, " "); /* deleting directory filepath * 20070912 this is old */ 
      pf = (p2) ? p2+1 : p1+1;/* it's always p1+1 */

      newdir_flag = has_newdir(pf, &newdir_list);

      if ((has_sub_string(pf, &softlink_list)<0) && newdir_flag<0) { 
	/* see comments above get_dir_softlinks() */
	printf("deleting %s\n", pf);
      } else if (newdir_flag>=0) { /* temporary action */
	/*** we can simply skip this block later. 20070912 ***/	   
	/***/
	fprintf(stderr, "CRITICAL ERROR: An old softlink has been changed to a directory!\n");
	fprintf(stderr, "                For now, we crash this code for human intervention\n");
	fprintf(stderr, "                line= %s\n", line);
	exit(-1);
	/***/
      }

      continue;
    }
    
    /* the softlink case is indicated by -> */
    pc= strstr(line, " -> ");
    if (pc) {
      *pc = '\0';
      output_subs(line);
      printf("%s\n", line);
      continue;
    }

    /* if rsync's -H is turned on, the output may contain
       file => tar_hardlink_file (relative address)
    */
    pc= strstr(line, " => ");
    if (pc) {
      *pc = '\0';
      output_subs(line);
      printf("%s %s\n", line, pc+4);
      continue;
    }

    /* the rest of the entries should be valid paths */
    sprintf(fn, "%s/%s", basedir, line);    
    if (lstat(fn, &st)<0) continue; /* We skip this bad entry - 
				       (1) the header and tail lines
				       (2) perhaps the file no longer exists */

    /* is this a hardlink? */
    if (st.st_nlink > 1) {
      int index;
      output_subs(line);
      if ((index = find_unit((unsigned int)st.st_ino, &ino_list))<0) { 
	append_uint_list((unsigned int)st.st_ino, &ino_list);
	append_string_list(line, &file_list); /* relative path */
	printf("%s\n", line);
      } else {
	printf("%s %s\n", line, file_list.str[index]);
      }
      continue;
    }

    /* all others */
    output_subs(line);
    printf("%s\n", line);
  } /* end of one line */

  fclose(fd);
  return 0;
}
Пример #19
0
int
main (int argc, char **argv)
{
	short supports_tls=FALSE;
	int n = 0;
	double elapsed_time;
	long microsec;
	int result = STATE_UNKNOWN;
	char *cmd_str = NULL;
	char *helocmd = NULL;
	char *error_msg = "";
	struct timeval tv;

	/* Catch pipe errors in read/write - sometimes occurs when writing QUIT */
	(void) signal (SIGPIPE, SIG_IGN);

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

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

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

	/* If localhostname not set on command line, use gethostname to set */
	if(! localhostname){
		localhostname = malloc (HOST_MAX_BYTES);
		if(!localhostname){
			printf(_("malloc() failed!\n"));
			return STATE_CRITICAL;
		}
		if(gethostname(localhostname, HOST_MAX_BYTES)){
			printf(_("gethostname() failed!\n"));
			return STATE_CRITICAL;
		}
	}
	if(use_ehlo)
		xasprintf (&helocmd, "%s%s%s", SMTP_EHLO, localhostname, "\r\n");
	else
		xasprintf (&helocmd, "%s%s%s", SMTP_HELO, localhostname, "\r\n");

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

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

	if (verbose && send_mail_from)
		printf ("FROM CMD: %s", cmd_str);

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

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

	/* start timer */
	gettimeofday (&tv, NULL);

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

	if (result == STATE_OK) { /* we connected */

		/* watch for the SMTP connection string and */
		/* return a WARNING status if we couldn't read any data */
		if (recvlines(buffer, MAX_INPUT_BUFFER) <= 0) {
			printf (_("recv() failed\n"));
			return STATE_WARNING;
		}
		else {
			if (verbose)
				printf ("%s", buffer);
			/* strip the buffer of carriage returns */
			strip (buffer);
			/* make sure we find the response we are looking for */
			if (!strstr (buffer, server_expect)) {
				if (server_port == SMTP_PORT)
					printf (_("Invalid SMTP response received from host: %s\n"), buffer);
				else
					printf (_("Invalid SMTP response received from host on port %d: %s\n"),
									server_port, buffer);
				return STATE_WARNING;
			}
		}

		/* send the HELO/EHLO command */
		send(sd, helocmd, strlen(helocmd), 0);

		/* allow for response to helo command to reach us */
		if (recvlines(buffer, MAX_INPUT_BUFFER) <= 0) {
			printf (_("recv() failed\n"));
			return STATE_WARNING;
		} else if(use_ehlo){
			if(strstr(buffer, "250 STARTTLS") != NULL ||
			   strstr(buffer, "250-STARTTLS") != NULL){
				supports_tls=TRUE;
			}
		}

		if(use_ssl && ! supports_tls){
			printf(_("WARNING - TLS not supported by server\n"));
			smtp_quit();
			return STATE_WARNING;
		}

#ifdef HAVE_SSL
		if(use_ssl) {
		  /* send the STARTTLS command */
		  send(sd, SMTP_STARTTLS, strlen(SMTP_STARTTLS), 0);

		  recvlines(buffer, MAX_INPUT_BUFFER); /* wait for it */
		  if (!strstr (buffer, server_expect)) {
		    printf (_("Server does not support STARTTLS\n"));
		    smtp_quit();
		    return STATE_UNKNOWN;
		  }
		  result = np_net_ssl_init(sd);
		  if(result != STATE_OK) {
		    printf (_("CRITICAL - Cannot create SSL context.\n"));
		    np_net_ssl_cleanup();
		    close(sd);
		    return STATE_CRITICAL;
		  } else {
			ssl_established = 1;
		  }

		/*
		 * Resend the EHLO command.
		 *
		 * RFC 3207 (4.2) says: ``The client MUST discard any knowledge
		 * obtained from the server, such as the list of SMTP service
		 * extensions, which was not obtained from the TLS negotiation
		 * itself.  The client SHOULD send an EHLO command as the first
		 * command after a successful TLS negotiation.''  For this
		 * reason, some MTAs will not allow an AUTH LOGIN command before
		 * we resent EHLO via TLS.
		 */
		if (my_send(helocmd, strlen(helocmd)) <= 0) {
			printf("%s\n", _("SMTP UNKNOWN - Cannot send EHLO command via TLS."));
			my_close();
			return STATE_UNKNOWN;
		}
		if (verbose)
			printf(_("sent %s"), helocmd);
		if ((n = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) {
			printf("%s\n", _("SMTP UNKNOWN - Cannot read EHLO response via TLS."));
			my_close();
			return STATE_UNKNOWN;
		}
		if (verbose) {
			printf("%s", buffer);
		}

#  ifdef USE_OPENSSL
		  if ( check_cert ) {
                    result = np_net_ssl_check_cert(days_till_exp_warn, days_till_exp_crit);
		    my_close();
		    return result;
		  }
#  endif /* USE_OPENSSL */
		}
#endif

		if (send_mail_from) {
		  my_send(cmd_str, strlen(cmd_str));
		  if (recvlines(buffer, MAX_INPUT_BUFFER) >= 1 && verbose)
		    printf("%s", buffer);
		}

		while (n < ncommands) {
			xasprintf (&cmd_str, "%s%s", commands[n], "\r\n");
			my_send(cmd_str, strlen(cmd_str));
			if (recvlines(buffer, MAX_INPUT_BUFFER) >= 1 && verbose)
				printf("%s", buffer);
			strip (buffer);
			if (n < nresponses) {
				cflags |= REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
				errcode = regcomp (&preg, responses[n], cflags);
				if (errcode != 0) {
					regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER);
					printf (_("Could Not Compile Regular Expression"));
					return ERROR;
				}
				excode = regexec (&preg, buffer, 10, pmatch, eflags);
				if (excode == 0) {
					result = STATE_OK;
				}
				else if (excode == REG_NOMATCH) {
					result = STATE_WARNING;
					printf (_("SMTP %s - Invalid response '%s' to command '%s'\n"), state_text (result), buffer, commands[n]);
				}
				else {
					regerror (excode, &preg, errbuf, MAX_INPUT_BUFFER);
					printf (_("Execute Error: %s\n"), errbuf);
					result = STATE_UNKNOWN;
				}
			}
			n++;
		}

		if (authtype != NULL) {
			if (strcmp (authtype, "LOGIN") == 0) {
				char *abuf;
				int ret;
				do {
					if (authuser == NULL) {
						result = STATE_CRITICAL;
						xasprintf(&error_msg, _("no authuser specified, "));
						break;
					}
					if (authpass == NULL) {
						result = STATE_CRITICAL;
						xasprintf(&error_msg, _("no authpass specified, "));
						break;
					}

					/* send AUTH LOGIN */
					my_send(SMTP_AUTH_LOGIN, strlen(SMTP_AUTH_LOGIN));
					if (verbose)
						printf (_("sent %s\n"), "AUTH LOGIN");

					if ((ret = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) {
						xasprintf(&error_msg, _("recv() failed after AUTH LOGIN, "));
						result = STATE_WARNING;
						break;
					}
					if (verbose)
						printf (_("received %s\n"), buffer);

					if (strncmp (buffer, "334", 3) != 0) {
						result = STATE_CRITICAL;
						xasprintf(&error_msg, _("invalid response received after AUTH LOGIN, "));
						break;
					}

					/* encode authuser with base64 */
					base64_encode_alloc (authuser, strlen(authuser), &abuf);
					xasprintf(&abuf, "%s\r\n", abuf);
					my_send(abuf, strlen(abuf));
					if (verbose)
						printf (_("sent %s\n"), abuf);

					if ((ret = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) {
						result = STATE_CRITICAL;
						xasprintf(&error_msg, _("recv() failed after sending authuser, "));
						break;
					}
					if (verbose) {
						printf (_("received %s\n"), buffer);
					}
					if (strncmp (buffer, "334", 3) != 0) {
						result = STATE_CRITICAL;
						xasprintf(&error_msg, _("invalid response received after authuser, "));
						break;
					}
					/* encode authpass with base64 */
					base64_encode_alloc (authpass, strlen(authpass), &abuf);
					xasprintf(&abuf, "%s\r\n", abuf);
					my_send(abuf, strlen(abuf));
					if (verbose) {
						printf (_("sent %s\n"), abuf);
					}
					if ((ret = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) {
						result = STATE_CRITICAL;
						xasprintf(&error_msg, _("recv() failed after sending authpass, "));
						break;
					}
					if (verbose) {
						printf (_("received %s\n"), buffer);
					}
					if (strncmp (buffer, "235", 3) != 0) {
						result = STATE_CRITICAL;
						xasprintf(&error_msg, _("invalid response received after authpass, "));
						break;
					}
					break;
				} while (0);
			} else {
				result = STATE_CRITICAL;
				xasprintf(&error_msg, _("only authtype LOGIN is supported, "));
			}
		}

		/* tell the server we're done */
		smtp_quit();

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

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

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

	if (result == STATE_OK) {
		if (check_critical_time && elapsed_time > critical_time)
			result = STATE_CRITICAL;
		else if (check_warning_time && elapsed_time > warning_time)
			result = STATE_WARNING;
	}

	printf (_("SMTP %s - %s%.3f sec. response time%s%s|%s\n"),
			state_text (result),
			error_msg,
			elapsed_time,
			verbose?", ":"", verbose?buffer:"",
			fperfdata ("time", elapsed_time, "s",
				(int)check_warning_time, warning_time,
				(int)check_critical_time, critical_time,
				TRUE, 0, FALSE, 0));

	return result;
}
Пример #20
0
/* processes a single directive */
int xpddefault_grab_config_directives(char *input) {
    char *temp_ptr = NULL;
    char *varname = NULL;
    char *varvalue = NULL;

    /* get the variable name */
    if ((temp_ptr = my_strtok(input, "=")) == NULL)
        return ERROR;
    if ((varname = (char *)strdup(temp_ptr)) == NULL)
        return ERROR;

    /* get the variable value */
    if ((temp_ptr = my_strtok(NULL, "\n")) == NULL) {
        my_free(varname);
        return ERROR;
    }
    if ((varvalue = (char *)strdup(temp_ptr)) == NULL) {
        my_free(varname);
        return ERROR;
    }

    if (!strcmp(varname, "perfdata_timeout")) {
        strip(varvalue);
        xpddefault_perfdata_timeout = atoi(varvalue);
    }

    else if (!strcmp(varname, "host_perfdata_command"))
        xpddefault_host_perfdata_command = (char *)strdup(varvalue);

    else if (!strcmp(varname, "service_perfdata_command"))
        xpddefault_service_perfdata_command = (char *)strdup(varvalue);

    else if (!strcmp(varname, "host_perfdata_file_template"))
        xpddefault_host_perfdata_file_template = (char *)strdup(varvalue);

    else if (!strcmp(varname, "service_perfdata_file_template"))
        xpddefault_service_perfdata_file_template = (char *)strdup(varvalue);

    else if (!strcmp(varname, "host_perfdata_file"))
        xpddefault_host_perfdata_file = (char *)strdup(varvalue);

    else if (!strcmp(varname, "service_perfdata_file"))
        xpddefault_service_perfdata_file = (char *)strdup(varvalue);

    else if (!strcmp(varname, "host_perfdata_file_mode")) {
        xpddefault_host_perfdata_file_pipe = FALSE;

        if (strstr(varvalue, "p") != NULL)
            xpddefault_host_perfdata_file_pipe = TRUE;
        else if (strstr(varvalue, "w") != NULL)
            xpddefault_host_perfdata_file_append = FALSE;
        else
            xpddefault_host_perfdata_file_append = TRUE;
    }

    else if (!strcmp(varname, "service_perfdata_file_mode")) {
        xpddefault_service_perfdata_file_pipe = FALSE;

        if (strstr(varvalue, "p") != NULL)
            xpddefault_service_perfdata_file_pipe = TRUE;
        else if (strstr(varvalue, "w") != NULL)
            xpddefault_service_perfdata_file_append = FALSE;
        else
            xpddefault_service_perfdata_file_append = TRUE;
    }

    else if (!strcmp(varname, "host_perfdata_file_processing_interval"))
        xpddefault_host_perfdata_file_processing_interval = strtoul(varvalue, NULL, 0);

    else if (!strcmp(varname, "service_perfdata_file_processing_interval"))
        xpddefault_service_perfdata_file_processing_interval = strtoul(varvalue, NULL, 0);

    else if (!strcmp(varname, "host_perfdata_file_processing_command"))
        xpddefault_host_perfdata_file_processing_command = (char *)strdup(varvalue);

    else if (!strcmp(varname, "service_perfdata_file_processing_command"))
        xpddefault_service_perfdata_file_processing_command = (char *)strdup(varvalue);

    else if (!strcmp(varname, "host_perfdata_process_empty_results"))
        xpddefault_host_perfdata_process_empty_results = (atoi(varvalue) > 0) ? TRUE : FALSE;

    else if (!strcmp(varname, "service_perfdata_process_empty_results"))
        xpddefault_service_perfdata_process_empty_results = (atoi(varvalue) > 0) ? TRUE : FALSE;

    /* free memory */
    my_free(varname);
    my_free(varvalue);

    return OK;
}
Пример #21
0
static int
telsnd(void)
{
    int tcc;
    int count;
    int returnValue = 0;
    unsigned char *tbp;

    tcc = 0;
    count = 0;
    while (NETROOM() > 2) {
	int sc;
	int c;

	if (tcc == 0) {
	    if (count) {
		ring_consumed(&ttyiring, count);
		returnValue = 1;
		count = 0;
	    }
	    tbp = ttyiring.consume;
	    tcc = ring_full_consecutive(&ttyiring);
	    if (tcc == 0) {
		break;
	    }
	}
	c = *tbp++ & 0xff, sc = strip(c), tcc--; count++;
	if (rlogin != _POSIX_VDISABLE) {
		if (bol) {
			bol = 0;
			if (sc == rlogin) {
				local = 1;
				continue;
			}
		} else if (local) {
			local = 0;
			if (sc == '.' || c == termEofChar) {
				bol = 1;
				command(0, "close\n", 6);
				continue;
			}
			if (sc == termSuspChar) {
				bol = 1;
				command(0, "z\n", 2);
				continue;
			}
			if (sc == escape) {
				command(0, (char *)tbp, tcc);
				bol = 1;
				count += tcc;
				tcc = 0;
				flushline = 1;
				break;
			}
			if (sc != rlogin) {
				++tcc;
				--tbp;
				--count;
				c = sc = rlogin;
			}
		}
		if ((sc == '\n') || (sc == '\r'))
			bol = 1;
	} else if (escape != _POSIX_VDISABLE && sc == escape) {
	    /*
	     * Double escape is a pass through of a single escape character.
	     */
	    if (tcc && strip(*tbp) == escape) {
		tbp++;
		tcc--;
		count++;
		bol = 0;
	    } else {
		command(0, (char *)tbp, tcc);
		bol = 1;
		count += tcc;
		tcc = 0;
		flushline = 1;
		break;
	    }
	} else
	    bol = 0;
#ifdef	KLUDGELINEMODE
	if (kludgelinemode && (globalmode&MODE_EDIT) && (sc == echoc)) {
	    if (tcc > 0 && strip(*tbp) == echoc) {
		tcc--; tbp++; count++;
	    } else {
		dontlecho = !dontlecho;
		settimer(echotoggle);
		setconnmode(0);
		flushline = 1;
		break;
	    }
	}
#endif
	if (sc != _POSIX_VDISABLE && MODE_LOCAL_CHARS(globalmode)) {
	    if (TerminalSpecialChars(sc) == 0) {
		bol = 1;
		break;
	    }
	}
	if (my_want_state_is_wont(TELOPT_BINARY)) {
	    switch (c) {
	    case '\n':
		    /*
		     * If we are in CRMOD mode (\r ==> \n)
		     * on our local machine, then probably
		     * a newline (unix) is CRLF (TELNET).
		     */
		if (MODE_LOCAL_CHARS(globalmode)) {
		    NETADD('\r');
		}
		NETADD('\n');
		bol = flushline = 1;
		break;
	    case '\r':
		if (!crlf) {
		    NET2ADD('\r', '\0');
		} else {
		    NET2ADD('\r', '\n');
		}
		bol = flushline = 1;
		break;
	    case IAC:
		NET2ADD(IAC, IAC);
		break;
	    default:
		NETADD(c);
		break;
	    }
	} else if (c == IAC) {
	    NET2ADD(IAC, IAC);
	} else {
	    NETADD(c);
	}
    }
    if (count)
	ring_consumed(&ttyiring, count);
    return returnValue||count;		/* Non-zero if we did anything */
}
Пример #22
0
/* initializes performance data */
int xpddefault_initialize_performance_data(char *config_file) {
    char *buffer = NULL;
    char *temp_buffer = NULL;
    char *temp_command_name = NULL;
    command *temp_command = NULL;
    time_t current_time;
    icinga_macros *mac;

    mac = get_global_macros();
    time(&current_time);

    /* reset vars */
    xpddefault_host_perfdata_command_ptr = NULL;
    xpddefault_service_perfdata_command_ptr = NULL;
    xpddefault_host_perfdata_file_processing_command_ptr = NULL;
    xpddefault_service_perfdata_file_processing_command_ptr = NULL;

    /* grab config info from main config file */
    xpddefault_grab_config_info(config_file);

    /* make sure we have some templates defined */
    if (xpddefault_host_perfdata_file_template == NULL)
        xpddefault_host_perfdata_file_template = (char *)strdup(DEFAULT_HOST_PERFDATA_FILE_TEMPLATE);
    if (xpddefault_service_perfdata_file_template == NULL)
        xpddefault_service_perfdata_file_template = (char *)strdup(DEFAULT_SERVICE_PERFDATA_FILE_TEMPLATE);

    /* process special chars in templates */
    xpddefault_preprocess_file_templates(xpddefault_host_perfdata_file_template);
    xpddefault_preprocess_file_templates(xpddefault_service_perfdata_file_template);

    /* open the performance data files */
    xpddefault_open_host_perfdata_file();
    xpddefault_open_service_perfdata_file();

    /* verify that performance data commands are valid */
    if (xpddefault_host_perfdata_command != NULL) {

        temp_buffer = (char *)strdup(xpddefault_host_perfdata_command);

        /* get the command name, leave any arguments behind */
        temp_command_name = my_strtok(temp_buffer, "!");

        if ((temp_command = find_command(temp_command_name)) == NULL) {

            logit(NSLOG_RUNTIME_WARNING, TRUE, "Warning: Host performance command '%s' was not found - host performance data will not be processed!\n", temp_command_name);

            my_free(xpddefault_host_perfdata_command);
        }

        my_free(temp_buffer);

        /* save the command pointer for later */
        xpddefault_host_perfdata_command_ptr = temp_command;
    }
    if (xpddefault_service_perfdata_command != NULL) {

        temp_buffer = (char *)strdup(xpddefault_service_perfdata_command);

        /* get the command name, leave any arguments behind */
        temp_command_name = my_strtok(temp_buffer, "!");

        if ((temp_command = find_command(temp_command_name)) == NULL) {

            logit(NSLOG_RUNTIME_WARNING, TRUE, "Warning: Service performance command '%s' was not found - service performance data will not be processed!\n", temp_command_name);

            my_free(xpddefault_service_perfdata_command);
        }

        /* free memory */
        my_free(temp_buffer);

        /* save the command pointer for later */
        xpddefault_service_perfdata_command_ptr = temp_command;
    }
    if (xpddefault_host_perfdata_file_processing_command != NULL) {

        temp_buffer = (char *)strdup(xpddefault_host_perfdata_file_processing_command);

        /* get the command name, leave any arguments behind */
        temp_command_name = my_strtok(temp_buffer, "!");

        if ((temp_command = find_command(temp_command_name)) == NULL) {

            logit(NSLOG_RUNTIME_WARNING, TRUE, "Warning: Host performance file processing command '%s' was not found - host performance data file will not be processed!\n", temp_command_name);

            my_free(xpddefault_host_perfdata_file_processing_command);
        }

        /* free memory */
        my_free(temp_buffer);

        /* save the command pointer for later */
        xpddefault_host_perfdata_file_processing_command_ptr = temp_command;
    }
    if (xpddefault_service_perfdata_file_processing_command != NULL) {

        temp_buffer = (char *)strdup(xpddefault_service_perfdata_file_processing_command);

        /* get the command name, leave any arguments behind */
        temp_command_name = my_strtok(temp_buffer, "!");

        if ((temp_command = find_command(temp_command_name)) == NULL) {

            logit(NSLOG_RUNTIME_WARNING, TRUE, "Warning: Service performance file processing command '%s' was not found - service performance data file will not be processed!\n", temp_command_name);

            my_free(xpddefault_service_perfdata_file_processing_command);
        }

        /* save the command pointer for later */
        xpddefault_service_perfdata_file_processing_command_ptr = temp_command;
    }

    /* periodically process the host perfdata file */
    if (xpddefault_host_perfdata_file_processing_interval > 0 && xpddefault_host_perfdata_file_processing_command != NULL)
        schedule_new_event(EVENT_USER_FUNCTION, TRUE, current_time + xpddefault_host_perfdata_file_processing_interval, TRUE, xpddefault_host_perfdata_file_processing_interval, NULL, TRUE, (void *)xpddefault_process_host_perfdata_file, NULL, 0);

    /* periodically process the service perfdata file */
    if (xpddefault_service_perfdata_file_processing_interval > 0 && xpddefault_service_perfdata_file_processing_command != NULL)
        schedule_new_event(EVENT_USER_FUNCTION, TRUE, current_time + xpddefault_service_perfdata_file_processing_interval, TRUE, xpddefault_service_perfdata_file_processing_interval, NULL, TRUE, (void *)xpddefault_process_service_perfdata_file, NULL, 0);

    /* save the host perf data file macro */
    my_free(mac->x[MACRO_HOSTPERFDATAFILE]);
    if (xpddefault_host_perfdata_file != NULL) {
        if ((mac->x[MACRO_HOSTPERFDATAFILE] = (char *)strdup(xpddefault_host_perfdata_file)))
            strip(mac->x[MACRO_HOSTPERFDATAFILE]);
    }

    /* save the service perf data file macro */
    my_free(mac->x[MACRO_SERVICEPERFDATAFILE]);
    if (xpddefault_service_perfdata_file != NULL) {
        if ((mac->x[MACRO_SERVICEPERFDATAFILE] = (char *)strdup(xpddefault_service_perfdata_file)))
            strip(mac->x[MACRO_SERVICEPERFDATAFILE]);
    }

    /* free memory */
    my_free(temp_buffer);
    my_free(buffer);

    return OK;
}
bool CVarConsole::parseAssignment(char* input) {
	bool isAssignment = false;
	for(int x=0; x<strlen(input); x++) {
		if(input[x] == '=') {
			isAssignment = true;
			break;
		}
	}
	if(!isAssignment) return false;

	char* token = strtok(input, "=");
	bool LHset = false;
	char LH[STR_BUFFER];
	char RH[STR_BUFFER];

	while(token != NULL) {
		if(!LHset) {
			strcpy(LH, token);
			LHset = true;
		}
		else strcpy(RH, token);
		token = strtok(NULL, "=");
	}

	char* strippedLH = stripVar(strip(LH));
	char* strippedRH = strip(RH);
	char* varname = stripVar(strippedRH);
	char vardata[STR_BUFFER];

	if(varname) {
		if(!cmap.DoesExist(varname)) {
			char buffer[STR_BUFFER];
			sprintf(buffer, "Identifier not found \"%s\"\n", varname);
			std::string out(buffer);
			out_buffer.push_back(out);
			return true;
		}
		
		if(cmap.GetType(varname) == CType_int) {
			CInt tmp(varname);
			sprintf(vardata, "%i", *tmp); 
		} else if(cmap.GetType(varname) == CType_float) {
			CFloat tmp(varname);
			sprintf(vardata, "%i", *tmp); 
		} if(cmap.GetType(varname) == CType_vec2) {
			CVec2 tmp(varname);
			sprintf(vardata, "%f, %f", (*tmp)[0], (*tmp)[1]); 
		}
		strippedRH = vardata;
	}

	bool vcount = cmap.DoesExist(strippedLH);
	if(!vcount) {
		char buffer[128];
		sprintf(buffer, "Identifier not found \"%s\"\n", strip(LH));
		std::string out(buffer);
		out_buffer.push_back(out);
	} else {
		CType type = cmap.GetType(strippedLH);
		if(type == CType_int) {
			CInt tmp(strippedLH);
			*tmp = atoi(strippedRH);
		} else if(type == CType_float) {
			CFloat tmp(strippedLH);
			*tmp = atof(strippedRH);
		} else if(type == CType_vec2) {
			CVec2 tmp(strippedLH);
			char* x = strtok(strippedRH, ",");
			char* y = strtok(NULL, ",");
			if(!x || !y) {
				char buffer[STR_BUFFER];
				sprintf(buffer, "Not enough arguments for vec2 assignment", strippedLH);
				std::string out(buffer);
				out_buffer.push_back(out);
				return true;
			}
			(*tmp)[0] = atof(x);
			(*tmp)[1] = atof(y);
		}
	}

	return true;
}
Пример #24
0
/* Returns a single line of text from the output buffer of the subprocess,
   taking into account wrapping, centering, etc.  Returns 0 if no complete
   line is currently available.
 */
static char *
get_one_line (fliptext_configuration *sc)
{
  char *result = 0;
  int wrap_pix = sc->font_wrap_pixels;
  int col = 0;
  int col_pix = 0;
  char *s = sc->buf;
  int target = sc->buf_size - sc->buf_tail - 2;

  /* Fill as much as we can into sc->buf, but stop at newline.
   */
  while (target > 0)
    {
      int c = textclient_getc (sc->tc);
      if (c <= 0)
        break;
      sc->buf[sc->buf_tail++] = (char) c;
      sc->buf[sc->buf_tail] = 0;
      target--;
      if (c == '\r' || c == '\n')
        break;
    }

  while (!result)
    {
      int cw;

      if (s >= sc->buf + sc->buf_tail)
        /* Reached end of buffer before end of line.  Bail. */
        return 0;

      cw = char_width (sc, *s);

      if (*s == '\r' || *s == '\n' ||
          col_pix + cw >= wrap_pix)
        {
          int L = s - sc->buf;

          if (*s == '\r' || *s == '\n')
            {
              if (*s == '\r' && s[1] == '\n')  /* swallow CRLF too */
                *s++ = 0;

              *s++ = 0;
            }
          else
            {
              /* We wrapped -- try to back up to the previous word boundary. */
              char *s2 = s;
              int n = 0;
              while (s2 > sc->buf && *s2 != ' ' && *s2 != '\t')
                s2--, n++;
              if (s2 > sc->buf)
                {
                  s = s2;
                  *s++ = 0;
                  L = s - sc->buf;
                }
            }

          if (result) abort();
          result = (char *) malloc (L+1);
          memcpy (result, sc->buf, L);
          result[L] = 0;

          {
            char *t = result;
            char *ut = untabify (t);
            strip (ut, (sc->alignment == 0), 1); /* if centering, strip
                                                    leading whitespace too */
            result = ut;
            free (t);
          }

          if (sc->buf_tail > (s - sc->buf))
            {
              int i = sc->buf_tail - (s - sc->buf);
              memmove (sc->buf, s, i);
              sc->buf_tail = i;
              sc->buf[sc->buf_tail] = 0;
            }
          else
            {
              sc->buf_tail = 0;
            }

          sc->buf[sc->buf_tail] = 0;
          s = sc->buf;
          col = 0;
          col_pix = 0;
        }
      else
        {
          col++;
          col_pix += cw;
          if (*s == '\t')
            {
              int tab_pix = TAB_WIDTH * sc->char_width;
              col     = TAB_WIDTH * ((col / TAB_WIDTH) + 1);
              col_pix = tab_pix   * ((col / tab_pix)   + 1);
            }
          s++;
        }
    }

  return result;
}
Пример #25
0
/* grab configuration information */
int xsddefault_grab_config_info(char *config_file) {
	char *input = NULL;
	mmapfile *thefile;
#ifdef NSCGI
	char *input2 = NULL;
	mmapfile *thefile2;
	char *temp_buffer;
#else
	nagios_macros *mac;
#endif


	/*** CORE PASSES IN MAIN CONFIG FILE, CGIS PASS IN CGI CONFIG FILE! ***/

	/* open the config file for reading */
	if((thefile = mmap_fopen(config_file)) == NULL)
		return ERROR;

	/* read in all lines from the main config file */
	while(1) {

		/* free memory */
		my_free(input);

		/* read the next line */
		if((input = mmap_fgets_multiline(thefile)) == NULL)
			break;

		strip(input);

		/* skip blank lines and comments */
		if(input[0] == '#' || input[0] == '\x0')
			continue;

#ifdef NSCGI
		/* CGI needs to find and read contents of main config file, since it was passed the name of the CGI config file */
		if(strstr(input, "main_config_file") == input) {

			temp_buffer = strtok(input, "=");
			temp_buffer = strtok(NULL, "\n");
			if(temp_buffer == NULL)
				continue;

			if((thefile2 = mmap_fopen(temp_buffer)) == NULL)
				continue;

			/* read in all lines from the main config file */
			while(1) {

				/* free memory */
				my_free(input2);

				/* read the next line */
				if((input2 = mmap_fgets_multiline(thefile2)) == NULL)
					break;

				strip(input2);

				/* skip blank lines and comments */
				if(input2[0] == '#' || input2[0] == '\x0')
					continue;

				xsddefault_grab_config_directives(input2);
				}

			/* free memory and close the file */
			my_free(input2);
			mmap_fclose(thefile2);
			}
#endif

#ifdef NSCORE
		/* core reads variables directly from the main config file */
		xsddefault_grab_config_directives(input);
#endif
		}

	/* free memory and close the file */
	my_free(input);
	mmap_fclose(thefile);

	/* initialize locations if necessary */
	if(xsddefault_status_log == NULL)
		xsddefault_status_log = (char *)strdup(DEFAULT_STATUS_FILE);
	if(xsddefault_temp_file == NULL)
		xsddefault_temp_file = (char *)strdup(DEFAULT_TEMP_FILE);

	/* make sure we have what we need */
	if(xsddefault_status_log == NULL)
		return ERROR;
	if(xsddefault_temp_file == NULL)
		return ERROR;

#ifdef NSCORE
	mac = get_global_macros();
	/* save the status file macro */
	my_free(mac->x[MACRO_STATUSDATAFILE]);
	if((mac->x[MACRO_STATUSDATAFILE] = (char *)strdup(xsddefault_status_log)))
		strip(mac->x[MACRO_STATUSDATAFILE]);
#endif

	return OK;
	}
Пример #26
0
int main()
{  /*  encode using public key  */
    Big e,m,y,ke,mn,mx;
    ifstream public_key("public.key");
    ifstream input_file;
    ofstream output_file;
    static char line[500];
    static char buff[256];
    static char ifname[13],ofname[13];
    BOOL fli,last;
    int i,ipt,klen;
    miracl *mip=&precision;
    mip->IOBASE=60;
    public_key >> ke;
    mn=root(ke,3);
    mx=mn*mn*mn-mn*mn;
 /* find key length in characters */
    klen=bits(mx)/7;
    cout << "file to be encoded = " ;
    cin.getline(ifname,13);
    fli=FALSE;
    if (strlen(ifname)>0) fli=TRUE;
    if (fli)
    { /* set up input file */
        strcpy(ofname,ifname);
        strip(ofname);
        strcat(ofname,".rsa");
        input_file.open(ifname,ios::in|ios::nocreate); 
        if (!input_file)
        {
            cout << "Unable to open file " << ifname << "\n";
            return 0;
        }
        cout << "encoding message\n";
    }
    else
    { /* accept input from keyboard */
        cout << "output filename = ";
        cin >> ofname; 
        strip(ofname);    
        strcat(ofname,".rsa");
        cout << "input message - finish with cntrl z\n";
    }
    output_file.open(ofname);
    ipt=0;
    last=FALSE;
    while (!last)
    { /* encode line by line */
        if (fli)
        {
            input_file.getline(&line[ipt],132);
            if (input_file.eof() || input_file.fail()) last=TRUE;
        }
        else
        {
            cin.getline(&line[ipt],132);
            if (cin.eof() || cin.fail()) last=TRUE;
        }
        strcat(line,"\n");
        ipt=strlen(line);
        if (ipt<klen && !last) continue;
        while (ipt>=klen)
        { /* chop up into klen-sized chunks and encode */
            for (i=0;i<klen;i++)
                buff[i]=line[i];
            buff[klen]='\0';
            for (i=klen;i<=ipt;i++)
                line[i-klen]=line[i];
            ipt-=klen;
            mip->IOBASE=128;
            m=buff;
            e=pow(m,3,ke);
            mip->IOBASE=60;
            output_file << e << endl;
        }
        if (last && ipt>0)
        { /* now deal with left overs */
            mip->IOBASE=128;
            m=line;
            if (m<mn)
            { /* pad out with random number if necessary */
                m+=mn*(mn*mn-rand(mn));
            }
            e=pow(m,3,ke);
            mip->IOBASE=60;
            output_file << e << endl;
        }
    }
    return 0;
}   
Пример #27
0
 void strip(std::string &str){
   str = strip(str.c_str(), str.size());
 }
Пример #28
0
static int conf_sym(struct menu *menu)
{
	struct symbol *sym = menu->sym;
	tristate oldval, newval;

	while (1) {
		printf("%*s%s ", indent - 1, "", _(menu->prompt->text));
		if (sym->name)
			printf("(%s) ", sym->name);
		putchar('[');
		oldval = sym_get_tristate_value(sym);
		switch (oldval) {
		case no:
			putchar('N');
			break;
		case mod:
			putchar('M');
			break;
		case yes:
			putchar('Y');
			break;
		}
		if (oldval != no && sym_tristate_within_range(sym, no))
			printf("/n");
		if (oldval != mod && sym_tristate_within_range(sym, mod))
			printf("/m");
		if (oldval != yes && sym_tristate_within_range(sym, yes))
			printf("/y");
		if (menu_has_help(menu))
			printf("/?");
		printf("] ");
		if (!conf_askvalue(sym, sym_get_string_value(sym)))
			return 0;
		strip(line);

		switch (line[0]) {
		case 'n':
		case 'N':
			newval = no;
			if (!line[1] || !strcmp(&line[1], "o"))
				break;
			continue;
		case 'm':
		case 'M':
			newval = mod;
			if (!line[1])
				break;
			continue;
		case 'y':
		case 'Y':
			newval = yes;
			if (!line[1] || !strcmp(&line[1], "es"))
				break;
			continue;
		case 0:
			newval = oldval;
			break;
		case '?':
			goto help;
		default:
			continue;
		}
		if (sym_set_tristate_value(sym, newval))
			return 0;
help:
		print_help(menu);
	}
}
Пример #29
0
int main(int argc, char *argv[])
{
	/* Win32 stuff */
#ifdef _WIN32
	WSADATA wsa;
#endif

	if (argc == 1)
		return 0;

	char *server = strtok(argv[1], ":"), *aport;
	short port;
	if ((aport = strtok(NULL, "")))
		port = atoi(aport);
	else
		port = 25;

	if (!server)
	{
		alog("No Server");
		/* Bad, bad, bad. This was a return from main with no value! -GD */
		return 0;
	}
	else
		alog("SMTP: server %s port %d",server,port);

	/* The WSAStartup function initiates use of WS2_32.DLL by a process. */
	/* guessing we can skip it under *nix */
#ifdef _WIN32
	if (WSAStartup(MAKEWORD(1, 1), &wsa))
		return 0;
#endif

	char buf[8192];
	bool headers_done = false;
	/* Read the message and parse it */
	while (fgets(buf, 8192, stdin))
	{
		if (smtp_is_header(buf) && !headers_done)
		{
			smail.smtp_headers.push_back(strip(buf) + "\r\n");
			std::string header, value;
			smtp_parse_header(buf, header, value);
			if (header == "From:")
			{
				alog("SMTP: from: %s", value.c_str());
				smail.from = value;
			}
			else if (header == "To:")
			{
				alog("SMTP: to: %s", value.c_str());
				smtp_set_to(value);
			}
			else if (smtp_is_end(buf))
				break;
			else
			{
				headers_done = true;
				smail.smtp_body.push_back(strip(buf) + "\r\n");
			}
		}
		else
			smail.smtp_body.push_back(strip(buf) + "\r\n");
	}

	if (!smtp_connect(server, port))
	{
		alog("SMTP: failed to connect to %s:%d", server, port);
		return 0;
	}
	if (!smtp_send_email())
	{
		alog("SMTP: error during sending of mail");
		return 0;
	}
	smtp_disconnect();

	return 1;
}
Пример #30
0
int
ssh_connect (char *haddr, int hport, char *remote_version, char *remote_protocol)
{
	int sd;
	int result;
	char *output = NULL;
	char *buffer = NULL;
	char *ssh_proto = NULL;
	char *ssh_server = NULL;
	static char *rev_no = VERSION;
	struct timeval tv;
	double elapsed_time;

	gettimeofday(&tv, NULL);

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

	if (result != STATE_OK)
		return result;

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

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

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

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

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

		printf
			(_("SSH OK - %s (protocol %s) | %s\n"),
			 ssh_server, ssh_proto, fperfdata("time", elapsed_time, "s",
			 FALSE, 0, FALSE, 0, TRUE, 0, TRUE, (int)socket_timeout));
		close(sd);
		exit (STATE_OK);
	}
}