Beispiel #1
0
/**
 * Frees memory allocated for chr_table datastructure.
 */
void chr_table_free(ChrTable *chr_tab) {
  chr_array_free(chr_tab->chr_array, chr_tab->n_chr);
  my_free(chr_tab->offset);
  my_free(chr_tab);
}
Beispiel #2
0
MY_DIR	*my_dir(const char *path, myf MyFlags)
{
  char          *buffer;
  MY_DIR        *result= 0;
  FILEINFO      finfo;
  DYNAMIC_ARRAY *dir_entries_storage;
  MEM_ROOT      *names_storage;
#ifdef __BORLANDC__
  struct ffblk       find;
#else
  struct _finddata_t find;
#endif
  ushort	mode;
  char		tmp_path[FN_REFLEN],*tmp_file,attrib;
#ifdef _WIN64
  __int64       handle;
#else
  long		handle;
#endif
  DBUG_ENTER("my_dir");
  DBUG_PRINT("my",("path: '%s' stat: %d  MyFlags: %d",path,MyFlags));

  /* Put LIB-CHAR as last path-character if not there */
  tmp_file=tmp_path;
  if (!*path)
    *tmp_file++ ='.';				/* From current dir */
  tmp_file= strnmov(tmp_file, path, FN_REFLEN-5);
  if (tmp_file[-1] == FN_DEVCHAR)
    *tmp_file++= '.';				/* From current dev-dir */
  if (tmp_file[-1] != FN_LIBCHAR)
    *tmp_file++ =FN_LIBCHAR;
  tmp_file[0]='*';				/* Windows needs this !??? */
  tmp_file[1]='.';
  tmp_file[2]='*';
  tmp_file[3]='\0';

  if (!(buffer= my_malloc(ALIGN_SIZE(sizeof(MY_DIR)) + 
                          ALIGN_SIZE(sizeof(DYNAMIC_ARRAY)) +
                          sizeof(MEM_ROOT), MyFlags)))
    goto error;

  dir_entries_storage= (DYNAMIC_ARRAY*)(buffer + ALIGN_SIZE(sizeof(MY_DIR))); 
  names_storage= (MEM_ROOT*)(buffer + ALIGN_SIZE(sizeof(MY_DIR)) +
                             ALIGN_SIZE(sizeof(DYNAMIC_ARRAY)));
  
  if (my_init_dynamic_array(dir_entries_storage, sizeof(FILEINFO),
                            ENTRIES_START_SIZE, ENTRIES_INCREMENT))
  {
    my_free((uchar*) buffer,MYF(0));
    goto error;
  }
  init_alloc_root(names_storage, NAMES_START_SIZE, NAMES_START_SIZE);
  
  /* MY_DIR structure is allocated and completly initialized at this point */
  result= (MY_DIR*)buffer;

#ifdef __BORLANDC__
  if ((handle= findfirst(tmp_path,&find,0)) == -1L)
#else
  if ((handle=_findfirst(tmp_path,&find)) == -1L)
#endif
  {
    DBUG_PRINT("info", ("findfirst returned error, errno: %d", errno));
    if  (errno != EINVAL)
      goto error;
    /*
      Could not read the directory, no read access.
      Probably because by "chmod -r".
      continue and return zero files in dir
    */
  }
  else
  {

    do
    {
#ifdef __BORLANDC__
      attrib= find.ff_attrib;
#else
      attrib= find.attrib;
      /*
        Do not show hidden and system files which Windows sometimes create.
        Note. Because Borland's findfirst() is called with the third
        argument = 0 hidden/system files are excluded from the search.
      */
      if (attrib & (_A_HIDDEN | _A_SYSTEM))
        continue;
#endif
#ifdef __BORLANDC__
      if (!(finfo.name= strdup_root(names_storage, find.ff_name)))
        goto error;
#else
      if (!(finfo.name= strdup_root(names_storage, find.name)))
        goto error;
#endif
      if (MyFlags & MY_WANT_STAT)
      {
        if (!(finfo.mystat= (MY_STAT*)alloc_root(names_storage,
                                                 sizeof(MY_STAT))))
          goto error;

        bzero(finfo.mystat, sizeof(MY_STAT));
#ifdef __BORLANDC__
        finfo.mystat->st_size=find.ff_fsize;
#else
        finfo.mystat->st_size=find.size;
#endif
        mode= MY_S_IREAD;
        if (!(attrib & _A_RDONLY))
          mode|= MY_S_IWRITE;
        if (attrib & _A_SUBDIR)
          mode|= MY_S_IFDIR;
        finfo.mystat->st_mode= mode;
#ifdef __BORLANDC__
        finfo.mystat->st_mtime= ((uint32) find.ff_ftime);
#else
        finfo.mystat->st_mtime= ((uint32) find.time_write);
#endif
      }
      else
        finfo.mystat= NULL;

      if (push_dynamic(dir_entries_storage, (uchar*)&finfo))
        goto error;
    }
#ifdef __BORLANDC__
    while (findnext(&find) == 0);
#else
    while (_findnext(handle,&find) == 0);

    _findclose(handle);
#endif
  }

  result->dir_entry= (FILEINFO *)dir_entries_storage->buffer;
  result->number_off_files= dir_entries_storage->elements;

  if (!(MyFlags & MY_DONT_SORT))
    my_qsort((void *) result->dir_entry, result->number_off_files,
          sizeof(FILEINFO), (qsort_cmp) comp_names);
  DBUG_PRINT("exit", ("found %d files", result->number_off_files));
  DBUG_RETURN(result);
error:
  my_errno=errno;
#ifndef __BORLANDC__
  if (handle != -1)
      _findclose(handle);
#endif
  my_dirend(result);
  if (MyFlags & MY_FAE+MY_WME)
    my_error(EE_DIR,MYF(ME_BELL+ME_WAITTANG),path,errno);
  DBUG_RETURN((MY_DIR *) NULL);
} /* my_dir */
Beispiel #3
0
int heap_create(const char *name, HP_CREATE_INFO *create_info,
                HP_SHARE **res, my_bool *created_new_share)
{
  uint i, j, key_segs, max_length, length;
  HP_SHARE *share= 0;
  HA_KEYSEG *keyseg;
  HP_KEYDEF *keydef= create_info->keydef;
  uint reclength= create_info->reclength;
  uint keys= create_info->keys;
  ulong min_records= create_info->min_records;
  ulong max_records= create_info->max_records;
  ulong max_rows_for_stated_memory;
  DBUG_ENTER("heap_create");

  if (!create_info->internal_table)
  {
    mysql_mutex_lock(&THR_LOCK_heap);
    share= hp_find_named_heap(name);
    if (share && share->open_count == 0)
    {
      hp_free(share);
      share= 0;
    }
  }
  *created_new_share= (share == NULL);

  if (!share)
  {
    uint chunk_dataspace_length, chunk_length, is_variable_size;
    uint fixed_data_length, fixed_column_count;
    HP_KEYDEF *keyinfo;
    DBUG_PRINT("info",("Initializing new table"));

    if (create_info->max_chunk_size)
    {
      uint configured_chunk_size= create_info->max_chunk_size;

      /* User requested variable-size records, let's see if they're possible */

      if (configured_chunk_size < create_info->fixed_data_size)
      {
        /*
          The resulting chunk_size cannot be smaller than fixed data part
          at the start of the first chunk which allows faster copying
          with a single memcpy().
        */
        my_error(ER_CANT_USE_OPTION_HERE, MYF(0), "key_block_size");
        goto err;
      }

      if (reclength > configured_chunk_size + VARIABLE_REC_OVERHEAD ||
	  create_info->blobs > 0)
      {
        /*
          Allow variable size only if we're saving some space, i.e.
          if a fixed-size record would take more space than variable-size
          one plus the variable-size overhead.
          There has to be at least one field after indexed fields.
          Note that NULL bits are already included in key_part_size.
        */
        is_variable_size= 1;
        chunk_dataspace_length= configured_chunk_size;
      }
      else
      {
        /* max_chunk_size is near the full reclength, let's use fixed size */
        is_variable_size= 0;
        chunk_dataspace_length= reclength;
      }
    }
    else if ((create_info->is_dynamic && reclength >
              256 + VARIABLE_REC_OVERHEAD)
             || create_info->blobs > 0)
    {
      /*
        User asked for dynamic records - use 256 as the chunk size, if that
        will may save some memory. Otherwise revert to fixed size format.
      */
      if ((create_info->fixed_data_size + VARIABLE_REC_OVERHEAD) > 256)
        chunk_dataspace_length= create_info->fixed_data_size;
      else
        chunk_dataspace_length= 256 - VARIABLE_REC_OVERHEAD;

      is_variable_size= 1;
    }
    else
    {
      /*
        If max_chunk_size is not specified, put the whole record in one chunk
      */
      is_variable_size= 0;
      chunk_dataspace_length= reclength;
    }

    if (is_variable_size)
    {
      /* Check whether we have any variable size records past key data */
      uint has_variable_fields= 0;

      fixed_data_length= create_info->fixed_data_size;
      fixed_column_count= create_info->fixed_key_fieldnr;

      for (i= create_info->fixed_key_fieldnr; i < create_info->columns; i++)
      {
        HP_COLUMNDEF *column= create_info->columndef + i;
	if ((column->type == MYSQL_TYPE_VARCHAR &&
	     (column->length - column->length_bytes) >= 32) ||
	    column->type == MYSQL_TYPE_BLOB)
        {
            /*
              The field has to be either blob or >= 5.0.3 true VARCHAR
              and have substantial length.
              TODO: do we want to calculate minimum length?
            */
            has_variable_fields= 1;
            break;
        }

        if (has_variable_fields)
        {
          break;
        }

        if ((column->offset + column->length) <= chunk_dataspace_length)
        {
          /* Still no variable-size columns, add one fixed-length */
          fixed_column_count= i + 1;
          fixed_data_length= column->offset + column->length;
        }
      }

      if (!has_variable_fields && create_info->blobs == 0)
      {
        /*
          There is no need to use variable-size records without variable-size
          columns.
          Reset sizes if it's not variable size anymore.
        */
        is_variable_size= 0;
        chunk_dataspace_length= reclength;
        fixed_data_length= reclength;
        fixed_column_count= create_info->columns;
      }
    }
    else
    {
      fixed_data_length= reclength;
      fixed_column_count= create_info->columns;
    }

    /*
      We store uchar* del_link inside the data area of deleted records,
      so the data length should be at least sizeof(uchar*)
    */
    set_if_bigger(chunk_dataspace_length, sizeof (uchar **));

    if (is_variable_size)
    {
      chunk_length= chunk_dataspace_length + VARIABLE_REC_OVERHEAD;
    }
    else
    {
      chunk_length= chunk_dataspace_length + FIXED_REC_OVERHEAD;
    }

    /* Align chunk length to the next pointer */
    chunk_length= (uint) (chunk_length + sizeof(uchar **) - 1) &
      ~(sizeof(uchar **) - 1);

    for (i= key_segs= max_length= 0, keyinfo= keydef; i < keys; i++, keyinfo++)
    {
      memset(&keyinfo->block, 0, sizeof(keyinfo->block));
      memset(&keyinfo->rb_tree, 0, sizeof(keyinfo->rb_tree));
      for (j= length= 0; j < keyinfo->keysegs; j++)
      {
	length+= keyinfo->seg[j].length;
	if (keyinfo->seg[j].null_bit)
	{
	  length++;
	  if (!(keyinfo->flag & HA_NULL_ARE_EQUAL))
	    keyinfo->flag|= HA_NULL_PART_KEY;
	  if (keyinfo->algorithm == HA_KEY_ALG_BTREE)
	    keyinfo->rb_tree.size_of_element++;
	}
	switch (keyinfo->seg[j].type) {
        case HA_KEYTYPE_VARBINARY1:
        case HA_KEYTYPE_VARTEXT1:
        case HA_KEYTYPE_VARBINARY2:
        case HA_KEYTYPE_VARTEXT2:
          length+= 2;
          break;
	default:
	  break;
	}
      }
      keyinfo->length= length;
      length+= keyinfo->rb_tree.size_of_element + 
	       ((keyinfo->algorithm == HA_KEY_ALG_BTREE) ? sizeof(uchar*) : 0);
      if (length > max_length)
	max_length= length;
      key_segs+= keyinfo->keysegs;
      if (keyinfo->algorithm == HA_KEY_ALG_BTREE)
      {
        key_segs++; /* additional HA_KEYTYPE_END segment */
        if (keyinfo->flag & HA_VAR_LENGTH_KEY)
          keyinfo->get_key_length= hp_rb_var_key_length;
        else if (keyinfo->flag & HA_NULL_PART_KEY)
          keyinfo->get_key_length= hp_rb_null_key_length;
        else
          keyinfo->get_key_length= hp_rb_key_length;
      }
    }
    if (!(share= (HP_SHARE*) my_malloc((uint) sizeof(HP_SHARE)+
				       keys*sizeof(HP_KEYDEF)+
                                       (create_info->columns *
                                        sizeof(HP_COLUMNDEF)) +
				       key_segs*sizeof(HA_KEYSEG),
				       MYF(MY_ZEROFILL))))
      goto err;

    /*
      Max_records is used for estimating block sizes and for enforcement.
      Calculate the very maximum number of rows (if everything was one chunk)
      and then take either that value or configured max_records (pick smallest
      one).
    */
    max_rows_for_stated_memory= (ha_rows) (create_info->max_table_size /
                                           (create_info->keys_memory_size +
                                            chunk_length));
    max_records = ((max_records && max_records < max_rows_for_stated_memory) ?
                   max_records : max_rows_for_stated_memory);

    share->column_defs= (HP_COLUMNDEF*) (share + 1);
    memcpy(share->column_defs, create_info->columndef,
           (size_t) (sizeof(create_info->columndef[0]) *
                     create_info->columns));

    share->keydef= (HP_KEYDEF*) (share->column_defs + create_info->columns);
    share->key_stat_version= 1;
    keyseg= (HA_KEYSEG*) (share->keydef + keys);
    init_block(&share->recordspace.block, chunk_length, min_records,
               max_records);
	/* Fix keys */
    memcpy(share->keydef, keydef, (size_t) (sizeof(keydef[0]) * keys));
    for (i= 0, keyinfo= share->keydef; i < keys; i++, keyinfo++)
    {
      keyinfo->seg= keyseg;
      memcpy(keyseg, keydef[i].seg,
	     (size_t) (sizeof(keyseg[0]) * keydef[i].keysegs));
      keyseg+= keydef[i].keysegs;

      if (keydef[i].algorithm == HA_KEY_ALG_BTREE)
      {
	/* additional HA_KEYTYPE_END keyseg */
	keyseg->type=     HA_KEYTYPE_END;
	keyseg->length=   sizeof(uchar*);
	keyseg->flag=     0;
	keyseg->null_bit= 0;
	keyseg++;

	init_tree(&keyinfo->rb_tree, 0, 0, sizeof(uchar*),
		  (qsort_cmp2)keys_compare, 1, NULL, NULL);
	keyinfo->delete_key= hp_rb_delete_key;
	keyinfo->write_key= hp_rb_write_key;
      }
      else
      {
	init_block(&keyinfo->block, sizeof(HASH_INFO), min_records,
		   max_records);
	keyinfo->delete_key= hp_delete_key;
	keyinfo->write_key= hp_write_key;
        keyinfo->hash_buckets= 0;
      }
      if ((keyinfo->flag & HA_AUTO_KEY) && create_info->with_auto_increment)
        share->auto_key= i + 1;
    }
    share->min_records= min_records;
    share->max_records= max_records;
    share->max_table_size= create_info->max_table_size;
    share->index_length= 0;
    share->blength= 1;
    share->keys= keys;
    share->max_key_length= max_length;
    share->column_count= create_info->columns;
    share->changed= 0;
    share->auto_key= create_info->auto_key;
    share->auto_key_type= create_info->auto_key_type;
    share->auto_increment= create_info->auto_increment;
    share->create_time= (long) time((time_t*) 0);

    share->fixed_data_length= fixed_data_length;
    share->fixed_column_count= fixed_column_count;
    share->blobs= create_info->blobs;

    share->recordspace.chunk_length= chunk_length;
    share->recordspace.chunk_dataspace_length= chunk_dataspace_length;
    share->recordspace.is_variable_size= is_variable_size;
    share->recordspace.total_data_length= 0;

    if (is_variable_size) {
      share->recordspace.offset_link= chunk_dataspace_length;
      share->recordspace.offset_status= share->recordspace.offset_link +
        sizeof(uchar **);
    } else {
      /* Make it likely to fail if anyone uses this offset */
      share->recordspace.offset_link= 1 << 22;
      share->recordspace.offset_status= chunk_dataspace_length;
    }

    /* Must be allocated separately for rename to work */
    if (!(share->name= my_strdup(name,MYF(0))))
    {
      my_free(share);
      goto err;
    }
    thr_lock_init(&share->lock);
    mysql_mutex_init(hp_key_mutex_HP_SHARE_intern_lock,
                     &share->intern_lock, MY_MUTEX_INIT_FAST);
    if (!create_info->internal_table)
    {
      share->open_list.data= (void*) share;
      heap_share_list= list_add(heap_share_list,&share->open_list);
    }
    else
      share->delete_on_close= 1;
  }
  if (!create_info->internal_table)
  {
    if (create_info->pin_share)
      ++share->open_count;
    mysql_mutex_unlock(&THR_LOCK_heap);
  }

  *res= share;
  DBUG_RETURN(0);

err:
  if (!create_info->internal_table)
    mysql_mutex_unlock(&THR_LOCK_heap);
  DBUG_RETURN(1);
} /* heap_create */
Beispiel #4
0
void display_logentries() {
	char image[MAX_INPUT_BUFFER];
	char image_alt[MAX_INPUT_BUFFER];
	char last_message_date[MAX_INPUT_BUFFER] = "";
	char current_message_date[MAX_INPUT_BUFFER] = "";
	char date_time[MAX_DATETIME_LENGTH];
	char *error_text = NULL;
	int status = READLOG_OK;
	int i = 0;
	int user_has_seen_something = FALSE;
	int json_start = TRUE;
	int total_entries = 0;
	int displayed_entries = 0;
	struct tm *time_ptr = NULL;
	logentry *entry_list = NULL;
	logentry *temp_entry = NULL;
	logfilter *filter_list = NULL;


	/* Add default filters */
	if (showlog_initial_states == FALSE) {
		add_log_filter(&filter_list, LOGENTRY_SERVICE_INITIAL_STATE, LOGFILTER_EXCLUDE);
		add_log_filter(&filter_list, LOGENTRY_HOST_INITIAL_STATE, LOGFILTER_EXCLUDE);
	}
	if (showlog_current_states == FALSE) {
		add_log_filter(&filter_list, LOGENTRY_SERVICE_CURRENT_STATE, LOGFILTER_EXCLUDE);
		add_log_filter(&filter_list, LOGENTRY_HOST_CURRENT_STATE, LOGFILTER_EXCLUDE);
	}

	/* Add requested filters */
	if (show_notifications == FALSE) {
		add_log_filter(&filter_list, LOGENTRY_HOST_NOTIFICATION, LOGFILTER_EXCLUDE);
		add_log_filter(&filter_list, LOGENTRY_SERVICE_NOTIFICATION, LOGFILTER_EXCLUDE);
	}
	if (show_host_status == FALSE) {
		add_log_filter(&filter_list, LOGENTRY_HOST_UP, LOGFILTER_EXCLUDE);
		add_log_filter(&filter_list, LOGENTRY_HOST_DOWN, LOGFILTER_EXCLUDE);
		add_log_filter(&filter_list, LOGENTRY_HOST_UNREACHABLE, LOGFILTER_EXCLUDE);
		add_log_filter(&filter_list, LOGENTRY_HOST_RECOVERY, LOGFILTER_EXCLUDE);
		add_log_filter(&filter_list, LOGENTRY_PASSIVE_HOST_CHECK, LOGFILTER_EXCLUDE);
	}
	if (show_service_status == FALSE) {
		add_log_filter(&filter_list, LOGENTRY_SERVICE_OK, LOGFILTER_EXCLUDE);
		add_log_filter(&filter_list, LOGENTRY_SERVICE_WARNING, LOGFILTER_EXCLUDE);
		add_log_filter(&filter_list, LOGENTRY_SERVICE_CRITICAL, LOGFILTER_EXCLUDE);
		add_log_filter(&filter_list, LOGENTRY_SERVICE_UNKNOWN, LOGFILTER_EXCLUDE);
		add_log_filter(&filter_list, LOGENTRY_SERVICE_RECOVERY, LOGFILTER_EXCLUDE);
		add_log_filter(&filter_list, LOGENTRY_PASSIVE_SERVICE_CHECK, LOGFILTER_EXCLUDE);
	}
	if (show_external_commands == FALSE)
		add_log_filter(&filter_list, LOGENTRY_EXTERNAL_COMMAND, LOGFILTER_EXCLUDE);

	if (show_system_messages == FALSE) {
		add_log_filter(&filter_list, LOGENTRY_SYSTEM_WARNING, LOGFILTER_EXCLUDE);
		add_log_filter(&filter_list, LOGENTRY_STARTUP, LOGFILTER_EXCLUDE);
		add_log_filter(&filter_list, LOGENTRY_SHUTDOWN, LOGFILTER_EXCLUDE);
		add_log_filter(&filter_list, LOGENTRY_BAILOUT, LOGFILTER_EXCLUDE);
		add_log_filter(&filter_list, LOGENTRY_RESTART, LOGFILTER_EXCLUDE);
		add_log_filter(&filter_list, LOGENTRY_LOG_ROTATION, LOGFILTER_EXCLUDE);
		add_log_filter(&filter_list, LOGENTRY_AUTOSAVE, LOGFILTER_EXCLUDE);
		add_log_filter(&filter_list, LOGENTRY_IDOMOD, LOGFILTER_EXCLUDE);
	}
	if (show_event_handler == FALSE) {
		add_log_filter(&filter_list, LOGENTRY_SERVICE_EVENT_HANDLER, LOGFILTER_EXCLUDE);
		add_log_filter(&filter_list, LOGENTRY_HOST_EVENT_HANDLER, LOGFILTER_EXCLUDE);
	}
	if (show_flapping == FALSE) {
		add_log_filter(&filter_list, LOGENTRY_SERVICE_FLAPPING_STARTED, LOGFILTER_EXCLUDE);
		add_log_filter(&filter_list, LOGENTRY_SERVICE_FLAPPING_STOPPED, LOGFILTER_EXCLUDE);
		add_log_filter(&filter_list, LOGENTRY_SERVICE_FLAPPING_DISABLED, LOGFILTER_EXCLUDE);
		add_log_filter(&filter_list, LOGENTRY_HOST_FLAPPING_STARTED, LOGFILTER_EXCLUDE);
		add_log_filter(&filter_list, LOGENTRY_HOST_FLAPPING_STOPPED, LOGFILTER_EXCLUDE);
		add_log_filter(&filter_list, LOGENTRY_HOST_FLAPPING_DISABLED, LOGFILTER_EXCLUDE);
	}
	if (show_downtime == FALSE) {
		add_log_filter(&filter_list, LOGENTRY_SERVICE_DOWNTIME_STARTED, LOGFILTER_EXCLUDE);
		add_log_filter(&filter_list, LOGENTRY_SERVICE_DOWNTIME_STOPPED, LOGFILTER_EXCLUDE);
		add_log_filter(&filter_list, LOGENTRY_SERVICE_DOWNTIME_CANCELLED, LOGFILTER_EXCLUDE);
		add_log_filter(&filter_list, LOGENTRY_HOST_DOWNTIME_STARTED, LOGFILTER_EXCLUDE);
		add_log_filter(&filter_list, LOGENTRY_HOST_DOWNTIME_STOPPED, LOGFILTER_EXCLUDE);
		add_log_filter(&filter_list, LOGENTRY_HOST_DOWNTIME_CANCELLED, LOGFILTER_EXCLUDE);
	}

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

	free_log_filters(&filter_list);


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

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


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

	/* now we start displaying the log entries */
	} else {

		if (content_type == JSON_CONTENT) {
			display_timebreaks = FALSE;
			if (status != READLOG_OK)
				printf(",\n");
			printf("\"log_entries\": [\n");
		} else if (content_type == CSV_CONTENT) {
			display_timebreaks = FALSE;

			printf("%sTimestamp%s%s", csv_data_enclosure, csv_data_enclosure, csv_delimiter);
			printf("%sDate Time%s%s", csv_data_enclosure, csv_data_enclosure, csv_delimiter);
			printf("%sLog Entry%s\n", csv_data_enclosure, csv_data_enclosure);

		} else {
			/* add export to csv, json, link */
			printf("<table width='100%%' cellspacing=0 cellpadding=0 border=0><tr><td width='33%%'></td><td width='33%%' align=center nowrap>");
			printf("<div class='page_selector' id='log_page_selector'>\n");
			printf("<div id='page_navigation_copy'></div>");
			page_limit_selector(result_start);
			printf("</div>\n");
			printf("</td><td width='33%%' align='right'>\n");
			printf("<div class='csv_export_link' style='margin-right:1em;'>");
			print_export_link(CSV_CONTENT, SHOWLOG_CGI, NULL);
			print_export_link(JSON_CONTENT, SHOWLOG_CGI, NULL);
			print_export_link(HTML_CONTENT, SHOWLOG_CGI, NULL);
			printf("</div></td></tr></table>");
			printf("</div>\n");

			printf("<DIV CLASS='logEntries'>\n");
		}

		for (temp_entry = entry_list; temp_entry != NULL; temp_entry = temp_entry->next) {

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

			total_entries++;
			displayed_entries++;

			/* set the correct icon and icon alt text for current log entry */
			if (temp_entry->type == LOGENTRY_STARTUP) {
				strcpy(image, START_ICON);
				strcpy(image_alt, START_ICON_ALT);
			} else if (temp_entry->type == LOGENTRY_SHUTDOWN || temp_entry->type == LOGENTRY_BAILOUT) {
				strcpy(image, STOP_ICON);
				strcpy(image_alt, STOP_ICON_ALT);
			} else if (temp_entry->type == LOGENTRY_RESTART) {
				strcpy(image, RESTART_ICON);
				strcpy(image_alt, RESTART_ICON_ALT);
			} else if (temp_entry->type == LOGENTRY_HOST_DOWN) {
				strcpy(image, HOST_DOWN_ICON);
				strcpy(image_alt, HOST_DOWN_ICON_ALT);
			} else if (temp_entry->type == LOGENTRY_HOST_UNREACHABLE) {
				strcpy(image, HOST_UNREACHABLE_ICON);
				strcpy(image_alt, HOST_UNREACHABLE_ICON_ALT);
			} else if (temp_entry->type == LOGENTRY_HOST_RECOVERY || temp_entry->type == LOGENTRY_HOST_UP) {
				strcpy(image, HOST_UP_ICON);
				strcpy(image_alt, HOST_UP_ICON_ALT);
			} else if (temp_entry->type == LOGENTRY_HOST_NOTIFICATION) {
				strcpy(image, HOST_NOTIFICATION_ICON);
				strcpy(image_alt, HOST_NOTIFICATION_ICON_ALT);
			} else if (temp_entry->type == LOGENTRY_SERVICE_CRITICAL) {
				strcpy(image, CRITICAL_ICON);
				strcpy(image_alt, CRITICAL_ICON_ALT);
			} else if (temp_entry->type == LOGENTRY_SERVICE_WARNING) {
				strcpy(image, WARNING_ICON);
				strcpy(image_alt, WARNING_ICON_ALT);
			} else if (temp_entry->type == LOGENTRY_SERVICE_UNKNOWN) {
				strcpy(image, UNKNOWN_ICON);
				strcpy(image_alt, UNKNOWN_ICON_ALT);
			} else if (temp_entry->type == LOGENTRY_SERVICE_RECOVERY || temp_entry->type == LOGENTRY_SERVICE_OK) {
				strcpy(image, OK_ICON);
				strcpy(image_alt, OK_ICON_ALT);
			} else if (temp_entry->type == LOGENTRY_SERVICE_NOTIFICATION) {
				strcpy(image, NOTIFICATION_ICON);
				strcpy(image_alt, NOTIFICATION_ICON_ALT);
			} else if (temp_entry->type == LOGENTRY_SERVICE_EVENT_HANDLER) {
				strcpy(image, SERVICE_EVENT_ICON);
				strcpy(image_alt, SERVICE_EVENT_ICON_ALT);
			} else if (temp_entry->type == LOGENTRY_HOST_EVENT_HANDLER) {
				strcpy(image, HOST_EVENT_ICON);
				strcpy(image_alt, HOST_EVENT_ICON_ALT);
			} else if (temp_entry->type == LOGENTRY_EXTERNAL_COMMAND) {
				strcpy(image, EXTERNAL_COMMAND_ICON);
				strcpy(image_alt, EXTERNAL_COMMAND_ICON_ALT);
			} else if (temp_entry->type == LOGENTRY_PASSIVE_SERVICE_CHECK) {
				strcpy(image, PASSIVE_ICON);
				strcpy(image_alt, "Passive Service Check");
			} else if (temp_entry->type == LOGENTRY_PASSIVE_HOST_CHECK) {
				strcpy(image, PASSIVE_ICON);
				strcpy(image_alt, "Passive Host Check");
			} else if (temp_entry->type == LOGENTRY_LOG_ROTATION) {
				strcpy(image, LOG_ROTATION_ICON);
				strcpy(image_alt, LOG_ROTATION_ICON_ALT);
			} else if (temp_entry->type == LOGENTRY_ACTIVE_MODE) {
				strcpy(image, ACTIVE_ICON);
				strcpy(image_alt, ACTIVE_ICON_ALT);
			} else if (temp_entry->type == LOGENTRY_STANDBY_MODE) {
				strcpy(image, STANDBY_ICON);
				strcpy(image_alt, STANDBY_ICON_ALT);
			} else if (temp_entry->type == LOGENTRY_SERVICE_FLAPPING_STARTED) {
				strcpy(image, FLAPPING_ICON);
				strcpy(image_alt, "Service started flapping");
			} else if (temp_entry->type == LOGENTRY_SERVICE_FLAPPING_STOPPED) {
				strcpy(image, FLAPPING_ICON);
				strcpy(image_alt, "Service stopped flapping");
			} else if (temp_entry->type == LOGENTRY_SERVICE_FLAPPING_DISABLED) {
				strcpy(image, FLAPPING_ICON);
				strcpy(image_alt, "Service flap detection disabled");
			} else if (temp_entry->type == LOGENTRY_HOST_FLAPPING_STARTED) {
				strcpy(image, FLAPPING_ICON);
				strcpy(image_alt, "Host started flapping");
			} else if (temp_entry->type == LOGENTRY_HOST_FLAPPING_STOPPED) {
				strcpy(image, FLAPPING_ICON);
				strcpy(image_alt, "Host stopped flapping");
			} else if (temp_entry->type == LOGENTRY_HOST_FLAPPING_DISABLED) {
				strcpy(image, FLAPPING_ICON);
				strcpy(image_alt, "Host flap detection disabled");
			} else if (temp_entry->type == LOGENTRY_SERVICE_DOWNTIME_STARTED) {
				strcpy(image, DOWNTIME_ICON);
				strcpy(image_alt, "Service entered a period of scheduled downtime");
			} else if (temp_entry->type == LOGENTRY_SERVICE_DOWNTIME_STOPPED) {
				strcpy(image, DOWNTIME_ICON);
				strcpy(image_alt, "Service exited a period of scheduled downtime");
			} else if (temp_entry->type == LOGENTRY_SERVICE_DOWNTIME_CANCELLED) {
				strcpy(image, DOWNTIME_ICON);
				strcpy(image_alt, "Service scheduled downtime has been cancelled");
			} else if (temp_entry->type == LOGENTRY_HOST_DOWNTIME_STARTED) {
				strcpy(image, DOWNTIME_ICON);
				strcpy(image_alt, "Host entered a period of scheduled downtime");
			} else if (temp_entry->type == LOGENTRY_HOST_DOWNTIME_STOPPED) {
				strcpy(image, DOWNTIME_ICON);
				strcpy(image_alt, "Host exited a period of scheduled downtime");
			} else if (temp_entry->type == LOGENTRY_HOST_DOWNTIME_CANCELLED) {
				strcpy(image, DOWNTIME_ICON);
				strcpy(image_alt, "Host scheduled downtime has been cancelled");
			} else if (temp_entry->type == LOGENTRY_IDOMOD) {
				strcpy(image, DATABASE_ICON);
				strcpy(image_alt, "IDOMOD Information");
			} else if (temp_entry->type == LOGENTRY_NPCDMOD) {
				strcpy(image, STATS_ICON);
				strcpy(image_alt, "NPCDMOD Information");
			} else if (temp_entry->type == LOGENTRY_AUTOSAVE) {
				strcpy(image, AUTOSAVE_ICON);
				strcpy(image_alt, "Auto-save retention data");
			} else if (temp_entry->type == LOGENTRY_SYSTEM_WARNING) {
				strcpy(image, DAEMON_WARNING_ICON);
				strcpy(image_alt, "Icinga warning message");
			} else {
				strcpy(image, INFO_ICON);
				strcpy(image_alt, INFO_ICON_ALT);
			}

			time_ptr = localtime(&temp_entry->timestamp);
			strftime(current_message_date, sizeof(current_message_date), "%B %d, %Y %H:00", time_ptr);
			current_message_date[sizeof(current_message_date) - 1] = '\x0';

			if (strcmp(last_message_date, current_message_date) != 0 && display_timebreaks == TRUE) {
				printf("</DIV>\n");
				printf("<BR>\n");
				printf("<DIV>\n");
				printf("<table border=0 width=99%% CLASS='dateTimeBreak' align=center><tr>");
				printf("<td width=40%%><hr width=100%%></td>");
				printf("<td align=center CLASS='dateTimeBreak'>%s</td>", current_message_date);
				printf("<td width=40%%><hr width=100%%></td>");
				printf("</tr></table>\n");
				printf("</DIV>\n");
				printf("<BR><DIV CLASS='logEntries'>\n");
				strncpy(last_message_date, current_message_date, sizeof(last_message_date));
				last_message_date[sizeof(last_message_date) - 1] = '\x0';
			}

			get_time_string(&temp_entry->timestamp, date_time, (int)sizeof(date_time), SHORT_DATE_TIME);
			strip(date_time);

			/* preparing logentries for json and csv output */
			if (content_type == CSV_CONTENT || content_type == JSON_CONTENT) {
				for (i = 0; i < strlen(temp_entry->entry_text) - 1; i++)
					*(temp_entry->entry_text + i) = *(temp_entry->entry_text + i + 1);
				temp_entry->entry_text[strlen(temp_entry->entry_text) - 1] = '\x0';
			}

			/* displays log entry depending on requested content type */
			if (content_type == JSON_CONTENT) {
				// always add a comma, except for the first line
				if (json_start == FALSE)
					printf(",\n");
				json_start = FALSE;
				printf("{ \"timestamp\": %lu, ", temp_entry->timestamp);
				printf(" \"date_time\": \"%s\", ", date_time);
				printf(" \"log_entry\": \"%s\"}", json_encode(temp_entry->entry_text));
			} else if (content_type == CSV_CONTENT) {
				printf("%s%lu%s%s", csv_data_enclosure, temp_entry->timestamp, csv_data_enclosure, csv_delimiter);
				printf("%s%s%s%s", csv_data_enclosure, date_time, csv_data_enclosure, csv_delimiter);
				printf("%s%s%s\n", csv_data_enclosure, temp_entry->entry_text, csv_data_enclosure);
			} else {
				if (display_frills == TRUE)
					printf("<img align=left src='%s%s' alt='%s' title='%s'>", url_images_path, image, image_alt, image_alt);
				printf("[%s] %s", date_time, (temp_entry->entry_text == NULL) ? "" : html_encode(temp_entry->entry_text, FALSE));
				if (enable_splunk_integration == TRUE) {
					printf("&nbsp;&nbsp;&nbsp;");
					display_splunk_generic_url(temp_entry->entry_text, 2);
				}
				printf("<br clear=all>\n");
			}

			user_has_seen_something = TRUE;
		}

		if (content_type != CSV_CONTENT && content_type != JSON_CONTENT) {
			if (user_has_seen_something == TRUE) {
				printf("</DIV><hr>\n");
				page_num_selector(result_start, total_entries, displayed_entries);
			} else {
				printf("<script type='text/javascript'>document.getElementById('log_page_selector').style.display='none';</script>");
			}
		} else if (content_type == JSON_CONTENT)
			printf("\n]\n");
	}

	free_log_entries(&entry_list);

	if (user_has_seen_something == FALSE && content_type != CSV_CONTENT && content_type != JSON_CONTENT)
		printf("<DIV CLASS='warningMessage'>No log entries found!</DIV>");

	return;
}
Beispiel #5
0
int heap_create(const char *name, HP_CREATE_INFO *create_info,
                HP_SHARE **res, my_bool *created_new_share)
{
    uint i, j, key_segs, max_length, length;
    HP_SHARE *share= 0;
    HA_KEYSEG *keyseg;
    HP_KEYDEF *keydef= create_info->keydef;
    uint reclength= create_info->reclength;
    uint keys= create_info->keys;
    ulong min_records= create_info->min_records;
    ulong max_records= create_info->max_records;
    DBUG_ENTER("heap_create");

    if (!create_info->internal_table)
    {
        mysql_mutex_lock(&THR_LOCK_heap);
        share= hp_find_named_heap(name);
        if (share && share->open_count == 0)
        {
            hp_free(share);
            share= 0;
        }
    }
    *created_new_share= (share == NULL);

    if (!share)
    {
        HP_KEYDEF *keyinfo;
        DBUG_PRINT("info",("Initializing new table"));

        /*
          We have to store sometimes uchar* del_link in records,
          so the record length should be at least sizeof(uchar*)
        */
        set_if_bigger(reclength, sizeof (uchar*));

        for (i= key_segs= max_length= 0, keyinfo= keydef; i < keys; i++, keyinfo++)
        {
            memset(&keyinfo->block, 0, sizeof(keyinfo->block));
            memset(&keyinfo->rb_tree, 0, sizeof(keyinfo->rb_tree));
            for (j= length= 0; j < keyinfo->keysegs; j++)
            {
                length+= keyinfo->seg[j].length;
                if (keyinfo->seg[j].null_bit)
                {
                    length++;
                    if (!(keyinfo->flag & HA_NULL_ARE_EQUAL))
                        keyinfo->flag|= HA_NULL_PART_KEY;
                    if (keyinfo->algorithm == HA_KEY_ALG_BTREE)
                        keyinfo->rb_tree.size_of_element++;
                }
                switch (keyinfo->seg[j].type) {
                case HA_KEYTYPE_SHORT_INT:
                case HA_KEYTYPE_LONG_INT:
                case HA_KEYTYPE_FLOAT:
                case HA_KEYTYPE_DOUBLE:
                case HA_KEYTYPE_USHORT_INT:
                case HA_KEYTYPE_ULONG_INT:
                case HA_KEYTYPE_LONGLONG:
                case HA_KEYTYPE_ULONGLONG:
                case HA_KEYTYPE_INT24:
                case HA_KEYTYPE_UINT24:
                case HA_KEYTYPE_INT8:
                    keyinfo->seg[j].flag|= HA_SWAP_KEY;
                    break;
                case HA_KEYTYPE_VARBINARY1:
                    /* Case-insensitiveness is handled in coll->hash_sort */
                    keyinfo->seg[j].type= HA_KEYTYPE_VARTEXT1;
                /* fall_through */
                case HA_KEYTYPE_VARTEXT1:
                    keyinfo->flag|= HA_VAR_LENGTH_KEY;
                    length+= 2;
                    /* Save number of bytes used to store length */
                    keyinfo->seg[j].bit_start= 1;
                    break;
                case HA_KEYTYPE_VARBINARY2:
                /* Case-insensitiveness is handled in coll->hash_sort */
                /* fall_through */
                case HA_KEYTYPE_VARTEXT2:
                    keyinfo->flag|= HA_VAR_LENGTH_KEY;
                    length+= 2;
                    /* Save number of bytes used to store length */
                    keyinfo->seg[j].bit_start= 2;
                    /*
                      Make future comparison simpler by only having to check for
                      one type
                    */
                    keyinfo->seg[j].type= HA_KEYTYPE_VARTEXT1;
                    break;
                default:
                    break;
                }
            }
            keyinfo->length= length;
            length+= keyinfo->rb_tree.size_of_element +
                     ((keyinfo->algorithm == HA_KEY_ALG_BTREE) ? sizeof(uchar*) : 0);
            if (length > max_length)
                max_length= length;
            key_segs+= keyinfo->keysegs;
            if (keyinfo->algorithm == HA_KEY_ALG_BTREE)
            {
                key_segs++; /* additional HA_KEYTYPE_END segment */
                if (keyinfo->flag & HA_VAR_LENGTH_KEY)
                    keyinfo->get_key_length= hp_rb_var_key_length;
                else if (keyinfo->flag & HA_NULL_PART_KEY)
                    keyinfo->get_key_length= hp_rb_null_key_length;
                else
                    keyinfo->get_key_length= hp_rb_key_length;
            }
        }
        if (!(share= (HP_SHARE*) my_malloc(hp_key_memory_HP_SHARE,
                                           (uint) sizeof(HP_SHARE)+
                                           keys*sizeof(HP_KEYDEF)+
                                           key_segs*sizeof(HA_KEYSEG),
                                           MYF(MY_ZEROFILL))))
            goto err;
        share->keydef= (HP_KEYDEF*) (share + 1);
        share->key_stat_version= 1;
        keyseg= (HA_KEYSEG*) (share->keydef + keys);
        init_block(&share->block, reclength + 1, min_records, max_records);
        /* Fix keys */
        memcpy(share->keydef, keydef, (size_t) (sizeof(keydef[0]) * keys));
        for (i= 0, keyinfo= share->keydef; i < keys; i++, keyinfo++)
        {
            keyinfo->seg= keyseg;
            memcpy(keyseg, keydef[i].seg,
                   (size_t) (sizeof(keyseg[0]) * keydef[i].keysegs));
            keyseg+= keydef[i].keysegs;

            if (keydef[i].algorithm == HA_KEY_ALG_BTREE)
            {
                /* additional HA_KEYTYPE_END keyseg */
                keyseg->type=     HA_KEYTYPE_END;
                keyseg->length=   sizeof(uchar*);
                keyseg->flag=     0;
                keyseg->null_bit= 0;
                keyseg++;

                init_tree(&keyinfo->rb_tree, 0, 0, sizeof(uchar*),
                          (qsort_cmp2)keys_compare, 1, NULL, NULL);
                keyinfo->delete_key= hp_rb_delete_key;
                keyinfo->write_key= hp_rb_write_key;
            }
            else
            {
                init_block(&keyinfo->block, sizeof(HASH_INFO), min_records,
                           max_records);
                keyinfo->delete_key= hp_delete_key;
                keyinfo->write_key= hp_write_key;
                keyinfo->hash_buckets= 0;
            }
            if ((keyinfo->flag & HA_AUTO_KEY) && create_info->with_auto_increment)
                share->auto_key= i + 1;
        }
        share->min_records= min_records;
        share->max_records= max_records;
        share->max_table_size= create_info->max_table_size;
        share->data_length= share->index_length= 0;
        share->reclength= reclength;
        share->blength= 1;
        share->keys= keys;
        share->max_key_length= max_length;
        share->changed= 0;
        share->auto_key= create_info->auto_key;
        share->auto_key_type= create_info->auto_key_type;
        share->auto_increment= create_info->auto_increment;
        share->create_time= (long) time((time_t*) 0);
        /* Must be allocated separately for rename to work */
        if (!(share->name= my_strdup(hp_key_memory_HP_SHARE,
                                     name, MYF(0))))
        {
            my_free(share);
            goto err;
        }
        if (!create_info->internal_table)
        {
            /*
              Do not initialize THR_LOCK object for internal temporary tables.
              It is not needed for such tables. Calling thr_lock_init() can
              cause scalability issues since it acquires global lock.
            */
            thr_lock_init(&share->lock);
            share->open_list.data= (void*) share;
            heap_share_list= list_add(heap_share_list,&share->open_list);
        }
        else
            share->delete_on_close= 1;
    }
    if (!create_info->internal_table)
    {
        if (create_info->pin_share)
            ++share->open_count;
        mysql_mutex_unlock(&THR_LOCK_heap);
    }

    *res= share;
    DBUG_RETURN(0);

err:
    if (!create_info->internal_table)
        mysql_mutex_unlock(&THR_LOCK_heap);
    DBUG_RETURN(1);
} /* heap_create */
Beispiel #6
0
int main(int argc, char **argv, char **env) {
    int result;
    int error = FALSE;
    char *buffer = NULL;
    int display_license = FALSE;
    int display_help = FALSE;
    int c = 0;
    struct tm *tm, tm_s;
    time_t now;
    char datestring[256];
    nagios_macros *mac;

#ifdef HAVE_GETOPT_H
    int option_index = 0;
    static struct option long_options[] = {
        {"help", no_argument, 0, 'h'},
        {"version", no_argument, 0, 'V'},
        {"license", no_argument, 0, 'V'},
        {"verify-config", no_argument, 0, 'v'},
        {"daemon", no_argument, 0, 'd'},
        {"test-scheduling", no_argument, 0, 's'},
        {"precache-objects", no_argument, 0, 'p'},
        {"use-precached-objects", no_argument, 0, 'u'},
        {"enable-timing-point", no_argument, 0, 'T'},
        {0, 0, 0, 0}
    };
#define getopt(argc, argv, o) getopt_long(argc, argv, o, long_options, &option_index)
#endif

    mac = get_global_macros();

    /* make sure we have the correct number of command line arguments */
    if(argc < 2)
        error = TRUE;

    /* get all command line arguments */
    while(1) {
        c = getopt(argc, argv, "+hVvdspuxT");

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

        switch(c) {

        case '?': /* usage */
        case 'h':
            display_help = TRUE;
            break;

        case 'V': /* version */
            display_license = TRUE;
            break;

        case 'v': /* verify */
            verify_config++;
            break;

        case 's': /* scheduling check */
            test_scheduling = TRUE;
            break;

        case 'd': /* daemon mode */
            daemon_mode = TRUE;
            break;

        case 'p': /* precache object config */
            precache_objects = TRUE;
            break;

        case 'u': /* use precached object config */
            use_precached_objects = TRUE;
            break;
        case 'T':
            enable_timing_point = TRUE;
            break;

        case 'x':
            printf("Warning: -x is deprecated and will be removed\n");
            break;

        default:
            break;
        }

    }

#ifdef DEBUG_MEMORY
    mtrace();
#endif

    if(daemon_mode == FALSE) {
        printf("\nNagios Core %s\n", PROGRAM_VERSION);
        printf("Copyright (c) 2009-2011 Nagios Core Development Team and Community Contributors\n");
        printf("Copyright (c) 1999-2009 Ethan Galstad\n");
        printf("Last Modified: %s\n", PROGRAM_MODIFICATION_DATE);
        printf("License: GPL\n\n");
        printf("Website: http://www.nagios.org\n");
    }

    /* just display the license */
    if(display_license == TRUE) {

        printf("This program is free software; you can redistribute it and/or modify\n");
        printf("it under the terms of the GNU General Public License version 2 as\n");
        printf("published by the Free Software Foundation.\n\n");
        printf("This program is distributed in the hope that it will be useful,\n");
        printf("but WITHOUT ANY WARRANTY; without even the implied warranty of\n");
        printf("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n");
        printf("GNU General Public License for more details.\n\n");
        printf("You should have received a copy of the GNU General Public License\n");
        printf("along with this program; if not, write to the Free Software\n");
        printf("Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\n");

        exit(OK);
    }

    /* make sure we got the main config file on the command line... */
    if(optind >= argc)
        error = TRUE;

    /* if there are no command line options (or if we encountered an error), print usage */
    if(error == TRUE || display_help == TRUE) {

        printf("Usage: %s [options] <main_config_file>\n", argv[0]);
        printf("\n");
        printf("Options:\n");
        printf("\n");
        printf("  -v, --verify-config          Verify all configuration data (-v -v for more info)\n");
        printf("  -s, --test-scheduling        Shows projected/recommended check scheduling and other\n");
        printf("                               diagnostic info based on the current configuration files.\n");
        printf("  -T, --enable-timing-point    Enable timed commentary on initialization\n");
        /*printf("  -o, --dont-verify-objects    Don't verify object relationships - USE WITH CAUTION!\n");*/
        printf("  -x, --dont-verify-paths      Don't check for circular object paths - USE WITH CAUTION!\n");
        printf("  -p, --precache-objects       Precache object configuration\n");
        printf("  -u, --use-precached-objects  Use precached object config file\n");
        printf("  -d, --daemon                 Starts Nagios in daemon mode, instead of as a foreground process\n");
        printf("\n");
        printf("Visit the Nagios website at http://www.nagios.org/ for bug fixes, new\n");
        printf("releases, online documentation, FAQs, information on subscribing to\n");
        printf("the mailing lists, and commercial support options for Nagios.\n");
        printf("\n");

        exit(ERROR);
    }


    /* config file is last argument specified */
    config_file = (char *)strdup(argv[optind]);
    if(config_file == NULL) {
        printf("Error allocating memory.\n");
        exit(ERROR);
    }

    /* make sure the config file uses an absolute path */
    if(config_file[0] != '/') {

        /* save the name of the config file */
        buffer = (char *)strdup(config_file);

        /* reallocate a larger chunk of memory */
        config_file = (char *)realloc(config_file, MAX_FILENAME_LENGTH);
        if(config_file == NULL) {
            printf("Error allocating memory.\n");
            exit(ERROR);
        }

        /* get absolute path of current working directory */
        getcwd(config_file, MAX_FILENAME_LENGTH);

        /* append a forward slash */
        strncat(config_file, "/", 1);
        config_file[MAX_FILENAME_LENGTH - 1] = '\x0';

        /* append the config file to the path */
        strncat(config_file, buffer, MAX_FILENAME_LENGTH - strlen(config_file) - 1);
        config_file[MAX_FILENAME_LENGTH - 1] = '\x0';

        my_free(buffer);
    }

    /*
     * let's go to town. We'll be noisy if we're verifying config
     * or running scheduling tests.
     */
    if(verify_config || test_scheduling || precache_objects) {
        reset_variables();

        if(verify_config)
            printf("Reading configuration data...\n");

        /* read our config file */
        result = read_main_config_file(config_file);
        if(result != OK) {
            printf("   Error processing main config file!\n\n");
            exit(EXIT_FAILURE);
        }

        if(verify_config)
            printf("   Read main config file okay...\n");

        /* drop privileges */
        if((result = drop_privileges(nagios_user, nagios_group)) == ERROR) {
            printf("   Failed to drop privileges.  Aborting.");
            exit(EXIT_FAILURE);
        }

        /* read object config files */
        result = read_all_object_data(config_file);
        if(result != OK) {
            printf("   Error processing object config files!\n\n");
            /* if the config filename looks fishy, warn the user */
            if(!strstr(config_file, "nagios.cfg")) {
                printf("\n***> The name of the main configuration file looks suspicious...\n");
                printf("\n");
                printf("     Make sure you are specifying the name of the MAIN configuration file on\n");
                printf("     the command line and not the name of another configuration file.  The\n");
                printf("     main configuration file is typically '/usr/local/nagios/etc/nagios.cfg'\n");
            }

            printf("\n***> One or more problems was encountered while processing the config files...\n");
            printf("\n");
            printf("     Check your configuration file(s) to ensure that they contain valid\n");
            printf("     directives and data defintions.  If you are upgrading from a previous\n");
            printf("     version of Nagios, you should be aware that some variables/definitions\n");
            printf("     may have been removed or modified in this version.  Make sure to read\n");
            printf("     the HTML documentation regarding the config files, as well as the\n");
            printf("     'Whats New' section to find out what has changed.\n\n");
            exit(EXIT_FAILURE);
        }

        if(verify_config) {
            printf("   Read object config files okay...\n\n");
            printf("Running pre-flight check on configuration data...\n\n");
        }

        /* run the pre-flight check to make sure things look okay... */
        result = pre_flight_check();

        if(result != OK) {
            printf("\n***> One or more problems was encountered while running the pre-flight check...\n");
            printf("\n");
            printf("     Check your configuration file(s) to ensure that they contain valid\n");
            printf("     directives and data defintions.  If you are upgrading from a previous\n");
            printf("     version of Nagios, you should be aware that some variables/definitions\n");
            printf("     may have been removed or modified in this version.  Make sure to read\n");
            printf("     the HTML documentation regarding the config files, as well as the\n");
            printf("     'Whats New' section to find out what has changed.\n\n");
            exit(EXIT_FAILURE);
        }

        if(verify_config) {
            printf("\nThings look okay - No serious problems were detected during the pre-flight check\n");
        }

        /* scheduling tests need a bit more than config verifications */
        if(test_scheduling == TRUE) {

            /* we'll need the event queue here so we can time insertions */
            init_event_queue();
            timing_point("Done initializing event queue\n");

            /* read initial service and host state information */
            initialize_retention_data(config_file);
            read_initial_state_information();
            timing_point("Retention data and initial state parsed\n");

            /* initialize the event timing loop */
            init_timing_loop();
            timing_point("Timing loop initialized\n");

            /* display scheduling information */
            display_scheduling_info();
        }

        if(precache_objects) {
            result = fcache_objects(object_precache_file);
            timing_point("Done precaching objects\n");
            if(result == OK) {
                printf("Object precache file created:\n%s\n", object_precache_file);
            }
            else {
                printf("Failed to precache objects to '%s': %s\n", object_precache_file, strerror(errno));
            }
        }

        /* clean up after ourselves */
        cleanup();

        /* exit */
        timing_point("Exiting\n");
        exit(result);
    }


    /* else start to monitor things... */
    else {

        nagios_iobs = iobroker_create();

        /* keep monitoring things until we get a shutdown command */
        do {

            init_event_queue();

            /* reset program variables */
            reset_variables();

            /* get PID */
            nagios_pid = (int)getpid();

            /* read in the configuration files (main and resource config files) */
            result = read_main_config_file(config_file);

            /* NOTE 11/06/07 EG moved to after we read config files, as user may have overridden timezone offset */
            /* get program (re)start time and save as macro */
            program_start = time(NULL);
            my_free(mac->x[MACRO_PROCESSSTARTTIME]);
            asprintf(&mac->x[MACRO_PROCESSSTARTTIME], "%lu", (unsigned long)program_start);

            /* open debug log */
            open_debug_log();

            /* drop privileges */
            if(drop_privileges(nagios_user, nagios_group) == ERROR) {

                logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR | NSLOG_CONFIG_ERROR, TRUE, "Failed to drop privileges.  Aborting.");

                cleanup();
                exit(ERROR);
            }

#ifdef USE_EVENT_BROKER
            /* initialize modules */
            neb_init_modules();
            neb_init_callback_list();
#endif

            /* this must be logged after we read config data, as user may have changed location of main log file */
            logit(NSLOG_PROCESS_INFO, TRUE, "Nagios %s starting... (PID=%d)\n", PROGRAM_VERSION, (int)getpid());

            /* log the local time - may be different than clock time due to timezone offset */
            now = time(NULL);
            tm = localtime_r(&now, &tm_s);
            strftime(datestring, sizeof(datestring), "%a %b %d %H:%M:%S %Z %Y", tm);
            logit(NSLOG_PROCESS_INFO, TRUE, "Local time is %s", datestring);

            /* write log version/info */
            write_log_file_info(NULL);

#ifdef USE_EVENT_BROKER
            /* load modules */
            neb_load_all_modules();

            /* send program data to broker */
            broker_program_state(NEBTYPE_PROCESS_PRELAUNCH, NEBFLAG_NONE, NEBATTR_NONE, NULL);
#endif

            /* read in all object config data */
            if(result == OK)
                result = read_all_object_data(config_file);

            /* there was a problem reading the config files */
            if(result != OK)
                logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR | NSLOG_CONFIG_ERROR, TRUE, "Bailing out due to one or more errors encountered in the configuration files. Run Nagios from the command line with the -v option to verify your config before restarting. (PID=%d)", (int)getpid());

            else {

                /* run the pre-flight check to make sure everything looks okay*/
                if((result = pre_flight_check()) != OK)
                    logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR | NSLOG_VERIFICATION_ERROR, TRUE, "Bailing out due to errors encountered while running the pre-flight check.  Run Nagios from the command line with the -v option to verify your config before restarting. (PID=%d)\n", (int)getpid());
            }

            /* an error occurred that prevented us from (re)starting */
            if(result != OK) {

                /* if we were restarting, we need to cleanup from the previous run */
                if(sigrestart == TRUE) {

                    /* clean up the status data */
                    cleanup_status_data(config_file, TRUE);
                }

#ifdef USE_EVENT_BROKER
                /* send program data to broker */
                broker_program_state(NEBTYPE_PROCESS_SHUTDOWN, NEBFLAG_PROCESS_INITIATED, NEBATTR_SHUTDOWN_ABNORMAL, NULL);
#endif
                cleanup();
                exit(ERROR);
            }

            /* write the objects.cache file */
            fcache_objects(object_cache_file);

            /* handle signals (interrupts) */
            setup_sighandler();


#ifdef USE_EVENT_BROKER
            /* send program data to broker */
            broker_program_state(NEBTYPE_PROCESS_START, NEBFLAG_NONE, NEBATTR_NONE, NULL);
#endif

            /* enter daemon mode (unless we're restarting...) */
            if(daemon_mode == TRUE && sigrestart == FALSE) {

                result = daemon_init();

                /* we had an error daemonizing, so bail... */
                if(result == ERROR) {
                    logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR, TRUE, "Bailing out due to failure to daemonize. (PID=%d)", (int)getpid());

#ifdef USE_EVENT_BROKER
                    /* send program data to broker */
                    broker_program_state(NEBTYPE_PROCESS_SHUTDOWN, NEBFLAG_PROCESS_INITIATED, NEBATTR_SHUTDOWN_ABNORMAL, NULL);
#endif
                    cleanup();
                    exit(ERROR);
                }

                asprintf(&buffer, "Finished daemonizing... (New PID=%d)\n", (int)getpid());
                write_to_all_logs(buffer, NSLOG_PROCESS_INFO);
                my_free(buffer);

                /* get new PID */
                nagios_pid = (int)getpid();
            }

            /* initialize status data unless we're starting */
            if(sigrestart == FALSE)
                initialize_status_data(config_file);

            /* read initial service and host state information  */
            initialize_retention_data(config_file);
            read_initial_state_information();

            /* initialize comment data */
            initialize_comment_data(config_file);

            /* initialize scheduled downtime data */
            initialize_downtime_data(config_file);

            /* initialize performance data */
            initialize_performance_data(config_file);

            /* initialize the event timing loop */
            init_timing_loop();

            /* initialize check statistics */
            init_check_stats();

            /* check for updates */
            check_for_nagios_updates(FALSE, TRUE);

            /* update all status data (with retained information) */
            update_all_status_data();

            /* log initial host and service state */
            log_host_states(INITIAL_STATES, NULL);
            log_service_states(INITIAL_STATES, NULL);

            /* reset the restart flag */
            sigrestart = FALSE;

            /* fire up command file worker */
            launch_command_file_worker();

            /* @TODO: get number of workers from config */
            init_workers(4);

#ifdef USE_EVENT_BROKER
            /* send program data to broker */
            broker_program_state(NEBTYPE_PROCESS_EVENTLOOPSTART, NEBFLAG_NONE, NEBATTR_NONE, NULL);
#endif

            /* get event start time and save as macro */
            event_start = time(NULL);
            my_free(mac->x[MACRO_EVENTSTARTTIME]);
            asprintf(&mac->x[MACRO_EVENTSTARTTIME], "%lu", (unsigned long)event_start);

            /***** start monitoring all services *****/
            /* (doesn't return until a restart or shutdown signal is encountered) */
            event_execution_loop();

            /* 03/01/2007 EG Moved from sighandler() to prevent FUTEX locking problems under NPTL */
            /* 03/21/2007 EG SIGSEGV signals are still logged in sighandler() so we don't loose them */
            /* did we catch a signal? */
            if(caught_signal == TRUE) {

                if(sig_id == SIGHUP)
                    logit(NSLOG_PROCESS_INFO, TRUE, "Caught SIGHUP, restarting...\n");

            }

#ifdef USE_EVENT_BROKER
            /* send program data to broker */
            broker_program_state(NEBTYPE_PROCESS_EVENTLOOPEND, NEBFLAG_NONE, NEBATTR_NONE, NULL);
            if(sigshutdown == TRUE)
                broker_program_state(NEBTYPE_PROCESS_SHUTDOWN, NEBFLAG_USER_INITIATED, NEBATTR_SHUTDOWN_NORMAL, NULL);
            else if(sigrestart == TRUE)
                broker_program_state(NEBTYPE_PROCESS_RESTART, NEBFLAG_USER_INITIATED, NEBATTR_RESTART_NORMAL, NULL);
#endif

            /* save service and host state information */
            save_state_information(FALSE);
            cleanup_retention_data(config_file);

            /* clean up performance data */
            cleanup_performance_data(config_file);

            /* clean up the scheduled downtime data */
            cleanup_downtime_data(config_file);

            /* clean up the status data unless we're restarting */
            if(sigrestart == FALSE) {
                cleanup_status_data(config_file, TRUE);
            }

            /* shutdown stuff... */
            if(sigshutdown == TRUE) {
                free_worker_memory(WPROC_FORCE);
                iobroker_destroy(nagios_iobs, IOBROKER_CLOSE_SOCKETS);

                /* make sure lock file has been removed - it may not have been if we received a shutdown command */
                if(daemon_mode == TRUE)
                    unlink(lock_file);

                /* log a shutdown message */
                logit(NSLOG_PROCESS_INFO, TRUE, "Successfully shutdown... (PID=%d)\n", (int)getpid());
            }

            /* clean up after ourselves */
            cleanup();

            /* close debug log */
            close_debug_log();

        }
        while(sigrestart == TRUE && sigshutdown == FALSE);

        /* free misc memory */
        my_free(config_file);
    }

    return OK;
}
int my_security_attr_create(SECURITY_ATTRIBUTES **psa, const char **perror,
                            DWORD owner_rights, DWORD everyone_rights)
{
    /* Top-level SID authority */
    SID_IDENTIFIER_AUTHORITY world_auth= SECURITY_WORLD_SID_AUTHORITY;
    PSID everyone_sid= 0;
    HANDLE htoken= 0;
    SECURITY_ATTRIBUTES *sa= 0;
    PACL dacl= 0;
    DWORD owner_token_length, dacl_length;
    SECURITY_DESCRIPTOR *sd;
    PTOKEN_USER owner_token;
    PSID owner_sid;
    My_security_attr *attr;

    if (! is_nt())
    {
        *psa= 0;
        return 0;
    }

    /*
      Get SID of Everyone group. Easier to retrieve all SIDs each time
      this function is called than worry about thread safety.
    */
    if (! AllocateAndInitializeSid(&world_auth, 1, SECURITY_WORLD_RID,
                                   0, 0, 0, 0, 0, 0, 0, &everyone_sid))
    {
        *perror= "Failed to retrieve the SID of Everyone group";
        goto error;
    }

    /*
      Get SID of the owner. Using GetSecurityInfo this task can be done
      in just one call instead of five, but GetSecurityInfo declared in
      aclapi.h, so I hesitate to use it.
      SIC: OpenThreadToken works only if there is an active impersonation
      token, hence OpenProcessToken is used.
    */
    if (! OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &htoken))
    {
        *perror= "Failed to retrieve thread access token";
        goto error;
    }
    GetTokenInformation(htoken, TokenUser, 0, 0, &owner_token_length);

    if (! my_multi_malloc(key_memory_win_SECURITY_ATTRIBUTES,
                          MYF(MY_WME),
                          &sa, ALIGN_SIZE(sizeof(SECURITY_ATTRIBUTES)) +
                          sizeof(My_security_attr),
                          &sd, sizeof(SECURITY_DESCRIPTOR),
                          &owner_token, owner_token_length,
                          0))
    {
        *perror= "Failed to allocate memory for SECURITY_ATTRIBUTES";
        goto error;
    }
    memset(owner_token, 0, owner_token_length);
    if (! GetTokenInformation(htoken, TokenUser, owner_token,
                              owner_token_length, &owner_token_length))
    {
        *perror= "GetTokenInformation failed";
        goto error;
    }
    owner_sid= owner_token->User.Sid;

    if (! IsValidSid(owner_sid))
    {
        *perror= "IsValidSid failed";
        goto error;
    }

    /* Calculate the amount of memory that must be allocated for the DACL */
    dacl_length= sizeof(ACL) + (sizeof(ACCESS_ALLOWED_ACE)-sizeof(DWORD)) * 2 +
                 GetLengthSid(everyone_sid) + GetLengthSid(owner_sid);

    /* Create an ACL */
    if (! (dacl= (PACL) my_malloc(key_memory_win_PACL,
                                  dacl_length, MYF(MY_ZEROFILL|MY_WME))))
    {
        *perror= "Failed to allocate memory for DACL";
        goto error;
    }
    if (! InitializeAcl(dacl, dacl_length, ACL_REVISION))
    {
        *perror= "Failed to initialize DACL";
        goto error;
    }
    if (! AddAccessAllowedAce(dacl, ACL_REVISION, everyone_rights, everyone_sid))
    {
        *perror= "Failed to set up DACL";
        goto error;
    }
    if (! AddAccessAllowedAce(dacl, ACL_REVISION, owner_rights, owner_sid))
    {
        *perror= "Failed to set up DACL";
        goto error;
    }
    if (! InitializeSecurityDescriptor(sd, SECURITY_DESCRIPTOR_REVISION))
    {
        *perror= "Could not initialize security descriptor";
        goto error;
    }
    if (! SetSecurityDescriptorDacl(sd, TRUE, dacl, FALSE))
    {
        *perror= "Failed to install DACL";
        goto error;
    }

    sa->nLength= sizeof(*sa);
    sa->bInheritHandle= TRUE;
    sa->lpSecurityDescriptor= sd;
    /* Save pointers to everyone_sid and dacl to be able to clean them up */
    attr= (My_security_attr*) (((char*) sa) + ALIGN_SIZE(sizeof(*sa)));
    attr->everyone_sid= everyone_sid;
    attr->dacl= dacl;
    *psa= sa;

    CloseHandle(htoken);
    return 0;
error:
    if (everyone_sid)
        FreeSid(everyone_sid);
    if (htoken)
        CloseHandle(htoken);
    my_free(sa);
    my_free(dacl);
    *psa= 0;
    return 1;
}
Beispiel #8
0
long PackCheckUFOS(const char * FileName, PUCHAR BaseString, long readed, long &HeadOffset, long &SomeOffset, long &FileSize, long &FileOffset, struct RIP_FILE_INFO **finfo, long &FilesNumber, long WorkFileSize, struct RIP_SERVICE_FUNC *func, struct RIP_FLAGS *flags)
{       
#pragma pack(1)
    struct FATItem{        
        long offset;
        long unpsize;
        long type;
        long packsize;                
    }Item;
#pragma pack(8)

    long rd, SOffset, FOffset, z=0;
    char s[MAX_PATH];
    long nFiles;
    bool WasError = false;
    int errorfrom;

    RIP_FILE_INFO * fi;    
    
    unsigned char t[]={0x41,0x72,0x74,0x65,0x63,0x68,0x00,0x00};//ID

    long fres = func->Find(t, BaseString, sizeof t, readed);
    if (fres == -1) return -1;
    
    SOffset = FileOffset+fres;

    FOffset = SOffset+sizeof t+4;
    rd =  func->ReadFromFile(FileName, FOffset, &nFiles, sizeof nFiles);
    if (rd < sizeof nFiles) return -1;

    if  ((nFiles<1)||
         (nFiles*sizeof Item>WorkFileSize)) return -1;    
        
    FOffset += rd+4;

    fi = (RIP_FILE_INFO*)my_malloc(sizeof(RIP_FILE_INFO)*nFiles);
    if (fi == NULL) return -1;
    *finfo = fi;    

    FilesNumber = nFiles;    
        
    for (int i = 0; i<FilesNumber; i++){    
        rd =  func->ReadFromFile(FileName, FOffset, &Item, sizeof Item);
        if (rd < sizeof Item)  {
            WasError = true;
            errorfrom = i;
            break;
        }
        FOffset += rd;        
        
        memset(&fi[i], 0, sizeof(RIP_FILE_INFO));
        
        fi[i].StartOffset = Item.offset+SOffset;
        fi[i].FileSize    = Item.packsize;
        

        if (fi[i].StartOffset+fi[i].FileSize>WorkFileSize) {
            WasError = true;
            errorfrom = i;
            break;
        }

        if (fi[i].StartOffset+fi[i].FileSize>z) z=fi[i].StartOffset+fi[i].FileSize;

        if (i< 10)           sprintf(s, "strm000%d", i);
        else if (i< 100)     sprintf(s, "strm00%d",  i);
        else if (i< 1000)    sprintf(s, "strm%d",    i);
        else if (i< 10000)   sprintf(s, "str%d",     i);
        else if (i< 100000)  sprintf(s, "st%d",      i);
        else if (i< 1000000) sprintf(s, "s%d",       i);
        else                 sprintf(s, "%d",        i);

        fi[i].FullFileName = my_strdup(s);
        fi[i].Description = my_strdup("");        
        
    }

    if (WasError){
        for (int j=0; j<errorfrom; j++){
            my_free(fi[j].FullFileName);                
            my_free(fi[j].Description);        
        }
        my_free(fi);
        fi = NULL;
        return -1;
    }

    FileOffset = SOffset;
    FileSize = z-SOffset;
    return z;
}
Beispiel #9
0
static void xml_element_serialize(xml_element *el, int (*fptr)(void *data, const char *text, int size), void *data, XML_ELEM_OUTPUT_OPTIONS options, int depth)
{
   int i;
   static STRUCT_XML_ELEM_OUTPUT_OPTIONS default_opts = {xml_elem_pretty, xml_elem_markup_escaping | xml_elem_non_print_escaping, XML_DECL_ENCODING_DEFAULT};
   static char whitespace[] = "                                                                                               "
                              "                                                                                               "
                              "                                                                                               ";
   depth++;

   if(!el) {
      /* fprintf(stderr, "Nothing to write\n"); */
      return;
   }
   if(!options) {
      options = &default_opts;
   }

   /* print xml declaration if at root level */
   if(depth == 1) {
      xml_elem_writefunc(fptr, XML_DECL_START, data, XML_DECL_START_LEN);
      xml_elem_writefunc(fptr, WHITESPACE, data, WHITESPACE_LEN);
      xml_elem_writefunc(fptr, XML_DECL_VERSION, data, XML_DECL_VERSION_LEN);
      if(options->encoding && *options->encoding) {
          xml_elem_writefunc(fptr, WHITESPACE, data, WHITESPACE_LEN);
          xml_elem_writefunc(fptr, XML_DECL_ENCODING_ATTR, data, XML_DECL_ENCODING_ATTR_LEN);
          xml_elem_writefunc(fptr, EQUALS, data, EQUALS_LEN);
          xml_elem_writefunc(fptr, ATTR_DELIMITER, data, ATTR_DELIMITER_LEN);
          xml_elem_writefunc(fptr, options->encoding, data, 0);
          xml_elem_writefunc(fptr, ATTR_DELIMITER, data, ATTR_DELIMITER_LEN);
      }
      xml_elem_writefunc(fptr, XML_DECL_END, data, XML_DECL_END_LEN);
      if(options->verbosity != xml_elem_no_white_space) {
         xml_elem_writefunc(fptr, NEWLINE, data, NEWLINE_LEN);
      }
   }

   if(options->verbosity == xml_elem_pretty && depth > 2) {
         xml_elem_writefunc(fptr, whitespace, data, depth - 2);
   }
   /* begin element */
   xml_elem_writefunc(fptr,START_TOKEN_BEGIN, data, START_TOKEN_BEGIN_LEN);
   if(el->name) {
      xml_elem_writefunc(fptr, el->name, data, 0);

      /* write attrs, if any */
      if(Q_Size(&el->attrs)) {
         xml_element_attr* iter = Q_Head(&el->attrs);
         while( iter ) {
            xml_elem_writefunc(fptr, WHITESPACE, data, WHITESPACE_LEN);
            xml_elem_writefunc(fptr, iter->key, data, 0);
            xml_elem_writefunc(fptr, EQUALS, data, EQUALS_LEN);
            xml_elem_writefunc(fptr, ATTR_DELIMITER, data, ATTR_DELIMITER_LEN);
            xml_elem_writefunc(fptr, iter->val, data, 0);
            xml_elem_writefunc(fptr, ATTR_DELIMITER, data, ATTR_DELIMITER_LEN);

            iter = Q_Next(&el->attrs);
         }
      }
   }
   else {
      xml_elem_writefunc(fptr, "None", data, 0);
   }
   /* if no text and no children, use abbreviated form, eg: <foo/> */
   if(!el->text.len && !Q_Size(&el->children)) {
       xml_elem_writefunc(fptr, EMPTY_START_TOKEN_END, data, EMPTY_START_TOKEN_END_LEN);
   }
   /* otherwise, print element contents */
   else {
       xml_elem_writefunc(fptr, START_TOKEN_END, data, START_TOKEN_END_LEN);

       /* print text, if any */
       if(el->text.len) {
          char* escaped_str = el->text.str;
          int buflen = el->text.len;

          if(options->escaping && options->escaping != xml_elem_cdata_escaping) {
             escaped_str = xml_elem_entity_escape(el->text.str, buflen, &buflen, options->escaping );
             if(!escaped_str) {
                escaped_str = el->text.str;
             }
          }

          if(options->escaping & xml_elem_cdata_escaping) {
             xml_elem_writefunc(fptr, CDATA_BEGIN, data, CDATA_BEGIN_LEN);
          }

          xml_elem_writefunc(fptr, escaped_str, data, buflen);

          if(escaped_str != el->text.str) {
             my_free(escaped_str);
          }

          if(options->escaping & xml_elem_cdata_escaping) {
             xml_elem_writefunc(fptr, CDATA_END, data, CDATA_END_LEN);
          }
       }
       /* no text, so print child elems */
       else {
          xml_element *kids = Q_Head(&el->children);
          i = 0;
          while( kids ) {
             if(i++ == 0) {
                if(options->verbosity != xml_elem_no_white_space) {
                   xml_elem_writefunc(fptr, NEWLINE, data, NEWLINE_LEN);
                }
             }
             xml_element_serialize(kids, fptr, data, options, depth);
             kids = Q_Next(&el->children);
          }
          if(i) {
             if(options->verbosity == xml_elem_pretty && depth > 2) {
                   xml_elem_writefunc(fptr, whitespace, data, depth - 2);
             }
          }
       }

       xml_elem_writefunc(fptr, END_TOKEN_BEGIN, data, END_TOKEN_BEGIN_LEN);
       xml_elem_writefunc(fptr,el->name ? el->name : "None", data, 0);
       xml_elem_writefunc(fptr, END_TOKEN_END, data, END_TOKEN_END_LEN);
   }
   if(options->verbosity != xml_elem_no_white_space) {
      xml_elem_writefunc(fptr, NEWLINE, data, NEWLINE_LEN);
   }
}
Beispiel #10
0
void impute_info_free(ImputeInfo *impute_info) {
  my_free(impute_info->buf);
  my_free(impute_info);
}
Beispiel #11
0
int
main(int argc, char**	argv)
{
  char*	server_key = 0,	*server_cert = 0;
  char*	client_key = 0,	*client_cert = 0;
  char*	ca_file = 0,	*ca_path = 0;
  char*	cipher=0;
  int	child_pid,sv[2];
  my_bool unused;
  struct st_VioSSLAcceptorFd* ssl_acceptor=0;
  struct st_VioSSLConnectorFd* ssl_connector=0; 
  Vio* client_vio=0, *server_vio=0;
  MY_INIT(argv[0]);
  DBUG_PROCESS(argv[0]);
  DBUG_PUSH(default_dbug_option);

  if (argc<5)
  {
    print_usage();
    return 1;
  }

  server_key = argv[1];
  server_cert = argv[2];
  client_key = argv[3];
  client_cert = argv[4];
  if (argc>5)
    ca_file = argv[5];
  if (argc>6)
    ca_path = argv[6];
  printf("Server key/cert : %s/%s\n", server_key, server_cert);
  printf("Client key/cert : %s/%s\n", client_key, client_cert);
  if (ca_file!=0)
    printf("CAfile          : %s\n", ca_file);
  if (ca_path!=0)
    printf("CApath          : %s\n", ca_path);


  if (socketpair(PF_UNIX, SOCK_STREAM, IPPROTO_IP, sv)==-1)
    fatal_error("socketpair");

  ssl_acceptor = new_VioSSLAcceptorFd(server_key, server_cert, ca_file,
				      ca_path, cipher);
  ssl_connector = new_VioSSLConnectorFd(client_key, client_cert, ca_file,
					ca_path, cipher);

  client_vio = (struct st_vio*)my_malloc(sizeof(struct st_vio),MYF(0));
  client_vio->sd = sv[0];
  client_vio->vioblocking(client_vio, 0, &unused);
  sslconnect(ssl_connector,client_vio,60L);
  server_vio = (struct st_vio*)my_malloc(sizeof(struct st_vio),MYF(0));
  server_vio->sd = sv[1];
  server_vio->vioblocking(client_vio, 0, &unused);
  sslaccept(ssl_acceptor,server_vio,60L);

  printf("Socketpair: %d , %d\n", client_vio->sd, server_vio->sd);

  child_pid = fork();
  if (child_pid==-1) {
    my_free((gptr)ssl_acceptor,MYF(0));
    my_free((gptr)ssl_connector,MYF(0));
    fatal_error("fork");
  }
  if (child_pid==0)
  {
    /* child, therefore, client */
    char	xbuf[100];
    int	r = client_vio->read(client_vio,xbuf, sizeof(xbuf));
    if (r<=0) {
      my_free((gptr)ssl_acceptor,MYF(0));
      my_free((gptr)ssl_connector,MYF(0));
      fatal_error("client:SSL_read");
    }
    xbuf[r] = 0;
    printf("client:got %s\n", xbuf);
    my_free((gptr)client_vio,MYF(0));
    my_free((gptr)ssl_acceptor,MYF(0));
    my_free((gptr)ssl_connector,MYF(0));
  }
  else
  {
    const char*	s = "Huhuhuh";
    int		r = server_vio->write(server_vio,(gptr)s, strlen(s));
    if (r<=0) {
      my_free((gptr)ssl_acceptor,MYF(0));
      my_free((gptr)ssl_connector,MYF(0));
      fatal_error("server:SSL_write");
    }
    my_free((gptr)server_vio,MYF(0));
    my_free((gptr)ssl_acceptor,MYF(0));
    my_free((gptr)ssl_connector,MYF(0));
  }
  return 0;
}
Beispiel #12
0
void merge_vcf(int n_vcf, char **vcf_filenames) {
  FileInfo *f_info;
  int n_done, n_chrom, i, *is_lowest, *lowest, n_lowest;
  int ret, use_geno_probs, use_haplotypes;
  Chromosome *chrom_tab;

  f_info = init_file_info(n_vcf, vcf_filenames);
  
  /* find chromosomes that are present in ALL VCFs */
  chrom_tab = chrom_table_intersect(f_info, n_vcf, &n_chrom);
  n_done = 0;
  is_lowest = my_malloc(sizeof(int) * n_vcf);
  lowest = my_malloc(sizeof(int) * n_vcf);

  /* only use genotypes and haplotypes if they are present in ALL files */
  use_geno_probs = TRUE;
  use_haplotypes = TRUE;
  
  /* read first SNP from all files */
  for(i = 0; i < n_vcf; i++) {
    ret = vcf_read_line(f_info[i].gzf, f_info[i].vcf, &f_info[i].cur_snp);
    if(ret == -1) {
      /* file is over */
      n_done += 1;
      f_info[i].is_done = TRUE;
      my_warn("file %s contains no SNPs\n", vcf_filenames[i]);
      f_info[i].cur_chrom = NULL;
    } else {
      set_cur_chrom(&f_info[i], chrom_tab, n_chrom);

      if(!f_info[i].cur_snp.has_geno_probs) {
	if(use_geno_probs) {
	  fprintf(stderr, "Not using genotype likelihoods (GL) because "
		  "not present in file %s\n", vcf_filenames[i]);
	}
	use_geno_probs = FALSE;
      }
      if(!f_info[i].cur_snp.has_haplotypes) {
	if(use_haplotypes) {
	  fprintf(stderr, "Not using genotypes (GT) because "
		  "not present in file %s\n", vcf_filenames[i]);
	}
	use_haplotypes = FALSE;
      }
    }
  }
  
  fprintf(stderr, "parsing files\n");

  while(n_done < n_vcf) {
    /* find SNP(s) with lowest (chrom, pos) */
    find_lowest(f_info, n_vcf, is_lowest, lowest, &n_lowest);

    /* merge counts and write line for these SNPs */
    write_output(stdout, f_info, n_vcf, is_lowest, lowest,
		 use_geno_probs, use_haplotypes);
    
    /* advance files with lowest SNPs */
    for(i = 0; i < n_vcf; i++) {
      if(!f_info[i].is_done && is_lowest[i]) {
	if(vcf_read_line(f_info[i].gzf, f_info[i].vcf, &f_info[i].cur_snp) == -1) {
	  /* have reached end of this file */
	  n_done += 1;
	  f_info[i].is_done = TRUE;
	}
      }
    }
  }
  
  fprintf(stderr, "done!\n");

  free_file_info(f_info, n_vcf);
  for(i = 0; i < n_chrom; i++) {
    my_free(chrom_tab[i].name);
    my_free(chrom_tab[i].assembly);
  }
  my_free(chrom_tab);
  my_free(is_lowest);
  
}
Beispiel #13
0
int mi_preload(MI_INFO *info, ulonglong key_map, my_bool ignore_leaves)
{
  uint i;
  ulong length, block_length= 0;
  uchar *buff= NULL;
  MYISAM_SHARE* share= info->s;
  uint keys= share->state.header.keys;
  MI_KEYDEF *keyinfo= share->keyinfo;
  my_off_t key_file_length= share->state.state.key_file_length;
  my_off_t pos= share->base.keystart;
  DBUG_ENTER("mi_preload");

  if (!keys || !mi_is_any_key_active(key_map) || key_file_length == pos)
    DBUG_RETURN(0);

  block_length= keyinfo[0].block_length;

  if (ignore_leaves)
  {
    /* Check whether all indexes use the same block size */
    for (i= 1 ; i < keys ; i++)
    {
      if (keyinfo[i].block_length != block_length)
        DBUG_RETURN(my_errno= HA_ERR_NON_UNIQUE_BLOCK_SIZE);
    }
  }
  else
    block_length= share->key_cache->key_cache_block_size;

  length= info->preload_buff_size/block_length * block_length;
  set_if_bigger(length, block_length);

  if (!(buff= (uchar *) my_malloc(length, MYF(MY_WME))))
    DBUG_RETURN(my_errno= HA_ERR_OUT_OF_MEM);

  if (flush_key_blocks(share->key_cache,share->kfile, FLUSH_RELEASE))
    goto err;

  do
  {
    /* Read the next block of index file into the preload buffer */
    if ((my_off_t) length > (key_file_length-pos))
      length= (ulong) (key_file_length-pos);
    if (my_pread(share->kfile, (uchar*) buff, length, pos, MYF(MY_FAE|MY_FNABP)))
      goto err;

    if (ignore_leaves)
    {
      uchar *end= buff+length;
      do
      {
        if (mi_test_if_nod(buff))
        {
          if (key_cache_insert(share->key_cache,
                               share->kfile, pos, DFLT_INIT_HITS,
                              (uchar*) buff, block_length))
	    goto err;
	}
        pos+= block_length;
      }
      while ((buff+= block_length) != end);
      buff= end-length;
    }
    else
    {
      if (key_cache_insert(share->key_cache,
                           share->kfile, pos, DFLT_INIT_HITS,
                           (uchar*) buff, length))
	goto err;
      pos+= length;
    }
  }
  while (pos != key_file_length);

  my_free((char*) buff, MYF(0));
  DBUG_RETURN(0);

err:
  my_free((char*) buff, MYF(MY_ALLOW_ZERO_PTR));
  DBUG_RETURN(my_errno= errno);
}
Beispiel #14
0
int main(int argc, char **argv) {
	int result;
	int error = FALSE;
	int display_license = FALSE;
	int display_help = FALSE;
	int c = 0;
	struct tm *tm, tm_s;
	time_t now;
	char datestring[256];
	nagios_macros *mac;
	const char *worker_socket = NULL;
	int i;

#ifdef HAVE_GETOPT_H
	int option_index = 0;
	static struct option long_options[] = {
			{"help", no_argument, 0, 'h'},
			{"version", no_argument, 0, 'V'},
			{"license", no_argument, 0, 'V'},
			{"verify-config", no_argument, 0, 'v'},
			{"daemon", no_argument, 0, 'd'},
			{"test-scheduling", no_argument, 0, 's'},
			{"precache-objects", no_argument, 0, 'p'},
			{"use-precached-objects", no_argument, 0, 'u'},
			{"enable-timing-point", no_argument, 0, 'T'},
			{"worker", required_argument, 0, 'W'},
			{0, 0, 0, 0}
		};
#define getopt(argc, argv, o) getopt_long(argc, argv, o, long_options, &option_index)
#endif

	memset(&loadctl, 0, sizeof(loadctl));
	mac = get_global_macros();

	/* make sure we have the correct number of command line arguments */
	if(argc < 2)
		error = TRUE;

	/* get all command line arguments */
	while(1) {
		c = getopt(argc, argv, "+hVvdspuxTW");

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

		switch(c) {

			case '?': /* usage */
			case 'h':
				display_help = TRUE;
				break;

			case 'V': /* version */
				display_license = TRUE;
				break;

			case 'v': /* verify */
				verify_config++;
				break;

			case 's': /* scheduling check */
				test_scheduling = TRUE;
				break;

			case 'd': /* daemon mode */
				daemon_mode = TRUE;
				break;

			case 'p': /* precache object config */
				precache_objects = TRUE;
				break;

			case 'u': /* use precached object config */
				use_precached_objects = TRUE;
				break;
			case 'T':
				enable_timing_point = TRUE;
				break;
			case 'W':
				worker_socket = optarg;
				break;

			case 'x':
				printf("Warning: -x is deprecated and will be removed\n");
				break;

			default:
				break;
			}

		}

#ifdef DEBUG_MEMORY
	mtrace();
#endif
	/* if we're a worker we can skip everything below */
	if(worker_socket) {
		exit(nagios_core_worker(worker_socket));
	}

	/* Initialize configuration variables */                             
	init_main_cfg_vars(1);
	init_shared_cfg_vars(1);

	if(daemon_mode == FALSE) {
		printf("\nNagios Core %s\n", PROGRAM_VERSION);
		printf("Copyright (c) 2009-present Nagios Core Development Team and Community Contributors\n");
		printf("Copyright (c) 1999-2009 Ethan Galstad\n");
		printf("Last Modified: %s\n", PROGRAM_MODIFICATION_DATE);
		printf("License: GPL\n\n");
		printf("Website: https://www.nagios.org\n");
		}

	/* just display the license */
	if(display_license == TRUE) {

		printf("This program is free software; you can redistribute it and/or modify\n");
		printf("it under the terms of the GNU General Public License version 2 as\n");
		printf("published by the Free Software Foundation.\n\n");
		printf("This program is distributed in the hope that it will be useful,\n");
		printf("but WITHOUT ANY WARRANTY; without even the implied warranty of\n");
		printf("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n");
		printf("GNU General Public License for more details.\n\n");
		printf("You should have received a copy of the GNU General Public License\n");
		printf("along with this program; if not, write to the Free Software\n");
		printf("Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\n");

		exit(OK);
		}

	/* make sure we got the main config file on the command line... */
	if(optind >= argc)
		error = TRUE;

	/* if there are no command line options (or if we encountered an error), print usage */
	if(error == TRUE || display_help == TRUE) {

		printf("Usage: %s [options] <main_config_file>\n", argv[0]);
		printf("\n");
		printf("Options:\n");
		printf("\n");
		printf("  -v, --verify-config          Verify all configuration data (-v -v for more info)\n");
		printf("  -s, --test-scheduling        Shows projected/recommended check scheduling and other\n");
		printf("                               diagnostic info based on the current configuration files.\n");
		printf("  -T, --enable-timing-point    Enable timed commentary on initialization\n");
		printf("  -x, --dont-verify-paths      Deprecated (Don't check for circular object paths)\n");
		printf("  -p, --precache-objects       Precache object configuration\n");
		printf("  -u, --use-precached-objects  Use precached object config file\n");
		printf("  -d, --daemon                 Starts Nagios in daemon mode, instead of as a foreground process\n");
		printf("  -W, --worker /path/to/socket Act as a worker for an already running daemon\n");
		printf("\n");
		printf("Visit the Nagios website at https://www.nagios.org/ for bug fixes, new\n");
		printf("releases, online documentation, FAQs, information on subscribing to\n");
		printf("the mailing lists, and commercial support options for Nagios.\n");
		printf("\n");

		exit(ERROR);
		}


	/*
	 * config file is last argument specified.
	 * Make sure it uses an absolute path
	 */
	config_file = nspath_absolute(argv[optind], NULL);
	if(config_file == NULL) {
		printf("Error allocating memory.\n");
		exit(ERROR);
		}

	config_file_dir = nspath_absolute_dirname(config_file, NULL);

	/* 
	 * Set the signal handler for the SIGXFSZ signal here because
	 * we may encounter this signal before the other signal handlers
	 * are set.
	 */
	signal(SIGXFSZ, handle_sigxfsz);

	/*
	 * let's go to town. We'll be noisy if we're verifying config
	 * or running scheduling tests.
	 */
	if(verify_config || test_scheduling || precache_objects) {
		reset_variables();
		/*
		 * if we don't beef up our resource limits as much as
		 * we can, it's quite possible we'll run headlong into
		 * EAGAIN due to too many processes when we try to
		 * drop privileges later.
		 */
		set_loadctl_defaults();

		if(verify_config)
			printf("Reading configuration data...\n");

		/* read our config file */
		result = read_main_config_file(config_file);
		if(result != OK) {
			printf("   Error processing main config file!\n\n");
			exit(EXIT_FAILURE);
			}

		if(verify_config)
			printf("   Read main config file okay...\n");

		/* drop privileges */
		if((result = drop_privileges(nagios_user, nagios_group)) == ERROR) {
			printf("   Failed to drop privileges.  Aborting.");
			exit(EXIT_FAILURE);
			}

		/*
		 * this must come after dropping privileges, so we make
		 * sure to test access permissions as the right user.
		 */
		if (!verify_config && test_configured_paths() == ERROR) {
			printf("   One or more path problems detected. Aborting.\n");
			exit(EXIT_FAILURE);
			}

		/* read object config files */
		result = read_all_object_data(config_file);
		if(result != OK) {
			printf("   Error processing object config files!\n\n");
			/* if the config filename looks fishy, warn the user */
			if(!strstr(config_file, "nagios.cfg")) {
				printf("\n***> The name of the main configuration file looks suspicious...\n");
				printf("\n");
				printf("     Make sure you are specifying the name of the MAIN configuration file on\n");
				printf("     the command line and not the name of another configuration file.  The\n");
				printf("     main configuration file is typically '%s'\n", DEFAULT_CONFIG_FILE);
				}

			printf("\n***> One or more problems was encountered while processing the config files...\n");
			printf("\n");
			printf("     Check your configuration file(s) to ensure that they contain valid\n");
			printf("     directives and data defintions.  If you are upgrading from a previous\n");
			printf("     version of Nagios, you should be aware that some variables/definitions\n");
			printf("     may have been removed or modified in this version.  Make sure to read\n");
			printf("     the HTML documentation regarding the config files, as well as the\n");
			printf("     'Whats New' section to find out what has changed.\n\n");
			exit(EXIT_FAILURE);
			}

		if(verify_config) {
			printf("   Read object config files okay...\n\n");
			printf("Running pre-flight check on configuration data...\n\n");
			}

		/* run the pre-flight check to make sure things look okay... */
		result = pre_flight_check();

		if(result != OK) {
			printf("\n***> One or more problems was encountered while running the pre-flight check...\n");
			printf("\n");
			printf("     Check your configuration file(s) to ensure that they contain valid\n");
			printf("     directives and data defintions.  If you are upgrading from a previous\n");
			printf("     version of Nagios, you should be aware that some variables/definitions\n");
			printf("     may have been removed or modified in this version.  Make sure to read\n");
			printf("     the HTML documentation regarding the config files, as well as the\n");
			printf("     'Whats New' section to find out what has changed.\n\n");
			exit(EXIT_FAILURE);
			}

		if(verify_config) {
			printf("\nThings look okay - No serious problems were detected during the pre-flight check\n");
			}

		/* scheduling tests need a bit more than config verifications */
		if(test_scheduling == TRUE) {

			/* we'll need the event queue here so we can time insertions */
			init_event_queue();
			timing_point("Done initializing event queue\n");

			/* read initial service and host state information */
			initialize_retention_data(config_file);
			read_initial_state_information();
			timing_point("Retention data and initial state parsed\n");

			/* initialize the event timing loop */
			init_timing_loop();
			timing_point("Timing loop initialized\n");

			/* display scheduling information */
			display_scheduling_info();
			}

		if(precache_objects) {
			result = fcache_objects(object_precache_file);
			timing_point("Done precaching objects\n");
			if(result == OK) {
				printf("Object precache file created:\n%s\n", object_precache_file);
				}
			else {
				printf("Failed to precache objects to '%s': %s\n", object_precache_file, strerror(errno));
				}
			}

		/* clean up after ourselves */
		cleanup();

		/* exit */
		timing_point("Exiting\n");

		/* make valgrind shut up about still reachable memory */
		neb_free_module_list();
		free(config_file_dir);
		free(config_file);

		exit(result);
		}


	/* else start to monitor things... */
	else {

		/*
		 * if we're called with a relative path we must make
		 * it absolute so we can launch our workers.
		 * If not, we needn't bother, as we're using execvp()
		 */
		if (strchr(argv[0], '/'))
			nagios_binary_path = nspath_absolute(argv[0], NULL);
		else
			nagios_binary_path = strdup(argv[0]);

		if (!nagios_binary_path) {
			logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Unable to allocate memory for nagios_binary_path\n");
			exit(EXIT_FAILURE);
			}

		if (!(nagios_iobs = iobroker_create())) {
			logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Failed to create IO broker set: %s\n",
				  strerror(errno));
			exit(EXIT_FAILURE);
			}

		/* keep monitoring things until we get a shutdown command */
		do {
			/* reset internal book-keeping (in case we're restarting) */
			wproc_num_workers_spawned = wproc_num_workers_online = 0;
			caught_signal = sigshutdown = FALSE;
			sig_id = 0;

			/* reset program variables */
			reset_variables();
			timing_point("Variables reset\n");

			/* get PID */
			nagios_pid = (int)getpid();

			/* read in the configuration files (main and resource config files) */
			result = read_main_config_file(config_file);
			if (result != OK) {
				logit(NSLOG_CONFIG_ERROR, TRUE, "Error: Failed to process config file '%s'. Aborting\n", config_file);
				exit(EXIT_FAILURE);
				}
			timing_point("Main config file read\n");

			/* NOTE 11/06/07 EG moved to after we read config files, as user may have overridden timezone offset */
			/* get program (re)start time and save as macro */
			program_start = time(NULL);
			my_free(mac->x[MACRO_PROCESSSTARTTIME]);
			asprintf(&mac->x[MACRO_PROCESSSTARTTIME], "%lu", (unsigned long)program_start);

			/* drop privileges */
			if(drop_privileges(nagios_user, nagios_group) == ERROR) {

				logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR | NSLOG_CONFIG_ERROR, TRUE, "Failed to drop privileges.  Aborting.");

				cleanup();
				exit(ERROR);
				}

			if (test_path_access(nagios_binary_path, X_OK)) {
				logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: failed to access() %s: %s\n", nagios_binary_path, strerror(errno));
				logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Spawning workers will be impossible. Aborting.\n");
				exit(EXIT_FAILURE);
				}

			if (test_configured_paths() == ERROR) {
				/* error has already been logged */
				exit(EXIT_FAILURE);
				}
			/* enter daemon mode (unless we're restarting...) */
			if(daemon_mode == TRUE && sigrestart == FALSE) {

				result = daemon_init();

				/* we had an error daemonizing, so bail... */
				if(result == ERROR) {
					logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR, TRUE, "Bailing out due to failure to daemonize. (PID=%d)", (int)getpid());
					cleanup();
					exit(EXIT_FAILURE);
					}

				/* get new PID */
				nagios_pid = (int)getpid();
				}

			/* this must be logged after we read config data, as user may have changed location of main log file */
			logit(NSLOG_PROCESS_INFO, TRUE, "Nagios %s starting... (PID=%d)\n", PROGRAM_VERSION, (int)getpid());

			/* log the local time - may be different than clock time due to timezone offset */
			now = time(NULL);
			tm = localtime_r(&now, &tm_s);
			strftime(datestring, sizeof(datestring), "%a %b %d %H:%M:%S %Z %Y", tm);
			logit(NSLOG_PROCESS_INFO, TRUE, "Local time is %s", datestring);

			/* write log version/info */
			write_log_file_info(NULL);

			/* open debug log now that we're the right user */
			open_debug_log();

#ifdef USE_EVENT_BROKER
			/* initialize modules */
			neb_init_modules();
			neb_init_callback_list();
#endif
			timing_point("NEB module API initialized\n");

			/* handle signals (interrupts) before we do any socket I/O */
			setup_sighandler();

			/*
			 * Initialize query handler and event subscription service.
			 * This must be done before modules are initialized, so
			 * the modules can use our in-core stuff properly
			 */
			if (qh_init(qh_socket_path ? qh_socket_path : DEFAULT_QUERY_SOCKET) != OK) {
				logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Failed to initialize query handler. Aborting\n");
				exit(EXIT_FAILURE);
			}
			timing_point("Query handler initialized\n");
			nerd_init();
			timing_point("NERD initialized\n");

			/* initialize check workers */
			if(init_workers(num_check_workers) < 0) {
				logit(NSLOG_RUNTIME_ERROR, TRUE, "Failed to spawn workers. Aborting\n");
				exit(EXIT_FAILURE);
			}
			timing_point("%u workers spawned\n", wproc_num_workers_spawned);
			i = 0;
			while (i < 50 && wproc_num_workers_online < wproc_num_workers_spawned) {
				iobroker_poll(nagios_iobs, 50);
				i++;
			}
			timing_point("%u workers connected\n", wproc_num_workers_online);

			/* now that workers have arrived we can set the defaults */
			set_loadctl_defaults();

#ifdef USE_EVENT_BROKER
			/* load modules */
			if (neb_load_all_modules() != OK) {
				logit(NSLOG_CONFIG_ERROR, ERROR, "Error: Module loading failed. Aborting.\n");
				/* if we're dumping core, we must remove all dl-files */
				if (daemon_dumps_core)
					neb_unload_all_modules(NEBMODULE_FORCE_UNLOAD, NEBMODULE_NEB_SHUTDOWN);
				exit(EXIT_FAILURE);
				}
			timing_point("Modules loaded\n");

			/* send program data to broker */
			broker_program_state(NEBTYPE_PROCESS_PRELAUNCH, NEBFLAG_NONE, NEBATTR_NONE, NULL);
			timing_point("First callback made\n");
#endif

			/* read in all object config data */
			if(result == OK)
				result = read_all_object_data(config_file);

			/* there was a problem reading the config files */
			if(result != OK)
				logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR | NSLOG_CONFIG_ERROR, TRUE, "Bailing out due to one or more errors encountered in the configuration files. Run Nagios from the command line with the -v option to verify your config before restarting. (PID=%d)", (int)getpid());

			else {

				/* run the pre-flight check to make sure everything looks okay*/
				if((result = pre_flight_check()) != OK)
					logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR | NSLOG_VERIFICATION_ERROR, TRUE, "Bailing out due to errors encountered while running the pre-flight check.  Run Nagios from the command line with the -v option to verify your config before restarting. (PID=%d)\n", (int)getpid());
				}

			/* an error occurred that prevented us from (re)starting */
			if(result != OK) {

				/* if we were restarting, we need to cleanup from the previous run */
				if(sigrestart == TRUE) {

					/* clean up the status data */
					cleanup_status_data(TRUE);
					}

#ifdef USE_EVENT_BROKER
				/* send program data to broker */
				broker_program_state(NEBTYPE_PROCESS_SHUTDOWN, NEBFLAG_PROCESS_INITIATED, NEBATTR_SHUTDOWN_ABNORMAL, NULL);
#endif
				cleanup();
				exit(ERROR);
				}

			timing_point("Object configuration parsed and understood\n");

			/* write the objects.cache file */
			fcache_objects(object_cache_file);
			timing_point("Objects cached\n");

			init_event_queue();
			timing_point("Event queue initialized\n");


#ifdef USE_EVENT_BROKER
			/* send program data to broker */
			broker_program_state(NEBTYPE_PROCESS_START, NEBFLAG_NONE, NEBATTR_NONE, NULL);
#endif

			/* initialize status data unless we're starting */
			if(sigrestart == FALSE) {
				initialize_status_data(config_file);
				timing_point("Status data initialized\n");
				}

			/* initialize scheduled downtime data */
			initialize_downtime_data();
			timing_point("Downtime data initialized\n");

			/* read initial service and host state information  */
			initialize_retention_data(config_file);
			timing_point("Retention data initialized\n");
			read_initial_state_information();
			timing_point("Initial state information read\n");

			/* initialize comment data */
			initialize_comment_data();
			timing_point("Comment data initialized\n");

			/* initialize performance data */
			initialize_performance_data(config_file);
			timing_point("Performance data initialized\n");

			/* initialize the event timing loop */
			init_timing_loop();
			timing_point("Event timing loop initialized\n");

			/* initialize check statistics */
			init_check_stats();
			timing_point("check stats initialized\n");

			/* check for updates */
			check_for_nagios_updates(FALSE, TRUE);
			timing_point("Update check concluded\n");

			/* update all status data (with retained information) */
			update_all_status_data();
			timing_point("Status data updated\n");

			/* log initial host and service state */
			log_host_states(INITIAL_STATES, NULL);
			log_service_states(INITIAL_STATES, NULL);
			timing_point("Initial states logged\n");

			/* reset the restart flag */
			sigrestart = FALSE;

			/* fire up command file worker */
			launch_command_file_worker();
			timing_point("Command file worker launched\n");

#ifdef USE_EVENT_BROKER
			/* send program data to broker */
			broker_program_state(NEBTYPE_PROCESS_EVENTLOOPSTART, NEBFLAG_NONE, NEBATTR_NONE, NULL);
#endif

			/* get event start time and save as macro */
			event_start = time(NULL);
			my_free(mac->x[MACRO_EVENTSTARTTIME]);
			asprintf(&mac->x[MACRO_EVENTSTARTTIME], "%lu", (unsigned long)event_start);

			timing_point("Entering event execution loop\n");
			/***** start monitoring all services *****/
			/* (doesn't return until a restart or shutdown signal is encountered) */
			event_execution_loop();

			/*
			 * immediately deinitialize the query handler so it
			 * can remove modules that have stashed data with it
			 */
			qh_deinit(qh_socket_path ? qh_socket_path : DEFAULT_QUERY_SOCKET);

			/* 03/01/2007 EG Moved from sighandler() to prevent FUTEX locking problems under NPTL */
			/* 03/21/2007 EG SIGSEGV signals are still logged in sighandler() so we don't loose them */
			/* did we catch a signal? */
			if(caught_signal == TRUE) {

				if(sig_id == SIGHUP)
					logit(NSLOG_PROCESS_INFO, TRUE, "Caught SIGHUP, restarting...\n");

				}

#ifdef USE_EVENT_BROKER
			/* send program data to broker */
			broker_program_state(NEBTYPE_PROCESS_EVENTLOOPEND, NEBFLAG_NONE, NEBATTR_NONE, NULL);
			if(sigshutdown == TRUE)
				broker_program_state(NEBTYPE_PROCESS_SHUTDOWN, NEBFLAG_USER_INITIATED, NEBATTR_SHUTDOWN_NORMAL, NULL);
			else if(sigrestart == TRUE)
				broker_program_state(NEBTYPE_PROCESS_RESTART, NEBFLAG_USER_INITIATED, NEBATTR_RESTART_NORMAL, NULL);
#endif

			/* save service and host state information */
			save_state_information(FALSE);
			cleanup_retention_data();

			/* clean up performance data */
			cleanup_performance_data();

			/* clean up the scheduled downtime data */
			cleanup_downtime_data();

			/* clean up the status data unless we're restarting */
			if(sigrestart == FALSE) {
				cleanup_status_data(TRUE);
				}

			free_worker_memory(WPROC_FORCE);
			/* shutdown stuff... */
			if(sigshutdown == TRUE) {
				iobroker_destroy(nagios_iobs, IOBROKER_CLOSE_SOCKETS);
				nagios_iobs = NULL;

				/* log a shutdown message */
				logit(NSLOG_PROCESS_INFO, TRUE, "Successfully shutdown... (PID=%d)\n", (int)getpid());
				}

			/* clean up after ourselves */
			cleanup();

			/* close debug log */
			close_debug_log();

			}
		while(sigrestart == TRUE && sigshutdown == FALSE);

		if(daemon_mode == TRUE)
			unlink(lock_file);

		/* free misc memory */
		my_free(lock_file);
		my_free(config_file);
		my_free(config_file_dir);
		my_free(nagios_binary_path);
		}

	return OK;
	}
Beispiel #15
0
/* initializes performance data */
int xpddefault_initialize_performance_data(const char *cfgfile) {
	char *buffer = NULL;
	char *temp_buffer = NULL;
	char *temp_command_name = NULL;
	command *temp_command = NULL;
	time_t current_time;
	nagios_macros *mac;

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

	/* reset vars */
	host_perfdata_command_ptr = NULL;
	service_perfdata_command_ptr = NULL;
	host_perfdata_file_processing_command_ptr = NULL;
	service_perfdata_file_processing_command_ptr = NULL;

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

	/* process special chars in templates */
	xpddefault_preprocess_file_templates(host_perfdata_file_template);
	xpddefault_preprocess_file_templates(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(host_perfdata_command != NULL) {

		temp_buffer = (char *)strdup(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(host_perfdata_command);
			}

		my_free(temp_buffer);

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

		temp_buffer = (char *)strdup(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(service_perfdata_command);
			}

		/* free memory */
		my_free(temp_buffer);

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

		temp_buffer = (char *)strdup(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(host_perfdata_file_processing_command);
			}

		/* free memory */
		my_free(temp_buffer);

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

		temp_buffer = (char *)strdup(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(service_perfdata_file_processing_command);
			}

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

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

	/* periodically process the service perfdata file */
	if(service_perfdata_file_processing_interval > 0 && service_perfdata_file_processing_command != NULL)
		schedule_new_event(EVENT_USER_FUNCTION, TRUE, current_time + service_perfdata_file_processing_interval, TRUE, 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(host_perfdata_file != NULL) {
		if((mac->x[MACRO_HOSTPERFDATAFILE] = (char *)strdup(host_perfdata_file)))
			strip(mac->x[MACRO_HOSTPERFDATAFILE]);
		}

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

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

	return OK;
	}
Beispiel #16
0
//***********************************************************************************
int main()
{
	 FILE * pFile;
	 pFile = fopen ("test3_output.txt","w");
    int size;
    int RAM_SIZE=1<<20;//1024*1024
    void* RAM=malloc(RAM_SIZE);//1024*1024
	setup(2,RAM_SIZE,RAM);//Worst Fit, Memory size=1024*1024, Start of memory=RAM
//test 3
    size=20*1024;
	void* a=my_malloc(size);//We have 4 bytes header to save the size of that chunk in memory so the output starts at 4
    if ((int)a==-1)
        fprintf(pFile, "This size can not be allocated!");
    else
    {
    	fprintf(pFile, "start of the chunk a: %d\n",a-RAM);
    	fprintf(pFile, "End of the chunk a: %d\n\n",a+size-RAM);
    }

    size=30*1024;
    void* b=my_malloc(size);
    if ((int)b==-1)
        fprintf(pFile, "This size can not be allocated!");
    else
    {
    	fprintf(pFile, "start of the chunk b: %d\n",b-RAM);
    	fprintf(pFile, "End of the chunk b: %d\n\n",b+size-RAM);
    }

    size=15*1024;
	void* c=my_malloc(size);
    if ((int)c==-1)
        fprintf(pFile, "This size can not be allocated!");
    else
    {
    	fprintf(pFile, "start of the chunk c: %d\n",c-RAM);
    	fprintf(pFile, "End of the chunk c: %d\n\n",c+size-RAM);
    }

    size=25*1024;
	void* d=my_malloc(size);
    if ((int)d==-1)
        fprintf(pFile, "This size can not be allocated!");
    else
    {
    	fprintf(pFile, "start of the chunk d: %d\n",d-RAM);
    	fprintf(pFile, "End of the chunk d: %d\n\n",d+size-RAM);
    }

    size=35*1024;
	void* e=my_malloc(size);
    if ((int)e==-1)
        fprintf(pFile, "This size can not be allocated!");
    else
    {
    	fprintf(pFile, "start of the chunk e: %d\n",e-RAM);
    	fprintf(pFile, "End of the chunk e: %d\n\n",e+size-RAM);
    }

    size=35*1024;
	void* f=my_malloc(size);
    if ((int)f==-1)
        fprintf(pFile, "This size can not be allocated!");
    else
    {
    	fprintf(pFile, "start of the chunk f: %d\n",f-RAM);
    	fprintf(pFile, "End of the chunk f: %d\n\n",f+size-RAM);
    }

    size=25*1024;
	void* g=my_malloc(size);
    if ((int)g==-1)
        fprintf(pFile, "This size can not be allocated!");
    else
    {
    	fprintf(pFile, "start of the chunk g: %d\n",g-RAM);
    	fprintf(pFile, "End of the chunk g: %d\n\n",g+size-RAM);
    }

	my_free(b);
	my_free(d);
	my_free(f);

    size=25*1024;
	void* h=my_malloc(size);
    if ((int)h==-1)
        fprintf(pFile, "This size can not be allocated!");
    else
    {
    	fprintf(pFile, "start of the chunk h: %d\n",h-RAM);
    	fprintf(pFile, "End of the chunk h: %d\n\n",h+size-RAM);
    }

    fclose (pFile);
	return 0;
}
Beispiel #17
0
/* top-level external command processor */
int main(int argv, char **argc) {
    if(argv < 2) {
        printf("Not enough arguments!\n"); 
        return 1;
    }
    char *cmd = argc[1];
    char *temp_buffer = NULL;
    char *command_id = NULL;
    char *args = NULL;
    time_t entry_time = 0L;
    int command_type = CMD_NONE;
    char *temp_ptr = NULL;

    if (cmd == NULL) {
        printf("No command given\n");
        return ERROR;
    }

    /* strip the command of newlines and carriage returns */
    strip(cmd);

    /* get the command entry time */
    if ((temp_ptr = my_strtok(cmd, "[")) == NULL) {
        printf("No entry time given\n");
        return ERROR;
    }
    if ((temp_ptr = my_strtok(NULL, "]")) == NULL) {
        printf("Missing ] character at entry time\n");
        return ERROR;
    }
    entry_time = (time_t)strtoul(temp_ptr, NULL, 10);

    /* get the command identifier */
    if ((temp_ptr = my_strtok(NULL, ";")) == NULL) {
        printf("Missing command identifier\n");
        return ERROR;
    }
    if ((command_id = (char *)strdup(temp_ptr + 1)) == NULL) {
        printf("Missing command identifier\n");
        return ERROR;
    }

    /* get the command arguments */
    if ((temp_ptr = my_strtok(NULL, "\n")) == NULL)
        args = (char *)strdup("");
    else
        args = (char *)strdup(temp_ptr);

    if (args == NULL) {
        printf("No arguments given\n");
        my_free(command_id);
        return ERROR;
    }

    /* decide what type of command this is... */

    /**************************/
    /**** PROCESS COMMANDS ****/
    /**************************/

    if (!strcmp(command_id, "ENTER_STANDBY_MODE") || !strcmp(command_id, "DISABLE_NOTIFICATIONS"))
        command_type = CMD_DISABLE_NOTIFICATIONS;
    else if (!strcmp(command_id, "ENTER_ACTIVE_MODE") || !strcmp(command_id, "ENABLE_NOTIFICATIONS"))
        command_type = CMD_ENABLE_NOTIFICATIONS;
    else if (!strcmp(command_id, "DISABLE_NOTIFICATIONS_EXPIRE_TIME"))
        command_type = CMD_DISABLE_NOTIFICATIONS_EXPIRE_TIME;

    else if (!strcmp(command_id, "SHUTDOWN_PROGRAM") || !strcmp(command_id, "SHUTDOWN_PROCESS"))
        command_type = CMD_SHUTDOWN_PROCESS;
    else if (!strcmp(command_id, "RESTART_PROGRAM") || !strcmp(command_id, "RESTART_PROCESS"))
        command_type = CMD_RESTART_PROCESS;

    else if (!strcmp(command_id, "SAVE_STATE_INFORMATION"))
        command_type = CMD_SAVE_STATE_INFORMATION;
    else if (!strcmp(command_id, "READ_STATE_INFORMATION"))
        command_type = CMD_READ_STATE_INFORMATION;
    else if (!strcmp(command_id, "SYNC_STATE_INFORMATION"))
        command_type = CMD_SYNC_STATE_INFORMATION;

    else if (!strcmp(command_id, "ENABLE_EVENT_HANDLERS"))
        command_type = CMD_ENABLE_EVENT_HANDLERS;
    else if (!strcmp(command_id, "DISABLE_EVENT_HANDLERS"))
        command_type = CMD_DISABLE_EVENT_HANDLERS;

    else if (!strcmp(command_id, "FLUSH_PENDING_COMMANDS"))
        command_type = CMD_FLUSH_PENDING_COMMANDS;

    else if (!strcmp(command_id, "ENABLE_FAILURE_PREDICTION"))
        command_type = CMD_ENABLE_FAILURE_PREDICTION;
    else if (!strcmp(command_id, "DISABLE_FAILURE_PREDICTION"))
        command_type = CMD_DISABLE_FAILURE_PREDICTION;

    else if (!strcmp(command_id, "ENABLE_PERFORMANCE_DATA"))
        command_type = CMD_ENABLE_PERFORMANCE_DATA;
    else if (!strcmp(command_id, "DISABLE_PERFORMANCE_DATA"))
        command_type = CMD_DISABLE_PERFORMANCE_DATA;

    else if (!strcmp(command_id, "START_EXECUTING_HOST_CHECKS"))
        command_type = CMD_START_EXECUTING_HOST_CHECKS;
    else if (!strcmp(command_id, "STOP_EXECUTING_HOST_CHECKS"))
        command_type = CMD_STOP_EXECUTING_HOST_CHECKS;

    else if (!strcmp(command_id, "START_EXECUTING_SVC_CHECKS"))
        command_type = CMD_START_EXECUTING_SVC_CHECKS;
    else if (!strcmp(command_id, "STOP_EXECUTING_SVC_CHECKS"))
        command_type = CMD_STOP_EXECUTING_SVC_CHECKS;

    else if (!strcmp(command_id, "START_ACCEPTING_PASSIVE_HOST_CHECKS"))
        command_type = CMD_START_ACCEPTING_PASSIVE_HOST_CHECKS;
    else if (!strcmp(command_id, "STOP_ACCEPTING_PASSIVE_HOST_CHECKS"))
        command_type = CMD_STOP_ACCEPTING_PASSIVE_HOST_CHECKS;

    else if (!strcmp(command_id, "START_ACCEPTING_PASSIVE_SVC_CHECKS"))
        command_type = CMD_START_ACCEPTING_PASSIVE_SVC_CHECKS;
    else if (!strcmp(command_id, "STOP_ACCEPTING_PASSIVE_SVC_CHECKS"))
        command_type = CMD_STOP_ACCEPTING_PASSIVE_SVC_CHECKS;

    else if (!strcmp(command_id, "START_OBSESSING_OVER_HOST_CHECKS"))
        command_type = CMD_START_OBSESSING_OVER_HOST_CHECKS;
    else if (!strcmp(command_id, "STOP_OBSESSING_OVER_HOST_CHECKS"))
        command_type = CMD_STOP_OBSESSING_OVER_HOST_CHECKS;

    else if (!strcmp(command_id, "START_OBSESSING_OVER_SVC_CHECKS"))
        command_type = CMD_START_OBSESSING_OVER_SVC_CHECKS;
    else if (!strcmp(command_id, "STOP_OBSESSING_OVER_SVC_CHECKS"))
        command_type = CMD_STOP_OBSESSING_OVER_SVC_CHECKS;

    else if (!strcmp(command_id, "ENABLE_FLAP_DETECTION"))
        command_type = CMD_ENABLE_FLAP_DETECTION;
    else if (!strcmp(command_id, "DISABLE_FLAP_DETECTION"))
        command_type = CMD_DISABLE_FLAP_DETECTION;

    else if (!strcmp(command_id, "CHANGE_GLOBAL_HOST_EVENT_HANDLER"))
        command_type = CMD_CHANGE_GLOBAL_HOST_EVENT_HANDLER;
    else if (!strcmp(command_id, "CHANGE_GLOBAL_SVC_EVENT_HANDLER"))
        command_type = CMD_CHANGE_GLOBAL_SVC_EVENT_HANDLER;

    else if (!strcmp(command_id, "ENABLE_SERVICE_FRESHNESS_CHECKS"))
        command_type = CMD_ENABLE_SERVICE_FRESHNESS_CHECKS;
    else if (!strcmp(command_id, "DISABLE_SERVICE_FRESHNESS_CHECKS"))
        command_type = CMD_DISABLE_SERVICE_FRESHNESS_CHECKS;

    else if (!strcmp(command_id, "ENABLE_HOST_FRESHNESS_CHECKS"))
        command_type = CMD_ENABLE_HOST_FRESHNESS_CHECKS;
    else if (!strcmp(command_id, "DISABLE_HOST_FRESHNESS_CHECKS"))
        command_type = CMD_DISABLE_HOST_FRESHNESS_CHECKS;


    /*******************************/
    /**** HOST-RELATED COMMANDS ****/
    /*******************************/

    else if (!strcmp(command_id, "ADD_HOST_COMMENT"))
        command_type = CMD_ADD_HOST_COMMENT;
    else if (!strcmp(command_id, "DEL_HOST_COMMENT"))
        command_type = CMD_DEL_HOST_COMMENT;
    else if (!strcmp(command_id, "DEL_ALL_HOST_COMMENTS"))
        command_type = CMD_DEL_ALL_HOST_COMMENTS;

    else if (!strcmp(command_id, "DELAY_HOST_NOTIFICATION"))
        command_type = CMD_DELAY_HOST_NOTIFICATION;

    else if (!strcmp(command_id, "ENABLE_HOST_NOTIFICATIONS"))
        command_type = CMD_ENABLE_HOST_NOTIFICATIONS;
    else if (!strcmp(command_id, "DISABLE_HOST_NOTIFICATIONS"))
        command_type = CMD_DISABLE_HOST_NOTIFICATIONS;

    else if (!strcmp(command_id, "ENABLE_ALL_NOTIFICATIONS_BEYOND_HOST"))
        command_type = CMD_ENABLE_ALL_NOTIFICATIONS_BEYOND_HOST;
    else if (!strcmp(command_id, "DISABLE_ALL_NOTIFICATIONS_BEYOND_HOST"))
        command_type = CMD_DISABLE_ALL_NOTIFICATIONS_BEYOND_HOST;

    else if (!strcmp(command_id, "ENABLE_HOST_AND_CHILD_NOTIFICATIONS"))
        command_type = CMD_ENABLE_HOST_AND_CHILD_NOTIFICATIONS;
    else if (!strcmp(command_id, "DISABLE_HOST_AND_CHILD_NOTIFICATIONS"))
        command_type = CMD_DISABLE_HOST_AND_CHILD_NOTIFICATIONS;

    else if (!strcmp(command_id, "ENABLE_HOST_SVC_NOTIFICATIONS"))
        command_type = CMD_ENABLE_HOST_SVC_NOTIFICATIONS;
    else if (!strcmp(command_id, "DISABLE_HOST_SVC_NOTIFICATIONS"))
        command_type = CMD_DISABLE_HOST_SVC_NOTIFICATIONS;

    else if (!strcmp(command_id, "ENABLE_HOST_SVC_CHECKS"))
        command_type = CMD_ENABLE_HOST_SVC_CHECKS;
    else if (!strcmp(command_id, "DISABLE_HOST_SVC_CHECKS"))
        command_type = CMD_DISABLE_HOST_SVC_CHECKS;

    else if (!strcmp(command_id, "ENABLE_PASSIVE_HOST_CHECKS"))
        command_type = CMD_ENABLE_PASSIVE_HOST_CHECKS;
    else if (!strcmp(command_id, "DISABLE_PASSIVE_HOST_CHECKS"))
        command_type = CMD_DISABLE_PASSIVE_HOST_CHECKS;

    else if (!strcmp(command_id, "SCHEDULE_HOST_SVC_CHECKS"))
        command_type = CMD_SCHEDULE_HOST_SVC_CHECKS;
    else if (!strcmp(command_id, "SCHEDULE_FORCED_HOST_SVC_CHECKS"))
        command_type = CMD_SCHEDULE_FORCED_HOST_SVC_CHECKS;

    else if (!strcmp(command_id, "ACKNOWLEDGE_HOST_PROBLEM"))
        command_type = CMD_ACKNOWLEDGE_HOST_PROBLEM;
    else if (!strcmp(command_id, "ACKNOWLEDGE_HOST_PROBLEM_EXPIRE"))
        command_type = CMD_ACKNOWLEDGE_HOST_PROBLEM_EXPIRE;
    else if (!strcmp(command_id, "REMOVE_HOST_ACKNOWLEDGEMENT"))
        command_type = CMD_REMOVE_HOST_ACKNOWLEDGEMENT;

    else if (!strcmp(command_id, "ENABLE_HOST_EVENT_HANDLER"))
        command_type = CMD_ENABLE_HOST_EVENT_HANDLER;
    else if (!strcmp(command_id, "DISABLE_HOST_EVENT_HANDLER"))
        command_type = CMD_DISABLE_HOST_EVENT_HANDLER;

    else if (!strcmp(command_id, "ENABLE_HOST_CHECK"))
        command_type = CMD_ENABLE_HOST_CHECK;
    else if (!strcmp(command_id, "DISABLE_HOST_CHECK"))
        command_type = CMD_DISABLE_HOST_CHECK;

    else if (!strcmp(command_id, "SCHEDULE_HOST_CHECK"))
        command_type = CMD_SCHEDULE_HOST_CHECK;
    else if (!strcmp(command_id, "SCHEDULE_FORCED_HOST_CHECK"))
        command_type = CMD_SCHEDULE_FORCED_HOST_CHECK;

    else if (!strcmp(command_id, "SCHEDULE_HOST_DOWNTIME"))
        command_type = CMD_SCHEDULE_HOST_DOWNTIME;
    else if (!strcmp(command_id, "SCHEDULE_HOST_SVC_DOWNTIME"))
        command_type = CMD_SCHEDULE_HOST_SVC_DOWNTIME;
    else if (!strcmp(command_id, "DEL_HOST_DOWNTIME"))
        command_type = CMD_DEL_HOST_DOWNTIME;
    else if (!strcmp(command_id, "DEL_DOWNTIME_BY_HOST_NAME"))
        command_type = CMD_DEL_DOWNTIME_BY_HOST_NAME;
    else if (!strcmp(command_id, "DEL_DOWNTIME_BY_HOSTGROUP_NAME"))
        command_type = CMD_DEL_DOWNTIME_BY_HOSTGROUP_NAME;

    else if (!strcmp(command_id, "DEL_DOWNTIME_BY_START_TIME_COMMENT"))
        command_type = CMD_DEL_DOWNTIME_BY_START_TIME_COMMENT;

    else if (!strcmp(command_id, "ENABLE_HOST_FLAP_DETECTION"))
        command_type = CMD_ENABLE_HOST_FLAP_DETECTION;
    else if (!strcmp(command_id, "DISABLE_HOST_FLAP_DETECTION"))
        command_type = CMD_DISABLE_HOST_FLAP_DETECTION;

    else if (!strcmp(command_id, "START_OBSESSING_OVER_HOST"))
        command_type = CMD_START_OBSESSING_OVER_HOST;
    else if (!strcmp(command_id, "STOP_OBSESSING_OVER_HOST"))
        command_type = CMD_STOP_OBSESSING_OVER_HOST;

    else if (!strcmp(command_id, "CHANGE_HOST_EVENT_HANDLER"))
        command_type = CMD_CHANGE_HOST_EVENT_HANDLER;
    else if (!strcmp(command_id, "CHANGE_HOST_CHECK_COMMAND"))
        command_type = CMD_CHANGE_HOST_CHECK_COMMAND;

    else if (!strcmp(command_id, "CHANGE_NORMAL_HOST_CHECK_INTERVAL"))
        command_type = CMD_CHANGE_NORMAL_HOST_CHECK_INTERVAL;
    else if (!strcmp(command_id, "CHANGE_RETRY_HOST_CHECK_INTERVAL"))
        command_type = CMD_CHANGE_RETRY_HOST_CHECK_INTERVAL;

    else if (!strcmp(command_id, "CHANGE_MAX_HOST_CHECK_ATTEMPTS"))
        command_type = CMD_CHANGE_MAX_HOST_CHECK_ATTEMPTS;

    else if (!strcmp(command_id, "SCHEDULE_AND_PROPAGATE_TRIGGERED_HOST_DOWNTIME"))
        command_type = CMD_SCHEDULE_AND_PROPAGATE_TRIGGERED_HOST_DOWNTIME;

    else if (!strcmp(command_id, "SCHEDULE_AND_PROPAGATE_HOST_DOWNTIME"))
        command_type = CMD_SCHEDULE_AND_PROPAGATE_HOST_DOWNTIME;

    else if (!strcmp(command_id, "SET_HOST_NOTIFICATION_NUMBER"))
        command_type = CMD_SET_HOST_NOTIFICATION_NUMBER;

    else if (!strcmp(command_id, "CHANGE_HOST_CHECK_TIMEPERIOD"))
        command_type = CMD_CHANGE_HOST_CHECK_TIMEPERIOD;

    else if (!strcmp(command_id, "CHANGE_CUSTOM_HOST_VAR"))
        command_type = CMD_CHANGE_CUSTOM_HOST_VAR;

    else if (!strcmp(command_id, "SEND_CUSTOM_HOST_NOTIFICATION"))
        command_type = CMD_SEND_CUSTOM_HOST_NOTIFICATION;

    else if (!strcmp(command_id, "CHANGE_HOST_NOTIFICATION_TIMEPERIOD"))
        command_type = CMD_CHANGE_HOST_NOTIFICATION_TIMEPERIOD;

    else if (!strcmp(command_id, "CHANGE_HOST_MODATTR"))
        command_type = CMD_CHANGE_HOST_MODATTR;


    /************************************/
    /**** HOSTGROUP-RELATED COMMANDS ****/
    /************************************/

    else if (!strcmp(command_id, "ENABLE_HOSTGROUP_HOST_NOTIFICATIONS"))
        command_type = CMD_ENABLE_HOSTGROUP_HOST_NOTIFICATIONS;
    else if (!strcmp(command_id, "DISABLE_HOSTGROUP_HOST_NOTIFICATIONS"))
        command_type = CMD_DISABLE_HOSTGROUP_HOST_NOTIFICATIONS;

    else if (!strcmp(command_id, "ENABLE_HOSTGROUP_SVC_NOTIFICATIONS"))
        command_type = CMD_ENABLE_HOSTGROUP_SVC_NOTIFICATIONS;
    else if (!strcmp(command_id, "DISABLE_HOSTGROUP_SVC_NOTIFICATIONS"))
        command_type = CMD_DISABLE_HOSTGROUP_SVC_NOTIFICATIONS;

    else if (!strcmp(command_id, "ENABLE_HOSTGROUP_HOST_CHECKS"))
        command_type = CMD_ENABLE_HOSTGROUP_HOST_CHECKS;
    else if (!strcmp(command_id, "DISABLE_HOSTGROUP_HOST_CHECKS"))
        command_type = CMD_DISABLE_HOSTGROUP_HOST_CHECKS;

    else if (!strcmp(command_id, "ENABLE_HOSTGROUP_PASSIVE_HOST_CHECKS"))
        command_type = CMD_ENABLE_HOSTGROUP_PASSIVE_HOST_CHECKS;
    else if (!strcmp(command_id, "DISABLE_HOSTGROUP_PASSIVE_HOST_CHECKS"))
        command_type = CMD_DISABLE_HOSTGROUP_PASSIVE_HOST_CHECKS;

    else if (!strcmp(command_id, "ENABLE_HOSTGROUP_SVC_CHECKS"))
        command_type = CMD_ENABLE_HOSTGROUP_SVC_CHECKS;
    else if (!strcmp(command_id, "DISABLE_HOSTGROUP_SVC_CHECKS"))
        command_type = CMD_DISABLE_HOSTGROUP_SVC_CHECKS;

    else if (!strcmp(command_id, "ENABLE_HOSTGROUP_PASSIVE_SVC_CHECKS"))
        command_type = CMD_ENABLE_HOSTGROUP_PASSIVE_SVC_CHECKS;
    else if (!strcmp(command_id, "DISABLE_HOSTGROUP_PASSIVE_SVC_CHECKS"))
        command_type = CMD_DISABLE_HOSTGROUP_PASSIVE_SVC_CHECKS;

    else if (!strcmp(command_id, "SCHEDULE_HOSTGROUP_HOST_DOWNTIME"))
        command_type = CMD_SCHEDULE_HOSTGROUP_HOST_DOWNTIME;
    else if (!strcmp(command_id, "SCHEDULE_HOSTGROUP_SVC_DOWNTIME"))
        command_type = CMD_SCHEDULE_HOSTGROUP_SVC_DOWNTIME;


    /**********************************/
    /**** SERVICE-RELATED COMMANDS ****/
    /**********************************/

    else if (!strcmp(command_id, "ADD_SVC_COMMENT"))
        command_type = CMD_ADD_SVC_COMMENT;
    else if (!strcmp(command_id, "DEL_SVC_COMMENT"))
        command_type = CMD_DEL_SVC_COMMENT;
    else if (!strcmp(command_id, "DEL_ALL_SVC_COMMENTS"))
        command_type = CMD_DEL_ALL_SVC_COMMENTS;

    else if (!strcmp(command_id, "SCHEDULE_SVC_CHECK"))
        command_type = CMD_SCHEDULE_SVC_CHECK;
    else if (!strcmp(command_id, "SCHEDULE_FORCED_SVC_CHECK"))
        command_type = CMD_SCHEDULE_FORCED_SVC_CHECK;

    else if (!strcmp(command_id, "ENABLE_SVC_CHECK"))
        command_type = CMD_ENABLE_SVC_CHECK;
    else if (!strcmp(command_id, "DISABLE_SVC_CHECK"))
        command_type = CMD_DISABLE_SVC_CHECK;

    else if (!strcmp(command_id, "ENABLE_PASSIVE_SVC_CHECKS"))
        command_type = CMD_ENABLE_PASSIVE_SVC_CHECKS;
    else if (!strcmp(command_id, "DISABLE_PASSIVE_SVC_CHECKS"))
        command_type = CMD_DISABLE_PASSIVE_SVC_CHECKS;

    else if (!strcmp(command_id, "DELAY_SVC_NOTIFICATION"))
        command_type = CMD_DELAY_SVC_NOTIFICATION;
    else if (!strcmp(command_id, "ENABLE_SVC_NOTIFICATIONS"))
        command_type = CMD_ENABLE_SVC_NOTIFICATIONS;
    else if (!strcmp(command_id, "DISABLE_SVC_NOTIFICATIONS"))
        command_type = CMD_DISABLE_SVC_NOTIFICATIONS;

    else if (!strcmp(command_id, "PROCESS_SERVICE_CHECK_RESULT"))
        command_type = CMD_PROCESS_SERVICE_CHECK_RESULT;
    else if (!strcmp(command_id, "PROCESS_HOST_CHECK_RESULT"))
        command_type = CMD_PROCESS_HOST_CHECK_RESULT;

    else if (!strcmp(command_id, "ENABLE_SVC_EVENT_HANDLER"))
        command_type = CMD_ENABLE_SVC_EVENT_HANDLER;
    else if (!strcmp(command_id, "DISABLE_SVC_EVENT_HANDLER"))
        command_type = CMD_DISABLE_SVC_EVENT_HANDLER;

    else if (!strcmp(command_id, "ENABLE_SVC_FLAP_DETECTION"))
        command_type = CMD_ENABLE_SVC_FLAP_DETECTION;
    else if (!strcmp(command_id, "DISABLE_SVC_FLAP_DETECTION"))
        command_type = CMD_DISABLE_SVC_FLAP_DETECTION;

    else if (!strcmp(command_id, "SCHEDULE_SVC_DOWNTIME"))
        command_type = CMD_SCHEDULE_SVC_DOWNTIME;
    else if (!strcmp(command_id, "DEL_SVC_DOWNTIME"))
        command_type = CMD_DEL_SVC_DOWNTIME;

    else if (!strcmp(command_id, "ACKNOWLEDGE_SVC_PROBLEM"))
        command_type = CMD_ACKNOWLEDGE_SVC_PROBLEM;
    else if (!strcmp(command_id, "ACKNOWLEDGE_SVC_PROBLEM_EXPIRE"))
        command_type = CMD_ACKNOWLEDGE_SVC_PROBLEM_EXPIRE;
    else if (!strcmp(command_id, "REMOVE_SVC_ACKNOWLEDGEMENT"))
        command_type = CMD_REMOVE_SVC_ACKNOWLEDGEMENT;

    else if (!strcmp(command_id, "START_OBSESSING_OVER_SVC"))
        command_type = CMD_START_OBSESSING_OVER_SVC;
    else if (!strcmp(command_id, "STOP_OBSESSING_OVER_SVC"))
        command_type = CMD_STOP_OBSESSING_OVER_SVC;

    else if (!strcmp(command_id, "CHANGE_SVC_EVENT_HANDLER"))
        command_type = CMD_CHANGE_SVC_EVENT_HANDLER;
    else if (!strcmp(command_id, "CHANGE_SVC_CHECK_COMMAND"))
        command_type = CMD_CHANGE_SVC_CHECK_COMMAND;

    else if (!strcmp(command_id, "CHANGE_NORMAL_SVC_CHECK_INTERVAL"))
        command_type = CMD_CHANGE_NORMAL_SVC_CHECK_INTERVAL;
    else if (!strcmp(command_id, "CHANGE_RETRY_SVC_CHECK_INTERVAL"))
        command_type = CMD_CHANGE_RETRY_SVC_CHECK_INTERVAL;

    else if (!strcmp(command_id, "CHANGE_MAX_SVC_CHECK_ATTEMPTS"))
        command_type = CMD_CHANGE_MAX_SVC_CHECK_ATTEMPTS;

    else if (!strcmp(command_id, "SET_SVC_NOTIFICATION_NUMBER"))
        command_type = CMD_SET_SVC_NOTIFICATION_NUMBER;

    else if (!strcmp(command_id, "CHANGE_SVC_CHECK_TIMEPERIOD"))
        command_type = CMD_CHANGE_SVC_CHECK_TIMEPERIOD;

    else if (!strcmp(command_id, "CHANGE_CUSTOM_SVC_VAR"))
        command_type = CMD_CHANGE_CUSTOM_SVC_VAR;

    else if (!strcmp(command_id, "CHANGE_CUSTOM_CONTACT_VAR"))
        command_type = CMD_CHANGE_CUSTOM_CONTACT_VAR;

    else if (!strcmp(command_id, "SEND_CUSTOM_SVC_NOTIFICATION"))
        command_type = CMD_SEND_CUSTOM_SVC_NOTIFICATION;

    else if (!strcmp(command_id, "CHANGE_SVC_NOTIFICATION_TIMEPERIOD"))
        command_type = CMD_CHANGE_SVC_NOTIFICATION_TIMEPERIOD;

    else if (!strcmp(command_id, "CHANGE_SVC_MODATTR"))
        command_type = CMD_CHANGE_SVC_MODATTR;


    /***************************************/
    /**** SERVICEGROUP-RELATED COMMANDS ****/
    /***************************************/

    else if (!strcmp(command_id, "ENABLE_SERVICEGROUP_HOST_NOTIFICATIONS"))
        command_type = CMD_ENABLE_SERVICEGROUP_HOST_NOTIFICATIONS;
    else if (!strcmp(command_id, "DISABLE_SERVICEGROUP_HOST_NOTIFICATIONS"))
        command_type = CMD_DISABLE_SERVICEGROUP_HOST_NOTIFICATIONS;

    else if (!strcmp(command_id, "ENABLE_SERVICEGROUP_SVC_NOTIFICATIONS"))
        command_type = CMD_ENABLE_SERVICEGROUP_SVC_NOTIFICATIONS;
    else if (!strcmp(command_id, "DISABLE_SERVICEGROUP_SVC_NOTIFICATIONS"))
        command_type = CMD_DISABLE_SERVICEGROUP_SVC_NOTIFICATIONS;

    else if (!strcmp(command_id, "ENABLE_SERVICEGROUP_HOST_CHECKS"))
        command_type = CMD_ENABLE_SERVICEGROUP_HOST_CHECKS;
    else if (!strcmp(command_id, "DISABLE_SERVICEGROUP_HOST_CHECKS"))
        command_type = CMD_DISABLE_SERVICEGROUP_HOST_CHECKS;

    else if (!strcmp(command_id, "ENABLE_SERVICEGROUP_PASSIVE_HOST_CHECKS"))
        command_type = CMD_ENABLE_SERVICEGROUP_PASSIVE_HOST_CHECKS;
    else if (!strcmp(command_id, "DISABLE_SERVICEGROUP_PASSIVE_HOST_CHECKS"))
        command_type = CMD_DISABLE_SERVICEGROUP_PASSIVE_HOST_CHECKS;

    else if (!strcmp(command_id, "ENABLE_SERVICEGROUP_SVC_CHECKS"))
        command_type = CMD_ENABLE_SERVICEGROUP_SVC_CHECKS;
    else if (!strcmp(command_id, "DISABLE_SERVICEGROUP_SVC_CHECKS"))
        command_type = CMD_DISABLE_SERVICEGROUP_SVC_CHECKS;

    else if (!strcmp(command_id, "ENABLE_SERVICEGROUP_PASSIVE_SVC_CHECKS"))
        command_type = CMD_ENABLE_SERVICEGROUP_PASSIVE_SVC_CHECKS;
    else if (!strcmp(command_id, "DISABLE_SERVICEGROUP_PASSIVE_SVC_CHECKS"))
        command_type = CMD_DISABLE_SERVICEGROUP_PASSIVE_SVC_CHECKS;

    else if (!strcmp(command_id, "SCHEDULE_SERVICEGROUP_HOST_DOWNTIME"))
        command_type = CMD_SCHEDULE_SERVICEGROUP_HOST_DOWNTIME;
    else if (!strcmp(command_id, "SCHEDULE_SERVICEGROUP_SVC_DOWNTIME"))
        command_type = CMD_SCHEDULE_SERVICEGROUP_SVC_DOWNTIME;


    /**********************************/
    /**** CONTACT-RELATED COMMANDS ****/
    /**********************************/

    else if (!strcmp(command_id, "ENABLE_CONTACT_HOST_NOTIFICATIONS"))
        command_type = CMD_ENABLE_CONTACT_HOST_NOTIFICATIONS;
    else if (!strcmp(command_id, "DISABLE_CONTACT_HOST_NOTIFICATIONS"))
        command_type = CMD_DISABLE_CONTACT_HOST_NOTIFICATIONS;

    else if (!strcmp(command_id, "ENABLE_CONTACT_SVC_NOTIFICATIONS"))
        command_type = CMD_ENABLE_CONTACT_SVC_NOTIFICATIONS;
    else if (!strcmp(command_id, "DISABLE_CONTACT_SVC_NOTIFICATIONS"))
        command_type = CMD_DISABLE_CONTACT_SVC_NOTIFICATIONS;

    else if (!strcmp(command_id, "CHANGE_CONTACT_HOST_NOTIFICATION_TIMEPERIOD"))
        command_type = CMD_CHANGE_CONTACT_HOST_NOTIFICATION_TIMEPERIOD;

    else if (!strcmp(command_id, "CHANGE_CONTACT_SVC_NOTIFICATION_TIMEPERIOD"))
        command_type = CMD_CHANGE_CONTACT_SVC_NOTIFICATION_TIMEPERIOD;

    else if (!strcmp(command_id, "CHANGE_CONTACT_MODATTR"))
        command_type = CMD_CHANGE_CONTACT_MODATTR;
    else if (!strcmp(command_id, "CHANGE_CONTACT_MODHATTR"))
        command_type = CMD_CHANGE_CONTACT_MODHATTR;
    else if (!strcmp(command_id, "CHANGE_CONTACT_MODSATTR"))
        command_type = CMD_CHANGE_CONTACT_MODSATTR;

    /***************************************/
    /**** CONTACTGROUP-RELATED COMMANDS ****/
    /***************************************/

    else if (!strcmp(command_id, "ENABLE_CONTACTGROUP_HOST_NOTIFICATIONS"))
        command_type = CMD_ENABLE_CONTACTGROUP_HOST_NOTIFICATIONS;
    else if (!strcmp(command_id, "DISABLE_CONTACTGROUP_HOST_NOTIFICATIONS"))
        command_type = CMD_DISABLE_CONTACTGROUP_HOST_NOTIFICATIONS;

    else if (!strcmp(command_id, "ENABLE_CONTACTGROUP_SVC_NOTIFICATIONS"))
        command_type = CMD_ENABLE_CONTACTGROUP_SVC_NOTIFICATIONS;
    else if (!strcmp(command_id, "DISABLE_CONTACTGROUP_SVC_NOTIFICATIONS"))
        command_type = CMD_DISABLE_CONTACTGROUP_SVC_NOTIFICATIONS;


    /**************************/
    /****** MISC COMMANDS *****/
    /**************************/

    else if (!strcmp(command_id, "PROCESS_FILE"))
        command_type = CMD_PROCESS_FILE;



    /****************************/
    /****** CUSTOM COMMANDS *****/
    /****************************/

    else if (command_id[0] == '_')
        command_type = CMD_CUSTOM_COMMAND;



    /**** UNKNOWN COMMAND ****/
    else {
        /* free memory */
        printf("UNKNOWN COMMAND: %s;%s\n", command_id, args);
        my_free(command_id);
        my_free(args);

        return ERROR;
    }


    /* log the external command */
    printf("%s;%s\n", command_id, args);
    my_free(temp_buffer);

    my_free(command_id);
    my_free(args);

    return OK;
}
Beispiel #18
0
void __as2805_make_custom(T_AS2805FIELD **flds, char **pmsg)
{
	int i;
	uint length = 0;
	uchar * request = NULL;
	char * string;
	T_AS2805FIELD *field = flds[0];

	// Set the AS2805 error to none
	AS2805_Error = -1;

	// Resolve element to a single value string
	if (flds)
	{

		// Initialise the custom AS2805 buffer with maximum of 1000 bytes.....This should be plenty.
		request = my_malloc(1000);

		// For each array within the main array
		for (i=0;field;i++)
		{
			uchar formatType=0;
			uint fieldSize;
			uchar * fieldValue;
			char * format;

            field = flds[i];
			if(field==NULL) break;

			format = field->type;
			fieldSize = field->fieldnum;
			fieldValue = field->data;

			// Get the field number

			if (strncmp(format, "a", 1) == 0) formatType = C_STRING;

			//else if (strcmp(format, "x+n") == 0) formatType = C_AMOUNT;
			else if (strcmp(format, "m") == 0) formatType = C_AMOUNT;
			else if (format[0] == 'z') formatType = C_LLNVAR;
			else if (format[0] == 'n') formatType = C_BCD;
			else if (format[0] == 'N') formatType = C_BCD_LINK;
			else if (format[0] == 'b') formatType = C_BITMAP;

			// Pack the value
			AS2805BufferPack((char *)fieldValue, formatType, fieldSize, request, &length);

		}

	}

	// Handle an empty message request situation
	if (length == 0)
	{
		*pmsg = NULL;
		return;
	}

	// Convert the request buffer to ASCII Hex
	string = my_malloc(length * 2 + 1);
	UtilHexToString((const char *)request, length, string);
	if (request) my_free(request);

	// We got our message now, release internal buffers
	AS2805Close();

	// return with the request buffer as a string
	*pmsg = string;
}
Beispiel #19
0
/*
  my_gethwaddr - Windows version

  @brief Retrieve MAC address from network hardware

  @param[out]  to MAC address exactly six bytes

  @return Operation status
    @retval 0       OK
    @retval <>0     FAILED
*/
my_bool my_gethwaddr(uchar *to)
{
  PIP_ADAPTER_ADDRESSES pAdapterAddresses;
  PIP_ADAPTER_ADDRESSES pCurrAddresses;
  IP_ADAPTER_ADDRESSES  adapterAddresses;
  ULONG                 address_len;
  my_bool               return_val= 1;
  static pfnGetAdaptersAddresses fnGetAdaptersAddresses=
                                (pfnGetAdaptersAddresses)-1;

  if(fnGetAdaptersAddresses == (pfnGetAdaptersAddresses)-1)
  {
    /* Get the function from the DLL */
    fnGetAdaptersAddresses= (pfnGetAdaptersAddresses)
                            GetProcAddress(LoadLibrary("iphlpapi.dll"),
                                          "GetAdaptersAddresses");
  }
  if (!fnGetAdaptersAddresses)
    return 1;                                   /* failed to get function */
  address_len= sizeof (IP_ADAPTER_ADDRESSES);

  /* Get the required size for the address data. */
  if (fnGetAdaptersAddresses(AF_UNSPEC, 0, 0, &adapterAddresses, &address_len)
      == ERROR_BUFFER_OVERFLOW)
  {
    pAdapterAddresses= my_malloc(key_memory_win_IP_ADAPTER_ADDRESSES,
                                 address_len, 0);
    if (!pAdapterAddresses)
      return 1;                                   /* error, alloc failed */
  }
  else
    pAdapterAddresses= &adapterAddresses;         /* one is enough don't alloc */

  /* Get the hardware info. */
  if (fnGetAdaptersAddresses(AF_UNSPEC, 0, 0, pAdapterAddresses, &address_len)
      == NO_ERROR)
  {
    pCurrAddresses= pAdapterAddresses;

    while (pCurrAddresses)
    {
      /* Look for ethernet cards. */
      if (pCurrAddresses->IfType == IF_TYPE_ETHERNET_CSMACD)
      {
        /* check for a good address */
        if (pCurrAddresses->PhysicalAddressLength < 6)
            continue;                           /* bad address */

        /* save 6 bytes of the address in the 'to' parameter */
        memcpy(to, pCurrAddresses->PhysicalAddress, 6);

        /* Network card found, we're done. */
        return_val= 0;
        break;
      }
      pCurrAddresses= pCurrAddresses->Next;
    }
  }

  /* Clean up memory allocation. */
  if (pAdapterAddresses != &adapterAddresses)
    my_free(pAdapterAddresses);

  return return_val;
}
Beispiel #20
0
void __as2805_break_custom(const char *msg,T_AS2805FIELD **flds, int *errfld)
{
	int i;
	uint respLength;
	uint length = 0;
	char temp[10];
	uchar * response;
	const char * data = msg;
	bool tooLong = false;
	T_AS2805FIELD *field = flds[0];

	// Convert the response to hex
	respLength = strlen(data) / 2;
	response = my_malloc(respLength + 200);		// To cover ill formatted messages
	UtilStringToHex(data, strlen(data), response);

	// Set the AS2805 error to none
	AS2805_Error = -1;

	// Resolve element to a single value string
	if (flds)
	{
		for (i=0;!tooLong && AS2805_Error==-1 && field;i++)
		{
			uchar formatType=0;
			int fieldSize;
			char * fieldValue = NULL;
			char * format;
			int operation;

            field = flds[i];
			if(field==NULL) break;

			operation = field->action;
			format = field->type;
			fieldSize = field->fieldnum;

			// Get the field number
			if (strcmp(format, "LLNVAR") == 0) formatType = C_LLNVAR;
			else if (strcmp(format, "LLAVAR") == 0) formatType = C_LLAVAR;
			else if (strcmp(format, "LLLNVAR") == 0) formatType = C_LLLNVAR;
			else if (strcmp(format, "LLLVAR") == 0) formatType = C_LLLVAR;
			else if (strncmp(format, "an", 2) == 0) formatType = C_STRING;
			else if (strncmp(format, "a", 1) == 0) formatType = C_STRING;
			else if (strcmp(format, "ns") == 0) formatType = C_STRING;
			else if (strcmp(format, "x+n") == 0) formatType = C_AMOUNT;
			else if (format[0] == 'z') formatType = C_LLNVAR;
			else if (format[0] == 'n') formatType = C_BCD;
			else if (format[0] == 'N') formatType = C_BCD_LINK;
			else if (format[0] == 'b') formatType = C_BITMAP;

			// Allocate enough space for the field value
			fieldValue = my_malloc(2000);
			fieldValue[0] = '\0';

			// Unpack the value
			// fetch the left message
			if(fieldSize == -1) fieldSize = respLength - length;
			AS2805BufferUnpack(fieldValue, formatType, fieldSize, response, &length);

			// Make sure we have not gone past the response field
			if (length > respLength) {
				tooLong = true;
				if(fieldValue) my_free(fieldValue);
			}
			else if (operation == C_GET || operation == C_GETS )
			{
				field->data = (unsigned char *)fieldValue;
			}
		}
	}


	// We got our message now, release internal buffers
	AS2805Close();
	my_free(response);

	// Return the result. If -1, no error. If a positive number then this is the field number that had the error during a CHK operation
	sprintf(temp, "%d", AS2805_Error);
	*errfld = AS2805_Error;
}
Beispiel #21
0
int process_cgivars(void) {
	char **variables;
	int error = FALSE;
	int x;

	variables = getcgivars();

	for (x = 0; variables[x] != NULL; x++) {

		/* do some basic length checking on the variable identifier to prevent buffer overflows */
		if (strlen(variables[x]) >= MAX_INPUT_BUFFER - 1)
			continue;

		/* found query string */
		else if (!strcmp(variables[x], "query_string")) {
			x++;
			if (variables[x] == NULL) {
				error = TRUE;
				break;
			}

			query_string = strdup(variables[x]);
			strip_html_brackets(query_string);

			if (strlen(query_string) == 0)
				my_free(query_string);
		}

		/* we found first time argument */
		else if (!strcmp(variables[x], "ts_start")) {
			x++;
			if (variables[x] == NULL) {
				error = TRUE;
				break;
			}

			ts_start = (time_t)strtoul(variables[x], NULL, 10);
		}

		/* we found last time argument */
		else if (!strcmp(variables[x], "ts_end")) {
			x++;
			if (variables[x] == NULL) {
				error = TRUE;
				break;
			}

			ts_end = (time_t)strtoul(variables[x], NULL, 10);
		}

		/* we found the start time */
		else if (!strcmp(variables[x], "start_time")) {
			x++;
			if (variables[x] == NULL) {
				error = TRUE;
				break;
			}

			start_time_string = (char *)malloc(strlen(variables[x]) + 1);
			if (start_time_string == NULL)
				start_time_string = "";
			else
				strcpy(start_time_string, variables[x]);
		}

		/* we found the end time */
		else if (!strcmp(variables[x], "end_time")) {
			x++;
			if (variables[x] == NULL) {
				error = TRUE;
				break;
			}

			end_time_string = (char *)malloc(strlen(variables[x]) + 1);
			if (end_time_string == NULL)
				end_time_string = "";
			else
				strcpy(end_time_string, variables[x]);
		}

		/* we found the standard timeperiod argument */
		else if (!strcmp(variables[x], "timeperiod")) {
			x++;
			if (variables[x] == NULL) {
				error = TRUE;
				break;
			}

			if (!strcmp(variables[x], "today"))
				timeperiod_type = TIMEPERIOD_TODAY;
			else if (!strcmp(variables[x], "singelday"))
				timeperiod_type = TIMEPERIOD_SINGLE_DAY;
			else if (!strcmp(variables[x], "last24hours"))
				timeperiod_type = TIMEPERIOD_LAST24HOURS;
			else if (!strcmp(variables[x], "thisweek"))
				timeperiod_type = TIMEPERIOD_THISWEEK;
			else if (!strcmp(variables[x], "lastweek"))
				timeperiod_type = TIMEPERIOD_LASTWEEK;
			else if (!strcmp(variables[x], "thismonth"))
				timeperiod_type = TIMEPERIOD_THISMONTH;
			else if (!strcmp(variables[x], "lastmonth"))
				timeperiod_type = TIMEPERIOD_LASTMONTH;
			else if (!strcmp(variables[x], "thisyear"))
				timeperiod_type = TIMEPERIOD_THISYEAR;
			else if (!strcmp(variables[x], "lastyear"))
				timeperiod_type = TIMEPERIOD_LASTYEAR;
			else if (!strcmp(variables[x], "last7days"))
				timeperiod_type = TIMEPERIOD_LAST7DAYS;
			else if (!strcmp(variables[x], "last31days"))
				timeperiod_type = TIMEPERIOD_LAST31DAYS;
			else if (!strcmp(variables[x], "custom"))
				timeperiod_type = TIMEPERIOD_CUSTOM;
			else
				continue;

			convert_timeperiod_to_times(timeperiod_type, &ts_start, &ts_end);
		}

		/* we found the order argument */
		else if (!strcmp(variables[x], "order")) {
			x++;
			if (variables[x] == NULL) {
				error = TRUE;
				break;
			}

			if (!strcmp(variables[x], "new2old"))
				reverse = FALSE;
			else if (!strcmp(variables[x], "old2new"))
				reverse = TRUE;
		}

		/* show filter */
		else if (!strcmp(variables[x], "display_filter")) {
			x++;
			if (variables[x] == NULL) {
				error = TRUE;
				break;
			}

			if (!strcmp(variables[x], "true"))
				display_filter = TRUE;
		}

		/* notification filter */
		else if (!strcmp(variables[x], "noti")) {
			x++;
			if (variables[x] == NULL) {
				error = TRUE;
				break;
			}

			if (!strcmp(variables[x], "off"))
				show_notifications = FALSE;
		}

		/* host status filter */
		else if (!strcmp(variables[x], "hst")) {
			x++;
			if (variables[x] == NULL) {
				error = TRUE;
				break;
			}

			if (!strcmp(variables[x], "off"))
				show_host_status = FALSE;
		}

		/* service status filter */
		else if (!strcmp(variables[x], "sst")) {
			x++;
			if (variables[x] == NULL) {
				error = TRUE;
				break;
			}

			if (!strcmp(variables[x], "off"))
				show_service_status = FALSE;
		}

		/* external commands filter */
		else if (!strcmp(variables[x], "cmd")) {
			x++;
			if (variables[x] == NULL) {
				error = TRUE;
				break;
			}

			if (!strcmp(variables[x], "off"))
				show_external_commands = FALSE;
		}

		/* system messages filter */
		else if (!strcmp(variables[x], "sms")) {
			x++;
			if (variables[x] == NULL) {
				error = TRUE;
				break;
			}

			if (!strcmp(variables[x], "off"))
				show_system_messages = FALSE;
		}

		/* event handler filter */
		else if (!strcmp(variables[x], "evh")) {
			x++;
			if (variables[x] == NULL) {
				error = TRUE;
				break;
			}

			if (!strcmp(variables[x], "off"))
				show_event_handler = FALSE;
		}

		/* flapping filter */
		else if (!strcmp(variables[x], "flp")) {
			x++;
			if (variables[x] == NULL) {
				error = TRUE;
				break;
			}

			if (!strcmp(variables[x], "off"))
				show_flapping = FALSE;
		}

		/* downtime filter */
		else if (!strcmp(variables[x], "dwn")) {
			x++;
			if (variables[x] == NULL) {
				error = TRUE;
				break;
			}

			if (!strcmp(variables[x], "off"))
				show_downtime = FALSE;
		}

		/* we found the CSV output option */
		else if (!strcmp(variables[x], "csvoutput")) {
			display_header = FALSE;
			content_type = CSV_CONTENT;
		}

		/* we found the CSV output option */
		else if (!strcmp(variables[x], "jsonoutput")) {
			display_header = FALSE;
			content_type = JSON_CONTENT;
		}

		/* we found the embed option */
		else if (!strcmp(variables[x], "embedded"))
			embedded = TRUE;

		/* we found the noheader option */
		else if (!strcmp(variables[x], "noheader"))
			display_header = FALSE;

		/* we found the nofrills option */
		else if (!strcmp(variables[x], "nofrills"))
			display_frills = FALSE;

		/* we found the notimebreaks option */
		else if (!strcmp(variables[x], "notimebreaks"))
			display_timebreaks = FALSE;

		/* we found the nodaemoncheck option */
		else if (!strcmp(variables[x], "nodaemoncheck"))
			daemon_check = FALSE;


		/* start num results to skip on displaying statusdata */
		else if (!strcmp(variables[x], "start")) {
			x++;
			if (variables[x] == NULL) {
				error = TRUE;
				break;
			}

			result_start = atoi(variables[x]);

			if (result_start < 1)
				result_start = 1;
		}

		/* amount of results to display */
		else if (!strcmp(variables[x], "limit")) {
			x++;
			if (variables[x] == NULL) {
				error = TRUE;
				break;
			}

			get_result_limit = atoi(variables[x]);
		}

		/* we received an invalid argument */
		else
			error = TRUE;

	}

	/* free memory allocated to the CGI variables */
	free_cgivars(variables);

	return error;
}
Beispiel #22
0
my_bool _nisam_read_pack_info(N_INFO *info, pbool fix_keys)
{
  File file;
  int diff_length;
  uint i,trees,huff_tree_bits,rec_reflength,length;
  uint16 *decode_table,*tmp_buff;
  ulong elements,intervall_length;
  char *disk_cache,*intervall_buff;
  uchar header[32];
  ISAM_SHARE *share=info->s;
  BIT_BUFF bit_buff;
  DBUG_ENTER("_nisam_read_pack_info");

  if (nisam_quick_table_bits < 4)
    nisam_quick_table_bits=4;
  else if (nisam_quick_table_bits > MAX_QUICK_TABLE_BITS)
    nisam_quick_table_bits=MAX_QUICK_TABLE_BITS;

  file=info->dfile;
  my_errno=0;
  if (my_read(file,(byte*) header,sizeof(header),MYF(MY_NABP)))
  {
    if (!my_errno)
      my_errno=HA_ERR_END_OF_FILE;
    DBUG_RETURN(1);
  }
  if (memcmp((byte*) header,(byte*) nisam_pack_file_magic,4))
  {
    my_errno=HA_ERR_WRONG_IN_RECORD;
    DBUG_RETURN(1);
  }
  share->pack.header_length=uint4korr(header+4);
  share->min_pack_length=(uint) uint4korr(header+8);
  share->max_pack_length=(uint) uint4korr(header+12);
  set_if_bigger(share->base.pack_reclength,share->max_pack_length);
  elements=uint4korr(header+16);
  intervall_length=uint4korr(header+20);
  trees=uint2korr(header+24);
  share->pack.ref_length=header[26];
  rec_reflength=header[27];
  diff_length=(int) rec_reflength - (int) share->base.rec_reflength;
  if (fix_keys)
    share->rec_reflength=rec_reflength;
  share->base.min_block_length=share->min_pack_length+share->pack.ref_length;

  if (!(share->decode_trees=(DECODE_TREE*)
	my_malloc((uint) (trees*sizeof(DECODE_TREE)+
			  intervall_length*sizeof(byte)),
		  MYF(MY_WME))))
    DBUG_RETURN(1);
  intervall_buff=(byte*) (share->decode_trees+trees);

  length=(uint) (elements*2+trees*(1 << nisam_quick_table_bits));
  if (!(share->decode_tables=(uint16*)
	my_malloc((length+512)*sizeof(uint16)+
		  (uint) (share->pack.header_length+7),
		  MYF(MY_WME | MY_ZEROFILL))))
  {
    my_free((gptr) share->decode_trees,MYF(0));
    DBUG_RETURN(1);
  }
  tmp_buff=share->decode_tables+length;
  disk_cache=(byte*) (tmp_buff+512);

  if (my_read(file,disk_cache,
	      (uint) (share->pack.header_length-sizeof(header)),
	      MYF(MY_NABP)))
  {
    my_free((gptr) share->decode_trees,MYF(0));
    my_free((gptr) share->decode_tables,MYF(0));
    DBUG_RETURN(1);
  }

  huff_tree_bits=max_bit(trees ? trees-1 : 0);
  init_bit_buffer(&bit_buff,disk_cache,
		  (uint) (share->pack.header_length-sizeof(header)));
	/* Read new info for each field */
  for (i=0 ; i < share->base.fields ; i++)
  {
    share->rec[i].base_type=(enum en_fieldtype) get_bits(&bit_buff,4);
    share->rec[i].pack_type=(uint) get_bits(&bit_buff,4);
    share->rec[i].space_length_bits=get_bits(&bit_buff,4);
    share->rec[i].huff_tree=share->decode_trees+(uint) get_bits(&bit_buff,
								huff_tree_bits);
    share->rec[i].unpack=get_unpack_function(share->rec+i);
  }
  skipp_to_next_byte(&bit_buff);
  decode_table=share->decode_tables;
  for (i=0 ; i < trees ; i++)
    read_huff_table(&bit_buff,share->decode_trees+i,&decode_table,
		    &intervall_buff,tmp_buff);
  decode_table=(uint16*)
    my_realloc((gptr) share->decode_tables,
	       (uint) ((byte*) decode_table - (byte*) share->decode_tables),
	       MYF(MY_HOLD_ON_ERROR));
  {
    my_ptrdiff_t diff=PTR_BYTE_DIFF(decode_table,share->decode_tables);
    share->decode_tables=decode_table;
    for (i=0 ; i < trees ; i++)
      share->decode_trees[i].table=ADD_TO_PTR(share->decode_trees[i].table,
					      diff, uint16*);
  }

	/* Fix record-ref-length for keys */
  if (fix_keys)
  {
    for (i=0 ; i < share->base.keys ; i++)
    {
      share->keyinfo[i].base.keylength+=(uint16) diff_length;
      share->keyinfo[i].base.minlength+=(uint16) diff_length;
      share->keyinfo[i].base.maxlength+=(uint16) diff_length;
      share->keyinfo[i].seg[share->keyinfo[i].base.keysegs].base.length=
	(uint16) rec_reflength;
    }
  }

  if (bit_buff.error || bit_buff.pos < bit_buff.end)
  {					/* info_length was wrong */
    my_errno=HA_ERR_WRONG_IN_RECORD;
    my_free((gptr) share->decode_trees,MYF(0));
    my_free((gptr) share->decode_tables,MYF(0));
    DBUG_RETURN(1);
  }
  DBUG_RETURN(0);
}
Beispiel #23
0
Datei: blosc.c Projekt: 87/carray
/* Specific routine optimized for decompression a small number of
   items out of a compressed chunk.  This does not use threads because
   it would affect negatively to performance. */
int blosc_getitem(const void *src, int start, int nitems, void *dest)
{
  uint8_t *_src=NULL;               /* current pos for source buffer */
  uint8_t version, versionlz;       /* versions for compressed header */
  uint8_t flags;                    /* flags for header */
  int32_t ntbytes = 0;              /* the number of uncompressed bytes */
  uint32_t nblocks;                 /* number of total blocks in buffer */
  uint32_t leftover;                /* extra bytes at end of buffer */
  uint32_t *bstarts;                /* start pointers for each block */
  uint8_t *tmp = params.tmp[0];     /* tmp for thread 0 */
  uint8_t *tmp2 = params.tmp2[0];   /* tmp2 for thread 0 */
  int tmp_init = 0;
  uint32_t typesize, blocksize, nbytes, ctbytes;
  uint32_t j, bsize, bsize2, leftoverblock;
  int32_t cbytes, startb, stopb;
  int stop = start + nitems;

  _src = (uint8_t *)(src);

  /* Read the header block */
  version = _src[0];                         /* blosc format version */
  versionlz = _src[1];                       /* blosclz format version */
  flags = _src[2];                           /* flags */
  typesize = (uint32_t)_src[3];              /* typesize */
  _src += 4;
  nbytes = sw32(((uint32_t *)_src)[0]);      /* buffer size */
  blocksize = sw32(((uint32_t *)_src)[1]);   /* block size */
  ctbytes = sw32(((uint32_t *)_src)[2]);     /* compressed buffer size */

  _src += sizeof(int32_t)*3;
  bstarts = (uint32_t *)_src;
  /* Compute some params */
  /* Total blocks */
  nblocks = nbytes / blocksize;
  leftover = nbytes % blocksize;
  nblocks = (leftover>0)? nblocks+1: nblocks;
  _src += sizeof(int32_t)*nblocks;

  /* Check region boundaries */
  if ((start < 0) || (start*typesize > nbytes)) {
    fprintf(stderr, "`start` out of bounds");
    return (-1);
  }

  if ((stop < 0) || (stop*typesize > nbytes)) {
    fprintf(stderr, "`start`+`nitems` out of bounds");
    return (-1);
  }

  /* Parameters needed by blosc_d */
  params.typesize = typesize;
  params.flags = flags;

  /* Initialize temporaries if needed */
  if (tmp == NULL || tmp2 == NULL || current_temp.blocksize < blocksize) {
    tmp = my_malloc(blocksize);
    tmp2 = my_malloc(blocksize);
    tmp_init = 1;
  }

  for (j = 0; j < nblocks; j++) {
    bsize = blocksize;
    leftoverblock = 0;
    if ((j == nblocks - 1) && (leftover > 0)) {
      bsize = leftover;
      leftoverblock = 1;
    }

    /* Compute start & stop for each block */
    startb = start * typesize - j * blocksize;
    stopb = stop * typesize - j * blocksize;
    if ((startb >= (int)blocksize) || (stopb <= 0)) {
      continue;
    }
    if (startb < 0) {
      startb = 0;
    }
    if (stopb > (int)blocksize) {
      stopb = blocksize;
    }
    bsize2 = stopb - startb;

    /* Do the actual data copy */
    if (flags & BLOSC_MEMCPYED) {
      /* We want to memcpy only */
      memcpy((uint8_t *)dest + ntbytes,
	     (uint8_t *)src + BLOSC_MAX_OVERHEAD + j*blocksize + startb,
             bsize2);
      cbytes = bsize2;
    }
    else {
      /* Regular decompression.  Put results in tmp2. */
      cbytes = blosc_d(bsize, leftoverblock,
                       (uint8_t *)src+sw32(bstarts[j]), tmp2, tmp, tmp2);
      if (cbytes < 0) {
        ntbytes = cbytes;
        break;
      }
      /* Copy to destination */
      memcpy((uint8_t *)dest + ntbytes, tmp2 + startb, bsize2);
      cbytes = bsize2;
    }
    ntbytes += cbytes;
  }

  if (tmp_init) {
    my_free(tmp);
    my_free(tmp2);
  }

  return ntbytes;
}
Beispiel #24
0
  int readCpuCounters(SFLHost_cpu_counters *cpu) {
    int gotData = NO;
	uint32_t i = 0;
	PPDH_RAW_COUNTER_ITEM thread = NULL;
	DWORD dwRet,cbData = sizeof(DWORD);
	HKEY hkey;

	cpu->load_one = (float)load_1;
	cpu->load_five = (float)load_5;
	cpu->load_fifteen = (float)load_15;
	cpu->cpu_user = (uint32_t)readSingleCounter("\\Processor(_Total)\\% User Time");
	cpu->cpu_system = (uint32_t)readSingleCounter("\\Processor(_Total)\\% Privileged Time");
	cpu->cpu_idle = (uint32_t)readSingleCounter("\\Processor(_Total)\\% Idle Time");
	cpu->cpu_intr = (uint32_t)readSingleCounter("\\Processor(_Total)\\% Interrupt Time");
	cpu->interrupts = (uint32_t)readSingleCounter("\\Processor(_Total)\\Interrupts/sec");
	cpu->contexts = (uint32_t)readSingleCounter("\\System\\Context Switches/sec");
	cpu->uptime = (uint32_t)readFormattedCounter("\\System\\System Up Time");
	cpu->cpu_num = getCpuNum();

	// see http://support.microsoft.com/kb/888282 for ways to determine CPU speed
	dwRet = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
						"hardware\\description\\system\\centralprocessor\\0",
						0,
						KEY_QUERY_VALUE,
						&hkey);

	if(dwRet == ERROR_SUCCESS) {
		dwRet = RegQueryValueEx( hkey,
			                     "~MHz",
			                     NULL,
								 NULL,
			                     (LPBYTE) &cpu->cpu_speed,
			                     &cbData );
		if(dwRet != ERROR_SUCCESS) cpu->cpu_speed = -1;
		RegCloseKey(hkey);
	}

	cpu->proc_total = readMultiCounter("\\Thread(*)\\Thread State",&thread);
	cpu->proc_run = 0;
	if(thread){
		for(i = 0; i < cpu->proc_total; i++){
			if(thread[i].RawValue.FirstValue == 2 && strncmp("Idle",thread[i].szName,4) != 0){
				cpu->proc_run++;
			}
		}
		my_free(thread);
	}

	//These have no obvious Windows equivalent
	cpu->cpu_sintr = UNKNOWN_COUNTER;
	cpu->cpu_nice = UNKNOWN_COUNTER;
	cpu->cpu_wio = UNKNOWN_COUNTER;
	
	myLog(LOG_INFO,
		"readCpuCounters:\n\tload_one:\t%f\n\tload_five:\t%f\n\tload_fifteen:\t%f\n"
		"\tuptime:\t\t%lus\n\tcpu_num:\t%d\n"
		"\tcpu speed:\t%d MHz\n\tuser: %lu\n\tsystem: %lu\n\tidle: %lu\n\tirq: %lu\n"
		"\tthreads_total: %lu\n\tthreads_running: %lu\n",
		cpu->load_one,cpu->load_five,cpu->load_fifteen,cpu->uptime,cpu->cpu_num,
		cpu->cpu_speed,cpu->cpu_user,cpu->cpu_system,
		cpu->cpu_idle,cpu->cpu_intr,cpu->proc_total,cpu->proc_run);


	gotData = YES;

    return gotData;
  }
Beispiel #25
0
/* handle service check events */
static int handle_svc_check( int event_type, void *data ) {
    host * hst   = NULL;
    service * svc = NULL;
    char *raw_command=NULL;
    char *processed_command=NULL;
    nebstruct_service_check_data * svcdata;
    int prio = GM_JOB_PRIO_LOW;
    check_result * chk_result;
    struct timeval core_time;
    struct tm next_check;
    char buffer1[GM_BUFFERSIZE];

    gettimeofday(&core_time,NULL);

    gm_log( GM_LOG_TRACE, "handle_svc_check(%i, data)\n", event_type );
    svcdata = ( nebstruct_service_check_data * )data;

    if ( event_type != NEBCALLBACK_SERVICE_CHECK_DATA )
        return NEB_OK;

    /* ignore non-initiate service checks */
    if ( svcdata->type != NEBTYPE_SERVICECHECK_ASYNC_PRECHECK )
        return NEB_OK;

    /* shouldn't happen - internal Nagios error */
    if ( svcdata == 0 ) {
        gm_log( GM_LOG_ERROR, "Service handler received NULL service data structure.\n" );
        return NEBERROR_CALLBACKCANCEL;
    }

    /* get objects and set target function */
    if((svc=svcdata->object_ptr)==NULL) {
        gm_log( GM_LOG_ERROR, "Service handler received NULL service object pointer.\n" );
        return NEBERROR_CALLBACKCANCEL;
    }

    /* find the host associated with this service */
    if((hst=svc->host_ptr)==NULL) {
        gm_log( GM_LOG_ERROR, "Service handler received NULL host object pointer.\n" );
        return NEBERROR_CALLBACKCANCEL;
    }
    set_target_queue( hst, svc );

    /* local check? */
    if(!strcmp( target_queue, "" )) {
        gm_log( GM_LOG_DEBUG, "passing by local servicecheck: %s - %s\n", svcdata->host_name, svcdata->service_description);
        return NEB_OK;
    }

    gm_log( GM_LOG_DEBUG, "received job for queue %s: %s - %s\n", target_queue, svcdata->host_name, svcdata->service_description );

    temp_buffer[0]='\x0';

    /* as we have to intercept service checks so early
     * (we cannot cancel checks otherwise)
     * we have to do some service check logic here
     * taken from checks.c:
     */
    /* clear check options - we don't want old check options retained */
    svc->check_options=CHECK_OPTION_NONE;

    /* unset the freshening flag, otherwise only the first freshness check would be run */
    svc->is_being_freshened=FALSE;

    /* grab the host and service macro variables */
    clear_volatile_macros();
    grab_host_macros(hst);
    grab_service_macros(svc);

    /* get the raw command line */
    get_raw_command_line(svc->check_command_ptr,svc->service_check_command,&raw_command,0);
    if(raw_command==NULL){
        gm_log( GM_LOG_ERROR, "Raw check command for service '%s' on host '%s' was NULL - aborting.\n", svc->description, svc->host_name );
        return NEBERROR_CALLBACKCANCEL;
    }

    /* process any macros contained in the argument */
    process_macros(raw_command, &processed_command, 0);
    if(processed_command==NULL) {
        gm_log( GM_LOG_ERROR, "Processed check command for service '%s' on host '%s' was NULL - aborting.\n", svc->description, svc->host_name);
        my_free(raw_command);
        return NEBERROR_CALLBACKCANCEL;
    }

    /* log latency */
    if(mod_gm_opt->debug_level >= GM_LOG_DEBUG) {
        localtime_r(&svc->next_check, &next_check);
        strftime(buffer1, sizeof(buffer1), "%Y-%m-%d %H:%M:%S", &next_check );
        gm_log( GM_LOG_DEBUG, "service: '%s' - '%s', next_check is at %s, latency so far: %i\n", svcdata->host_name, svcdata->service_description, buffer1, ((int)core_time.tv_sec - (int)svc->next_check));
    }

    /* increment number of service checks that are currently running... */
    currently_running_service_checks++;

    /* set the execution flag */
    svc->is_executing=TRUE;

    gm_log( GM_LOG_TRACE, "cmd_line: %s\n", processed_command );

    snprintf( temp_buffer,GM_BUFFERSIZE-1,"type=service\nresult_queue=%s\nhost_name=%s\nservice_description=%s\nstart_time=%i.0\nnext_check=%i.0\ncore_time=%i.%i\ntimeout=%d\ncommand_line=%s\n\n\n",
              mod_gm_opt->result_queue,
              svcdata->host_name,
              svcdata->service_description,
              (int)svc->next_check,
              (int)svc->next_check,
              (int)core_time.tv_sec,
              (int)core_time.tv_usec,
              service_check_timeout,
              processed_command
            );

    uniq[0]='\x0';
    snprintf( uniq,GM_BUFFERSIZE-1,"%s-%s", svcdata->host_name, svcdata->service_description);

    /* execute forced checks with high prio as they are propably user requested */
    if(check_result_info.check_options & CHECK_OPTION_FORCE_EXECUTION)
        prio = GM_JOB_PRIO_HIGH;

    if(add_job_to_queue( &client,
                         mod_gm_opt->server_list,
                         target_queue,
                        (mod_gm_opt->use_uniq_jobs == GM_ENABLED ? uniq : NULL),
                         temp_buffer,
                         prio,
                         GM_DEFAULT_JOB_RETRIES,
                         mod_gm_opt->transportmode,
                         TRUE
                        ) == GM_OK) {
        gm_log( GM_LOG_TRACE, "handle_svc_check() finished successfully\n" );
    }
    else {
        my_free(raw_command);
        my_free(processed_command);

        /* unset the execution flag */
        svc->is_executing=FALSE;

        /* decrement number of host checks that are currently running */
        currently_running_service_checks--;

        gm_log( GM_LOG_TRACE, "handle_svc_check() finished unsuccessfully\n" );
        return NEBERROR_CALLBACKCANCEL;
    }

    /* clean up */
    my_free(raw_command);
    my_free(processed_command);

    /* orphanded check - submit fake result to mark service as orphaned */
    if(mod_gm_opt->orphan_service_checks == GM_ENABLED && svc->check_options & CHECK_OPTION_ORPHAN_CHECK) {
        gm_log( GM_LOG_DEBUG, "service check for %s - %s orphanded\n", svc->host_name, svc->description );
        if ( ( chk_result = ( check_result * )malloc( sizeof *chk_result ) ) == 0 )
            return NEBERROR_CALLBACKCANCEL;
        snprintf( temp_buffer,GM_BUFFERSIZE-1,"(service check orphaned, is the mod-gearman worker on queue '%s' running?)\n", target_queue);
        init_check_result(chk_result);
        chk_result->host_name           = strdup( svc->host_name );
        chk_result->service_description = strdup( svc->description );
        chk_result->scheduled_check     = TRUE;
        chk_result->reschedule_check    = TRUE;
        chk_result->output_file         = 0;
        chk_result->output_file_fd      = -1;
        chk_result->output              = strdup(temp_buffer);
        chk_result->return_code         = 2;
        chk_result->check_options       = CHECK_OPTION_NONE;
        chk_result->object_check_type   = SERVICE_CHECK;
        chk_result->check_type          = SERVICE_CHECK_ACTIVE;
        chk_result->start_time.tv_sec   = (unsigned long)time(NULL);
        chk_result->finish_time.tv_sec  = (unsigned long)time(NULL);
        chk_result->latency             = 0;
        mod_gm_add_result_to_list( chk_result );
        chk_result = NULL;
    }

    /* tell nagios to not execute */
    gm_log( GM_LOG_TRACE, "handle_svc_check() finished successfully -> %d\n", NEBERROR_CALLBACKOVERRIDE );

    return NEBERROR_CALLBACKOVERRIDE;
}
Beispiel #26
0
Datei: ll.c Projekt: hmofrad/etc
void my_free(struct Node *head) {
    if(head->next) {
        my_free(head->next);
    }
    free(head);
}
Beispiel #27
0
MY_DIR	*my_dir(const char *path, myf MyFlags)
{
  char          *buffer;
  MY_DIR        *result= 0;
  FILEINFO      finfo;
  DYNAMIC_ARRAY *dir_entries_storage;
  MEM_ROOT      *names_storage;
  DIR		*dirp;
  struct dirent *dp;
  char		tmp_path[FN_REFLEN+1],*tmp_file;
#ifdef THREAD
  char	dirent_tmp[sizeof(struct dirent)+_POSIX_PATH_MAX+1];
#endif
  DBUG_ENTER("my_dir");
  DBUG_PRINT("my",("path: '%s' MyFlags: %d",path,MyFlags));

#if defined(THREAD) && !defined(HAVE_READDIR_R)
  pthread_mutex_lock(&THR_LOCK_open);
#endif

  dirp = opendir(directory_file_name(tmp_path,(char *) path));
#if defined(__amiga__)
  if ((dirp->dd_fd) < 0)			/* Directory doesn't exists */
    goto error;
#endif
  if (dirp == NULL || 
      ! (buffer= my_malloc(ALIGN_SIZE(sizeof(MY_DIR)) + 
                           ALIGN_SIZE(sizeof(DYNAMIC_ARRAY)) +
                           sizeof(MEM_ROOT), MyFlags)))
    goto error;

  dir_entries_storage= (DYNAMIC_ARRAY*)(buffer + ALIGN_SIZE(sizeof(MY_DIR))); 
  names_storage= (MEM_ROOT*)(buffer + ALIGN_SIZE(sizeof(MY_DIR)) +
                             ALIGN_SIZE(sizeof(DYNAMIC_ARRAY)));
  
  if (my_init_dynamic_array(dir_entries_storage, sizeof(FILEINFO),
                            ENTRIES_START_SIZE, ENTRIES_INCREMENT))
  {
    my_free((uchar*) buffer,MYF(0));
    goto error;
  }
  init_alloc_root(names_storage, NAMES_START_SIZE, NAMES_START_SIZE);
  
  /* MY_DIR structure is allocated and completly initialized at this point */
  result= (MY_DIR*)buffer;

  tmp_file=strend(tmp_path);

#ifdef THREAD
  dp= (struct dirent*) dirent_tmp;
#else
  dp=0;
#endif
  
  while (!(READDIR(dirp,(struct dirent*) dirent_tmp,dp)))
  {
    if (!(finfo.name= strdup_root(names_storage, dp->d_name)))
      goto error;
    
    if (MyFlags & MY_WANT_STAT)
    {
      if (!(finfo.mystat= (MY_STAT*)alloc_root(names_storage, 
                                               sizeof(MY_STAT))))
        goto error;
      
      bzero(finfo.mystat, sizeof(MY_STAT));
      VOID(strmov(tmp_file,dp->d_name));
      VOID(my_stat(tmp_path, finfo.mystat, MyFlags));
      if (!(finfo.mystat->st_mode & MY_S_IREAD))
        continue;
    }
    else
      finfo.mystat= NULL;

    if (push_dynamic(dir_entries_storage, (uchar*)&finfo))
      goto error;
  }

  (void) closedir(dirp);
#if defined(THREAD) && !defined(HAVE_READDIR_R)
  pthread_mutex_unlock(&THR_LOCK_open);
#endif
  result->dir_entry= (FILEINFO *)dir_entries_storage->buffer;
  result->number_off_files= dir_entries_storage->elements;
  
  if (!(MyFlags & MY_DONT_SORT))
    my_qsort((void *) result->dir_entry, result->number_off_files,
          sizeof(FILEINFO), (qsort_cmp) comp_names);
  DBUG_RETURN(result);

 error:
#if defined(THREAD) && !defined(HAVE_READDIR_R)
  pthread_mutex_unlock(&THR_LOCK_open);
#endif
  my_errno=errno;
  if (dirp)
    (void) closedir(dirp);
  my_dirend(result);
  if (MyFlags & (MY_FAE | MY_WME))
    my_error(EE_DIR,MYF(ME_BELL+ME_WAITTANG),path,my_errno);
  DBUG_RETURN((MY_DIR *) NULL);
} /* my_dir */
Beispiel #28
0
/* send event handler data to broker */
int broker_event_handler(int type, int flags, int attr, int eventhandler_type, void *data, int state, int state_type, struct timeval start_time, struct timeval end_time, double exectime, int timeout, int early_timeout, int retcode, char *cmd, char *cmdline, char *output, struct timeval *timestamp) {
	service *temp_service = NULL;
	host *temp_host = NULL;
	char *command_buf = NULL;
	char *command_name = NULL;
	char *command_args = NULL;
	nebstruct_event_handler_data ds;
	int return_code = OK;

	if(!(event_broker_options & BROKER_EVENT_HANDLERS))
		return return_code;

	if(data == NULL)
		return ERROR;

	/* get command name/args */
	if(cmd != NULL) {
		command_buf = (char *)strdup(cmd);
		command_name = strtok(command_buf, "!");
		command_args = strtok(NULL, "\x0");
		}

	/* fill struct with relevant data */
	ds.type = type;
	ds.flags = flags;
	ds.attr = attr;
	ds.timestamp = get_broker_timestamp(timestamp);

	ds.eventhandler_type = eventhandler_type;
	if(eventhandler_type == SERVICE_EVENTHANDLER || eventhandler_type == GLOBAL_SERVICE_EVENTHANDLER) {
		temp_service = (service *)data;
		ds.host_name = temp_service->host_name;
		ds.service_description = temp_service->description;
		}
	else {
		temp_host = (host *)data;
		ds.host_name = temp_host->name;
		ds.service_description = NULL;
		}
	ds.object_ptr = data;
	ds.state = state;
	ds.state_type = state_type;
	ds.start_time = start_time;
	ds.end_time = end_time;
	ds.timeout = timeout;
	ds.command_name = command_name;
	ds.command_args = command_args;
	ds.command_line = cmdline;
	ds.early_timeout = early_timeout;
	ds.execution_time = exectime;
	ds.return_code = retcode;
	ds.output = output;

	/* make callbacks */
	return_code = neb_make_callbacks(NEBCALLBACK_EVENT_HANDLER_DATA, (void *)&ds);

	/* free memory */
	my_free(command_buf);

	return return_code;
	}
Beispiel #29
0
/* handle host check events */
static int handle_host_check( int event_type, void *data ) {
    nebstruct_host_check_data * hostdata;
    char *raw_command=NULL;
    char *processed_command=NULL;
    host * hst;
    check_result * chk_result;
    int check_options;
    struct timeval core_time;
    struct tm next_check;
    char buffer1[GM_BUFFERSIZE];

    gettimeofday(&core_time,NULL);

    gm_log( GM_LOG_TRACE, "handle_host_check(%i)\n", event_type );

    if ( mod_gm_opt->do_hostchecks != GM_ENABLED )
        return NEB_OK;

    hostdata = ( nebstruct_host_check_data * )data;

    gm_log( GM_LOG_TRACE, "---------------\nhost Job -> %i, %i\n", event_type, hostdata->type );

    if ( event_type != NEBCALLBACK_HOST_CHECK_DATA )
        return NEB_OK;

    /* ignore non-initiate host checks */
    if (   hostdata->type != NEBTYPE_HOSTCHECK_ASYNC_PRECHECK
        && hostdata->type != NEBTYPE_HOSTCHECK_SYNC_PRECHECK)
        return NEB_OK;

    /* get objects and set target function */
    if((hst=hostdata->object_ptr)==NULL) {
        gm_log( GM_LOG_ERROR, "Host handler received NULL host object pointer.\n" );
        return NEBERROR_CALLBACKCANCEL;
    }
    set_target_queue( hst, NULL );

    /* local check? */
    if(!strcmp( target_queue, "" )) {
        gm_log( GM_LOG_DEBUG, "passing by local hostcheck: %s\n", hostdata->host_name );
        return NEB_OK;
    }

    gm_log( GM_LOG_DEBUG, "received job for queue %s: %s\n", target_queue, hostdata->host_name );

    /* as we have to intercept host checks so early
     * (we cannot cancel checks otherwise)
     * we have to do some host check logic here
     * taken from checks.c:
     */
    /* clear check options - we don't want old check options retained */
    check_options = hst->check_options;
    hst->check_options = CHECK_OPTION_NONE;

    /* unset the freshening flag, otherwise only the first freshness check would be run */
    hst->is_being_freshened=FALSE;

    /* adjust host check attempt */
    adjust_host_check_attempt(hst,TRUE);

    temp_buffer[0]='\x0';

    /* grab the host macro variables */
    clear_volatile_macros();
    grab_host_macros(hst);

    /* get the raw command line */
    get_raw_command_line(hst->check_command_ptr,hst->check_command,&raw_command,0);
    if(raw_command==NULL){
        gm_log( GM_LOG_ERROR, "Raw check command for host '%s' was NULL - aborting.\n",hst->name );
        return NEBERROR_CALLBACKCANCEL;
    }

    /* process any macros contained in the argument */
    process_macros(raw_command,&processed_command,0);
    if(processed_command==NULL){
        gm_log( GM_LOG_ERROR, "Processed check command for host '%s' was NULL - aborting.\n",hst->name);
        return NEBERROR_CALLBACKCANCEL;
    }

    /* log latency */
    if(mod_gm_opt->debug_level >= GM_LOG_DEBUG) {
        localtime_r(&hst->next_check, &next_check);
        strftime(buffer1, sizeof(buffer1), "%Y-%m-%d %H:%M:%S", &next_check );
        gm_log( GM_LOG_DEBUG, "host: '%s', next_check is at %s, latency so far: %i\n", hst->name, buffer1, ((int)core_time.tv_sec - (int)hst->next_check));
    }

    /* increment number of host checks that are currently running */
    currently_running_host_checks++;

    /* set the execution flag */
    hst->is_executing=TRUE;

    gm_log( GM_LOG_TRACE, "cmd_line: %s\n", processed_command );

    snprintf( temp_buffer,GM_BUFFERSIZE-1,"type=host\nresult_queue=%s\nhost_name=%s\nstart_time=%i.0\nnext_check=%i.0\ntimeout=%d\ncore_time=%i.%i\ncommand_line=%s\n\n\n",
              mod_gm_opt->result_queue,
              hst->name,
              (int)hst->next_check,
              (int)hst->next_check,
              host_check_timeout,
              (int)core_time.tv_sec,
              (int)core_time.tv_usec,
              processed_command
            );

    if(add_job_to_queue( &client,
                         mod_gm_opt->server_list,
                         target_queue,
                        (mod_gm_opt->use_uniq_jobs == GM_ENABLED ? hst->name : NULL),
                         temp_buffer,
                         GM_JOB_PRIO_NORMAL,
                         GM_DEFAULT_JOB_RETRIES,
                         mod_gm_opt->transportmode,
                         TRUE
                        ) == GM_OK) {
    }
    else {
        my_free(raw_command);
        my_free(processed_command);

        /* unset the execution flag */
        hst->is_executing=FALSE;

        /* decrement number of host checks that are currently running */
        currently_running_host_checks--;

        gm_log( GM_LOG_TRACE, "handle_host_check() finished unsuccessfully -> %d\n", NEBERROR_CALLBACKCANCEL );
        return NEBERROR_CALLBACKCANCEL;
    }

    /* clean up */
    my_free(raw_command);
    my_free(processed_command);

    /* orphaned check - submit fake result to mark host as orphaned */
    if(mod_gm_opt->orphan_host_checks == GM_ENABLED && check_options & CHECK_OPTION_ORPHAN_CHECK) {
        gm_log( GM_LOG_DEBUG, "host check for %s orphaned\n", hst->name );
        if ( ( chk_result = ( check_result * )malloc( sizeof *chk_result ) ) == 0 )
            return NEBERROR_CALLBACKCANCEL;
        snprintf( temp_buffer,GM_BUFFERSIZE-1,"(host check orphaned, is the mod-gearman worker on queue '%s' running?)\n", target_queue);
        init_check_result(chk_result);
        chk_result->host_name           = strdup( hst->name );
        chk_result->scheduled_check     = TRUE;
        chk_result->reschedule_check    = TRUE;
        chk_result->output_file         = 0;
        chk_result->output_file_fp      = NULL;
        chk_result->output              = strdup(temp_buffer);
        chk_result->return_code         = mod_gm_opt->orphan_return;
        chk_result->check_options       = CHECK_OPTION_NONE;
        chk_result->object_check_type   = HOST_CHECK;
        chk_result->check_type          = HOST_CHECK_ACTIVE;
        chk_result->start_time.tv_sec   = (unsigned long)time(NULL);
        chk_result->finish_time.tv_sec  = (unsigned long)time(NULL);
        chk_result->latency             = 0;
        mod_gm_add_result_to_list( chk_result );
        chk_result = NULL;
    }

    /* tell naemon to not execute */
    gm_log( GM_LOG_TRACE, "handle_host_check() finished successfully -> %d\n", NEBERROR_CALLBACKOVERRIDE );
    return NEBERROR_CALLBACKOVERRIDE;
}
Beispiel #30
0
int readSystemUUID(u_char *uuidbuf){
	int	                    gotData = NO;
	BSTR                    path = SysAllocString(L"root\\wmi");
	BSTR                    className = SysAllocString(L"MSSmBios_RawSMBiosTables");
	BSTR                    propName = SysAllocString(L"SMBiosData");
	ULONG                   uReturned = 1;
	HRESULT                 hr = S_FALSE;
	IWbemLocator            *pLocator = NULL;
	IWbemServices           *pNamespace = NULL;
	IEnumWbemClassObject    *pEnumSMBIOS = NULL;
	IWbemClassObject        *pSmbios = NULL;
	CIMTYPE                 type;
	VARIANT                 pVal;
	SAFEARRAY               *pArray = NULL;
	smbiosHeader            *smbiosData;
	u_char                  *uuidPtr;
	DWORD                   smbufSize;

	hr =  CoInitializeEx(0, COINIT_MULTITHREADED);
	if (! SUCCEEDED( hr ) ){
		myLog(LOG_ERR,"readSystemUUID: failed to initialize COM");
		gotData = NO;
		goto Cleanup;
	}
	
	hr =  CoInitializeSecurity(NULL,-1,NULL,NULL,RPC_C_AUTHN_LEVEL_DEFAULT,RPC_C_IMP_LEVEL_IMPERSONATE,NULL,EOAC_NONE,NULL);
	hr = CoCreateInstance( CLSID_WbemLocator, NULL, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID *) &pLocator );
	if(! SUCCEEDED( hr ) ){
		myLog(LOG_ERR,"readSystemUUID: failed to create WMI instance");
		gotData = NO;
		goto Cleanup;
	}

	hr = pLocator->ConnectServer(path, NULL, NULL, NULL, 0, NULL, NULL, &pNamespace );
	pLocator->Release();
	if( WBEM_S_NO_ERROR != hr ){
		myLog(LOG_ERR,"getSystemUUID: ConnectServer() failed for namespace");
		gotData = NO;
		goto Cleanup;
	}

	hr = pNamespace->CreateInstanceEnum(className, 0, NULL, &pEnumSMBIOS );
	pNamespace->Release();
	if (! SUCCEEDED( hr ) ){
		myLog(LOG_ERR,"getSystemUUID: CreateInstanceEnum() failed for MSSmBios_RawSMBiosTables");
		gotData = NO;
		goto Cleanup;
	}

	hr = pEnumSMBIOS->Next(4000, 1, &pSmbios, &uReturned );
	pEnumSMBIOS->Release();
	if ( 1 != uReturned ){
		myLog(LOG_ERR,"getSystemUUID: Next() failed for pEnumSMBIOS");
		gotData = NO;
		goto Cleanup;
	}
	
	pSmbios->Get(propName,0L,&pVal,&type,NULL);
	if ( ( VT_UI1 | VT_ARRAY) != pVal.vt){
		myLog(LOG_ERR,"getSystemUUID: Get() failed for pSmbios");
	    gotData = NO;
		goto Cleanup;
	}

	pArray = V_ARRAY(&pVal);
	smbufSize = pArray->rgsabound[0].cElements;
	smbiosData = (smbiosHeader*)my_calloc(smbufSize);
	if(!smbiosData){
		myLog(LOG_ERR,"getSystemUUID: failed to allocate buffer for smbiosData");
		gotData = NO;
		goto Cleanup;
	}
	memcpy((void*)smbiosData,pArray->pvData,smbufSize);
	uuidPtr = (u_char*)getUUIDPtr(smbufSize,smbiosData);
	if(!uuidPtr){
		myLog(LOG_ERR,"getSystemUUID: failed to find UUID in SMBIOS");
		gotData = NO;
		goto Cleanup;
	}
	memcpy((void*)uuidbuf,uuidPtr,16);
	gotData = YES;

Cleanup:
	SysFreeString(propName);
	SysFreeString(className);
	SysFreeString(path);
	if(smbiosData) my_free(smbiosData);

	return gotData;
}