Esempio n. 1
0
File: unix.c Progetto: dnaeon/core
void Unix_GetInterfaceInfo(enum cfagenttype ag)
{
    int fd, len, i, j, first_address = false, ipdefault = false;
    struct ifreq ifbuf[CF_IFREQ], ifr, *ifp;
    struct ifconf list;
    struct sockaddr_in *sin;
    struct hostent *hp;
    char *sp, workbuf[CF_BUFSIZE];
    char ip[CF_MAXVARSIZE];
    char name[CF_MAXVARSIZE];
    char last_name[CF_BUFSIZE];
    Rlist *interfaces = NULL, *hardware = NULL, *ips = NULL;

    CfDebug("Unix_GetInterfaceInfo()\n");

    memset(ifbuf, 0, sizeof(ifbuf));

    InitIgnoreInterfaces();
    
    last_name[0] = '\0';

    if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
    {
        CfOut(cf_error, "socket", "Couldn't open socket");
        exit(1);
    }

    list.ifc_len = sizeof(ifbuf);
    list.ifc_req = ifbuf;

# ifdef SIOCGIFCONF
    if (ioctl(fd, SIOCGIFCONF, &list) == -1 || (list.ifc_len < (sizeof(struct ifreq))))
# else
    if (ioctl(fd, OSIOCGIFCONF, &list) == -1 || (list.ifc_len < (sizeof(struct ifreq))))
# endif
    {
        CfOut(cf_error, "ioctl", "Couldn't get interfaces - old kernel? Try setting CF_IFREQ to 1024");
        exit(1);
    }

    last_name[0] = '\0';

    for (j = 0, len = 0, ifp = list.ifc_req; len < list.ifc_len;
         len += SIZEOF_IFREQ(*ifp), j++, ifp = (struct ifreq *) ((char *) ifp + SIZEOF_IFREQ(*ifp)))
    {

        if (ifp->ifr_addr.sa_family == 0)
        {
            continue;
        }

        if (ifp->ifr_name == NULL || strlen(ifp->ifr_name) == 0)
        {
            continue;
        }

        /* Skip virtual network interfaces for Linux, which seems to be a problem */

        if (IgnoreInterface(ifp->ifr_name))
        {
            continue;
        }
        
        if (strstr(ifp->ifr_name, ":"))
        {
            if (VSYSTEMHARDCLASS == linuxx)
            {
                CfOut(cf_verbose, "", "Skipping apparent virtual interface %d: %s\n", j + 1, ifp->ifr_name);
                continue;
            }
        }
        else
        {
            CfOut(cf_verbose, "", "Interface %d: %s\n", j + 1, ifp->ifr_name);
        }

        // Ignore the loopback

        if (strcmp(ifp->ifr_name, "lo") == 0)
        {
            continue;
        }

        if (strncmp(last_name, ifp->ifr_name, sizeof(ifp->ifr_name)) == 0)
        {
            first_address = false;
        }
        else
        {
            strncpy(last_name, ifp->ifr_name, sizeof(ifp->ifr_name));

            if (!first_address)
            {
                NewScalar("sys", "interface", last_name, cf_str);
                first_address = true;
            }
        }

        snprintf(workbuf, CF_BUFSIZE, "net_iface_%s", CanonifyName(ifp->ifr_name));

        NewClass(workbuf);

        if (ifp->ifr_addr.sa_family == AF_INET)
        {
            strncpy(ifr.ifr_name, ifp->ifr_name, sizeof(ifp->ifr_name));

            if (ioctl(fd, SIOCGIFFLAGS, &ifr) == -1)
            {
                CfOut(cf_error, "ioctl", "No such network device");
                //close(fd);
                //return;
                continue;
            }

            if ((ifr.ifr_flags & IFF_BROADCAST) && !(ifr.ifr_flags & IFF_LOOPBACK))
            {
                sin = (struct sockaddr_in *) &ifp->ifr_addr;

                if (IgnoreJailInterface(j + 1, sin))
                {
                    CfOut(cf_verbose, "", "Ignoring interface %d", j + 1);
                    continue;
                }

                CfDebug("Adding hostip %s..\n", inet_ntoa(sin->sin_addr));
                NewClass(inet_ntoa(sin->sin_addr));

                if ((hp =
                     gethostbyaddr((char *) &(sin->sin_addr.s_addr), sizeof(sin->sin_addr.s_addr), AF_INET)) == NULL)
                {
                    CfDebug("No hostinformation for %s not found\n", inet_ntoa(sin->sin_addr));
                }
                else
                {
                    if (hp->h_name != NULL)
                    {
                        CfDebug("Adding hostname %s..\n", hp->h_name);
                        NewClass(hp->h_name);

                        if (hp->h_aliases != NULL)
                        {
                            for (i = 0; hp->h_aliases[i] != NULL; i++)
                            {
                                CfOut(cf_verbose, "", "Adding alias %s..\n", hp->h_aliases[i]);
                                NewClass(hp->h_aliases[i]);
                            }
                        }
                    }
                }

                if (strcmp(inet_ntoa(sin->sin_addr), "0.0.0.0") == 0)
                {
                    // Maybe we need to do something windows specific here?
                    CfOut(cf_verbose, "", " !! Cannot discover hardware IP, using DNS value");
                    strcpy(ip, "ipv4_");
                    strcat(ip, VIPADDRESS);
                    AppendItem(&IPADDRESSES, VIPADDRESS, "");
                    AppendRlist(&ips, VIPADDRESS, CF_SCALAR);

                    for (sp = ip + strlen(ip) - 1; (sp > ip); sp--)
                    {
                        if (*sp == '.')
                        {
                            *sp = '\0';
                            NewClass(ip);
                        }
                    }

                    strcpy(ip, VIPADDRESS);
                    i = 3;

                    for (sp = ip + strlen(ip) - 1; (sp > ip); sp--)
                    {
                        if (*sp == '.')
                        {
                            *sp = '\0';
                            snprintf(name, CF_MAXVARSIZE - 1, "ipv4_%d[%s]", i--, CanonifyName(VIPADDRESS));
                            NewScalar("sys", name, ip, cf_str);
                        }
                    }
                    //close(fd);
                    //return;
                    continue;
                }

                strncpy(ip, "ipv4_", CF_MAXVARSIZE);
                strncat(ip, inet_ntoa(sin->sin_addr), CF_MAXVARSIZE - 6);
                NewClass(ip);

                if (!ipdefault)
                {
                    ipdefault = true;
                    NewScalar("sys", "ipv4", inet_ntoa(sin->sin_addr), cf_str);

                    strcpy(VIPADDRESS, inet_ntoa(sin->sin_addr));
                }

                AppendItem(&IPADDRESSES, inet_ntoa(sin->sin_addr), "");
                AppendRlist(&ips, inet_ntoa(sin->sin_addr), CF_SCALAR);

                for (sp = ip + strlen(ip) - 1; (sp > ip); sp--)
                {
                    if (*sp == '.')
                    {
                        *sp = '\0';
                        NewClass(ip);
                    }
                }

                // Set the IPv4 on interface array

                strcpy(ip, inet_ntoa(sin->sin_addr));

                if (ag != cf_know)
                {
                    snprintf(name, CF_MAXVARSIZE - 1, "ipv4[%s]", CanonifyName(ifp->ifr_name));
                }
                else
                {
                    snprintf(name, CF_MAXVARSIZE - 1, "ipv4[interface_name]");
                }

                NewScalar("sys", name, ip, cf_str);

                i = 3;

                for (sp = ip + strlen(ip) - 1; (sp > ip); sp--)
                {
                    if (*sp == '.')
                    {
                        *sp = '\0';

                        if (ag != cf_know)
                        {
                            snprintf(name, CF_MAXVARSIZE - 1, "ipv4_%d[%s]", i--, CanonifyName(ifp->ifr_name));
                        }
                        else
                        {
                            snprintf(name, CF_MAXVARSIZE - 1, "ipv4_%d[interface_name]", i--);
                        }

                        NewScalar("sys", name, ip, cf_str);
                    }
                }
            }

            // Set the hardware/mac address array
            Unix_GetMacAddress(ag, fd, &ifr, ifp, &interfaces, &hardware);
        }
    }

    close(fd);

    NewList("sys", "interfaces", interfaces, cf_slist);
    NewList("sys", "hardware_addresses", hardware, cf_slist);
    NewList("sys", "ip_addresses", ips, cf_slist);
}
Esempio n. 2
0
//----------------------------------------
void CDatasetTreeCtrl::AddItemsToTree()
{
  //int image = wxGetApp().ShowImages() ? MyTreeCtrl::TreeCtrlIcon_Folder : -1;
  int image = CTreeCtrl::TreeCtrlIcon_Folder;

  /*wxTreeItemId rootId = AddRoot(wxT("Root"),
                                image, image,
                                new MyTreeItemData(wxT("Root item")));
                                */
  wxTreeItemId rootId = AddRoot(wxT("Root"),
                                image, image);

  CWorkspaceDataset* wks = wxGetApp().GetCurrentWorkspaceDataset();
  if (wks == NULL)
  {
    return;
  }
  
  if (wks->GetDatasetCount() <= 0)
  {
    return;
  }
  /*
  wxArrayString array;
  wks->GetDatasetNames(array);
  for (uint32_t i = 0 ; i < array.GetCount() ; i++)
  {
    image = CTreeCtrl::TreeCtrlIcon_File;
    wxTreeItemId id = AppendItem(rootId, array[i], image, image + 1);
                                         
  }  
*/
  CObMap* datasets = wks->GetDatasets();
  CObMap::iterator it;

  for (it = datasets->begin() ; it != datasets->end() ; it++)
  {
    CDataset* dataset = dynamic_cast<CDataset*>(it->second);

    //string value = it->first;
    image = CTreeCtrl::TreeCtrlIcon_File;
    wxTreeItemId id = AppendItem(rootId, (it->first).c_str(), image, image + 1, new CDatasetTreeItemData(dataset));
  }



/*
  m_currentDataset = -1;
  GetOpdataset()->SetSelection(m_currentDataset);

  SetCurrentDataset();

  EnableCtrl();
    wxTreeItemId rootId = AddRoot(wxT("Root"),
                                  image, image,
                                  new MyTreeItemData(wxT("Root item")));
    if ( image != -1 )
    {
        SetItemImage(rootId, TreeCtrlIcon_FolderOpened, wxTreeItemIcon_Expanded);
    }

    AddItemsRecursively(rootId, numChildren, depth, 0);

    // set some colours/fonts for testing
    SetItemFont(rootId, *wxITALIC_FONT);

    wxTreeItemIdValue cookie;
    wxTreeItemId id = GetFirstChild(rootId, cookie);
    SetItemTextColour(id, *wxBLUE);

    id = GetNextChild(rootId, cookie);
    id = GetNextChild(rootId, cookie);
    SetItemTextColour(id, *wxRED);
    SetItemBackgroundColour(id, *wxLIGHT_GREY);
    */
}
Esempio n. 3
0
File: unix.c Progetto: dnaeon/core
int Unix_LoadProcessTable(Item **procdata)
{
    FILE *prp;
    char pscomm[CF_MAXLINKSIZE], vbuff[CF_BUFSIZE], *sp;
    Item *rootprocs = NULL;
    Item *otherprocs = NULL;
    const char *psopts = GetProcessOptions();

    snprintf(pscomm, CF_MAXLINKSIZE, "%s %s", VPSCOMM[VSYSTEMHARDCLASS], psopts);

    CfOut(cf_verbose, "", "Observe process table with %s\n", pscomm);

    if ((prp = cf_popen(pscomm, "r")) == NULL)
    {
        CfOut(cf_error, "popen", "Couldn't open the process list with command %s\n", pscomm);
        return false;
    }

    while (!feof(prp))
    {
        memset(vbuff, 0, CF_BUFSIZE);
        CfReadLine(vbuff, CF_BUFSIZE, prp);

        for (sp = vbuff + strlen(vbuff) - 1; sp > vbuff && isspace(*sp); sp--)
        {
            *sp = '\0';
        }

        if (ForeignZone(vbuff))
        {
            continue;
        }

        AppendItem(procdata, vbuff, "");
    }

    cf_pclose(prp);

/* Now save the data */

    snprintf(vbuff, CF_MAXVARSIZE, "%s/state/cf_procs", CFWORKDIR);
    RawSaveItemList(*procdata, vbuff);

    CopyList(&rootprocs, *procdata);
    CopyList(&otherprocs, *procdata);

    while (DeleteItemNotContaining(&rootprocs, "root"))
    {
    }

    while (DeleteItemContaining(&otherprocs, "root"))
    {
    }

    if (otherprocs)
    {
        PrependItem(&rootprocs, otherprocs->name, NULL);
    }

    snprintf(vbuff, CF_MAXVARSIZE, "%s/state/cf_rootprocs", CFWORKDIR);
    RawSaveItemList(rootprocs, vbuff);
    DeleteItemList(rootprocs);

    snprintf(vbuff, CF_MAXVARSIZE, "%s/state/cf_otherprocs", CFWORKDIR);
    RawSaveItemList(otherprocs, vbuff);
    DeleteItemList(otherprocs);

    return true;
}
Esempio n. 4
0
int LoadProcessTable()
{
    FILE *prp;
    char pscomm[CF_MAXLINKSIZE];
    Item *rootprocs = NULL;
    Item *otherprocs = NULL;


    if (PROCESSTABLE)
    {
        Log(LOG_LEVEL_VERBOSE, "Reusing cached process table");
        return true;
    }

    LoadPlatformExtraTable();

    CheckPsLineLimitations();

    const char *psopts = GetProcessOptions();

    snprintf(pscomm, CF_MAXLINKSIZE, "%s %s", VPSCOMM[VPSHARDCLASS], psopts);

    Log(LOG_LEVEL_VERBOSE, "Observe process table with %s", pscomm);

    if ((prp = cf_popen(pscomm, "r", false)) == NULL)
    {
        Log(LOG_LEVEL_ERR, "Couldn't open the process list with command '%s'. (popen: %s)", pscomm, GetErrorStr());
        return false;
    }

    size_t vbuff_size = CF_BUFSIZE;
    char *vbuff = xmalloc(vbuff_size);

# ifdef HAVE_GETZONEID

    char *names[CF_PROCCOLS];
    int start[CF_PROCCOLS];
    int end[CF_PROCCOLS];
    Seq *pidlist = SeqNew(1, NULL);
    Seq *rootpidlist = SeqNew(1, NULL);
    bool global_zone = IsGlobalZone();

    if (global_zone)
    {
        int res = ZLoadProcesstable(pidlist, rootpidlist);

        if (res == false)
        {
            Log(LOG_LEVEL_ERR, "Unable to load solaris zone process table.");
            return false;
        }
    }

# endif

    ARG_UNUSED bool header = true;           /* used only if HAVE_GETZONEID */

    for (;;)
    {
        ssize_t res = CfReadLine(&vbuff, &vbuff_size, prp);
        if (res == -1)
        {
            if (!feof(prp))
            {
                Log(LOG_LEVEL_ERR, "Unable to read process list with command '%s'. (fread: %s)", pscomm, GetErrorStr());
                cf_pclose(prp);
                free(vbuff);
                return false;
            }
            else
            {
                break;
            }
        }
        Chop(vbuff, vbuff_size);

# ifdef HAVE_GETZONEID

        if (global_zone)
        {
            if (header)
            {   /* this is the banner so get the column header names for later use*/
                GetProcessColumnNames(vbuff, &names[0], start, end);
            }
            else
            {
               int gpid = ExtractPid(vbuff, names, end);

               if (!IsGlobalProcess(gpid, pidlist, rootpidlist))
               {
                    continue;
               }
            }
        }

# endif
        AppendItem(&PROCESSTABLE, vbuff, "");

        header = false;
    }

    cf_pclose(prp);

/* Now save the data */
    const char* const statedir = GetStateDir();

    snprintf(vbuff, CF_MAXVARSIZE, "%s%ccf_procs", statedir, FILE_SEPARATOR);
    RawSaveItemList(PROCESSTABLE, vbuff, NewLineMode_Unix);

# ifdef HAVE_GETZONEID
    if (global_zone) /* pidlist and rootpidlist are empty if we're not in the global zone */
    {
        Item *ip = PROCESSTABLE;
        while (ip != NULL)
        {
            ZCopyProcessList(&rootprocs, ip, rootpidlist, names, end);
            ip = ip->next;
        }
        ReverseItemList(rootprocs);
        ip = PROCESSTABLE;
        while (ip != NULL)
        {
            ZCopyProcessList(&otherprocs, ip, pidlist, names, end);
            ip = ip->next;
        }
        ReverseItemList(otherprocs);
    }
    else
# endif
    {
        CopyList(&rootprocs, PROCESSTABLE);
        CopyList(&otherprocs, PROCESSTABLE);

        while (DeleteItemNotContaining(&rootprocs, "root"))
        {
        }

        while (DeleteItemContaining(&otherprocs, "root"))
        {
        }
    }
    if (otherprocs)
    {
        PrependItem(&rootprocs, otherprocs->name, NULL);
    }

    snprintf(vbuff, CF_MAXVARSIZE, "%s%ccf_rootprocs", statedir, FILE_SEPARATOR);
    RawSaveItemList(rootprocs, vbuff, NewLineMode_Unix);
    DeleteItemList(rootprocs);

    snprintf(vbuff, CF_MAXVARSIZE, "%s%ccf_otherprocs", statedir, FILE_SEPARATOR);
    RawSaveItemList(otherprocs, vbuff, NewLineMode_Unix);
    DeleteItemList(otherprocs);

    free(vbuff);
    return true;
}
Esempio n. 5
0
File: unix.c Progetto: someara/core
void Unix_FindV6InterfaceInfo(void)
{
    FILE *pp = NULL;
    char buffer[CF_BUFSIZE];

/* Whatever the manuals might say, you cannot get IPV6
   interface configuration from the ioctls. This seems
   to be implemented in a non standard way across OSes
   BSDi has done getifaddrs(), solaris 8 has a new ioctl, Stevens
   book shows the suggestion which has not been implemented...
*/

    CfOut(cf_verbose, "", "Trying to locate my IPv6 address\n");

    switch (VSYSTEMHARDCLASS)
    {
    case cfnt:
        /* NT cannot do this */
        return;

    case irix:
    case irix4:
    case irix64:

        if ((pp = cf_popen("/usr/etc/ifconfig -a", "r")) == NULL)
        {
            CfOut(cf_verbose, "", "Could not find interface info\n");
            return;
        }

        break;

    case hp:

        if ((pp = cf_popen("/usr/sbin/ifconfig -a", "r")) == NULL)
        {
            CfOut(cf_verbose, "", "Could not find interface info\n");
            return;
        }

        break;

    case aix:

        if ((pp = cf_popen("/etc/ifconfig -a", "r")) == NULL)
        {
            CfOut(cf_verbose, "", "Could not find interface info\n");
            return;
        }

        break;

    default:

        if ((pp = cf_popen("/sbin/ifconfig -a", "r")) == NULL)
        {
            CfOut(cf_verbose, "", "Could not find interface info\n");
            return;
        }

    }

/* Don't know the output format of ifconfig on all these .. hope for the best*/

    while (!feof(pp))
    {
        fgets(buffer, CF_BUFSIZE - 1, pp);

        if (ferror(pp))         /* abortable */
        {
            break;
        }

        if (strcasestr(buffer, "inet6"))
        {
            Item *ip, *list = NULL;
            char *sp;

            list = SplitStringAsItemList(buffer, ' ');

            for (ip = list; ip != NULL; ip = ip->next)
            {
                for (sp = ip->name; *sp != '\0'; sp++)
                {
                    if (*sp == '/')     /* Remove CIDR mask */
                    {
                        *sp = '\0';
                    }
                }

                if (IsIPV6Address(ip->name) && (strcmp(ip->name, "::1") != 0))
                {
                    CfOut(cf_verbose, "", "Found IPv6 address %s\n", ip->name);
                    AppendItem(&IPADDRESSES, ip->name, "");
                    NewClass(ip->name);
                }
            }

            DeleteItemList(list);
        }
    }

    cf_pclose(pp);
}
Esempio n. 6
0
void CRemoteTreeView::RefreshItem(wxTreeItemId parent, const CDirectoryListing& listing, bool will_select_parent)
{
	SetItemImages(parent, false);

	wxTreeItemIdValue cookie;
	wxTreeItemId child = GetFirstChild(parent, cookie);
	if (!child || GetItemText(child).empty())
	{
		DisplayItem(parent, listing);
		return;
	}

	CFilterManager filter;

	const wxString path = listing.path.GetPath();

	wxArrayString dirs;
	for (unsigned int i = 0; i < listing.GetCount(); i++)
	{
		if (!listing[i].is_dir())
			continue;

		if (!filter.FilenameFiltered(listing[i].name, path, true, -1, false, 0, listing[i].time))
			dirs.push_back(listing[i].name);
	}

	auto const& sortFunc = CFileListCtrlSortBase::GetCmpFunction(m_nameSortMode);
	dirs.Sort(sortFunc);

	bool inserted = false;
	child = GetLastChild(parent);
	wxArrayString::reverse_iterator iter = dirs.rbegin();
	while (child && iter != dirs.rend()) {
		int cmp = sortFunc(GetItemText(child), *iter);

		if (!cmp) {
			CServerPath path = listing.path;
			path.AddSegment(*iter);

			CDirectoryListing subListing;
			if (m_pState->m_pEngine->CacheLookup(path, subListing) == FZ_REPLY_OK)
			{
				if (!GetLastChild(child) && HasSubdirs(subListing, filter))
					AppendItem(child, _T(""), -1, -1);
				SetItemImages(child, false);
			}
			else
				SetItemImages(child, true);

			child = GetPrevSibling(child);
			++iter;
		}
		else if (cmp > 0) {
			// Child no longer exists
			wxTreeItemId sel = GetSelection();
			while (sel && sel != child)
				sel = GetItemParent(sel);
			wxTreeItemId prev = GetPrevSibling(child);
			if (!sel || will_select_parent)
				Delete(child);
			child = prev;
		}
		else if (cmp < 0) {
			// New directory
			CServerPath path = listing.path;
			path.AddSegment(*iter);

			CDirectoryListing subListing;
			if (m_pState->m_pEngine->CacheLookup(path, subListing) == FZ_REPLY_OK) {
				wxTreeItemId child = AppendItem(parent, *iter, 0, 2, 0);
				SetItemImages(child, false);

				if (HasSubdirs(subListing, filter))
					AppendItem(child, _T(""), -1, -1);
			}
			else {
				wxTreeItemId child = AppendItem(parent, *iter, 1, 3, 0);
				if (child)
					SetItemImages(child, true);
			}

			++iter;
			inserted = true;
		}
	}
	while (child) {
		// Child no longer exists
		wxTreeItemId sel = GetSelection();
		while (sel && sel != child)
			sel = GetItemParent(sel);
		wxTreeItemId prev = GetPrevSibling(child);
		if (!sel || will_select_parent)
			Delete(child);
		child = prev;
	}
	while (iter != dirs.rend()) {
		CServerPath path = listing.path;
		path.AddSegment(*iter);

		CDirectoryListing subListing;
		if (m_pState->m_pEngine->CacheLookup(path, subListing) == FZ_REPLY_OK) {
			wxTreeItemId child = AppendItem(parent, *iter, 0, 2, 0);
			SetItemImages(child, false);

			if (HasSubdirs(subListing, filter))
				AppendItem(child, _T(""), -1, -1);
		}
		else {
			wxTreeItemId child = AppendItem(parent, *iter, 1, 3, 0);
			SetItemImages(child, true);
		}

		++iter;
		inserted = true;
	}

	if (inserted)
		SortChildren(parent);
}
Esempio n. 7
0
//----------------------------------------
wxTreeItemId CFieldsTreeCtrl::InsertField(const wxTreeItemId& parentId, CObjectTreeNode* node)
{
  int32_t depth = node->GetLevel();

  long numChildren = node->ChildCount();

  CField *field  = dynamic_cast<CField*>(node->GetData());
  if (field == NULL)
  {
    wxMessageBox("ERROR in CFieldsTreeCtrl::InsertField - at least one of the tree object is not a CField object",
                 "Error",
              wxOK | wxICON_ERROR);
    return parentId;
  }

  if ((typeid(*field) == typeid(CFieldIndex)) && field->IsVirtual())
  {
    return parentId;
  }

  if ( depth <= 1 )
  {

    wxString str;
    str.Printf(wxT("%s"), field->GetName().c_str());

    // here we pass to AppendItem() normal and selected item images (we
    // suppose that selected image follows the normal one in the enum)
    int32_t image = TreeCtrlIcon_Folder;
    int32_t imageSel = image + 1;

    wxTreeItemId id = AddRoot(str, image, image, new CFieldsTreeItemData(field));

    return id;
  }



  bool hasChildren = numChildren > 0;

  wxString str;
  if (field->GetUnit().empty())
  {
    str.Printf(wxT("%s"), field->GetName().c_str());
  }
  else
  {
    str.Printf(wxT("%s (%s)"), field->GetName().c_str(), field->GetUnit().c_str());
  }

  /*
  // at depth 1 elements won't have any more children
  if ( hasChildren )
  {
      str.Printf(wxT("%s"), field->GetName().c_str());
  }
  else
  {
    str.Printf(wxT("%s child %d.%d"), wxT("File"), folder, n + 1);
  }
  */
  // here we pass to AppendItem() normal and selected item images (we
  // suppose that selected image follows the normal one in the enum)
  int32_t image = (hasChildren) ?  TreeCtrlIcon_Folder : TreeCtrlIcon_File;
  int32_t imageSel = image + 1;

  //wxTreeItemId id = AppendItem(idParent, str, image, imageSel,
  //                             new MyTreeItemData(str));

  wxTreeItemId id = AppendItem(parentId, str, image, imageSel,
                               new CFieldsTreeItemData(field));


  //Expand(parentId);

  if    ( (typeid(*field) == typeid(CFieldRecord))
     || ( (typeid(*field) == typeid(CFieldArray)) && (field->IsFixedSize() == false) ) )
  {
    SetItemBold(id, true);
    //SetItemFont(parentId, *wxSWISS_FONT);
    //SetItemFont(rootId, *wxITALIC_FONT);
  }

  // and now we also set the expanded one (only for the folders)
  if ( hasChildren )
  {
      SetItemImage(id, TreeCtrlIcon_FolderOpened,
                   wxTreeItemIcon_Expanded);
  }

  // remember the last child for OnEnsureVisible()
  if ( !hasChildren  )
  {
      m_lastItem = id;
  }

  wxTreeItemId returnId;

  if (hasChildren)
  {
    returnId = id;
  }
  else
  {
    returnId = parentId;
    CObjectTreeNode* parentNode = node->GetParent();
    while (parentNode != NULL)
    {
      if (parentNode->m_current == parentNode->GetChildren().end())
      {
        returnId = GetItemParent(returnId);
        parentNode = parentNode->GetParent();
      }
      else
      {
        break;
      }
    }
  }

  return returnId;

}
Esempio n. 8
0
void CRemoteTreeView::SetDirectoryListing(std::shared_ptr<CDirectoryListing> const& pListing, bool modified)
{
	m_busy = true;

	if (!pListing) {
		m_ExpandAfterList = wxTreeItemId();
		DeleteAllItems();
		AddRoot(_T(""));
		m_busy = false;
		if (FindFocus() == this) {
			wxNavigationKeyEvent *evt = new wxNavigationKeyEvent();
			evt->SetFromTab(true);
			evt->SetEventObject(this);
			evt->SetDirection(true);
			QueueEvent(evt);
		}
		Enable(false);
		m_contextMenuItem = wxTreeItemId();
		return;
	}
	Enable(true);
#ifdef __WXGTK__
	GetParent()->m_dirtyTabOrder = true;
#endif

	if (pListing->get_unsure_flags() && !(pListing->get_unsure_flags() & ~(CDirectoryListing::unsure_unknown | CDirectoryListing::unsure_file_mask))) {
		// Just files changed, does not affect directory tree
		m_busy = false;
		return;
	}

#ifndef __WXMSW__
	Freeze();
#endif
	wxTreeItemId parent = MakeParent(pListing->path, !modified);
	if (!parent)
	{
		m_busy = false;
#ifndef __WXMSW__
		Thaw();
#endif
		return;
	}

	if (!IsExpanded(parent) && parent != m_ExpandAfterList)
	{
		DeleteChildren(parent);
		CFilterManager filter;
		if (HasSubdirs(*pListing, filter))
			AppendItem(parent, _T(""), -1, -1);
	}
	else
	{
		RefreshItem(parent, *pListing, !modified);

		if (m_ExpandAfterList == parent)
		{
#ifndef __WXMSW__
			// Prevent CalculatePositions from being called
			wxGenericTreeItem *anchor = m_anchor;
			m_anchor = 0;
#endif
			Expand(parent);
#ifndef __WXMSW__
			m_anchor = anchor;
#endif
		}
	}
	m_ExpandAfterList = wxTreeItemId();

	SetItemImages(parent, false);

#ifndef __WXMSW__
	Thaw();
#endif
	if (!modified)
		SafeSelectItem(parent);
#ifndef __WXMSW__
	else
		Refresh();
#endif

	m_busy = false;
}
Esempio n. 9
0
wxTreeItemId CRemoteTreeView::MakeParent(CServerPath path, bool select)
{
	std::list<wxString> pieces;
	while (path.HasParent())
	{
		pieces.push_front(path.GetLastSegment());
		path = path.GetParent();
	}
	wxASSERT(!path.GetPath().empty());
	pieces.push_front(path.GetPath());

	const wxTreeItemId root = GetRootItem();
	wxTreeItemId parent = root;

	for (std::list<wxString>::const_iterator iter = pieces.begin(); iter != pieces.end(); ++iter)
	{
		if (iter != pieces.begin())
			path.AddSegment(*iter);

		wxTreeItemIdValue cookie;
		wxTreeItemId child = GetFirstChild(parent, cookie);
		if (child && GetItemText(child).empty())
		{
			Delete(child);
			child = wxTreeItemId();
			if (parent != root)
				ListExpand(parent);
		}
		for (child = GetFirstChild(parent, cookie); child; child = GetNextSibling(child))
		{
			const wxString& text = GetItemText(child);
			if (text == *iter)
				break;
		}
		if (!child)
		{
			CDirectoryListing listing;

			if (m_pState->m_pEngine->CacheLookup(path, listing) == FZ_REPLY_OK)
			{
				child = AppendItem(parent, *iter, 0, 2, path.HasParent() ? 0 : new CItemData(path));
				SetItemImages(child, false);
			}
			else
			{
				child = AppendItem(parent, *iter, 1, 3, path.HasParent() ? 0 : new CItemData(path));
				SetItemImages(child, true);
			}
			SortChildren(parent);

			std::list<wxString>::const_iterator nextIter = iter;
			++nextIter;
			if (nextIter != pieces.end())
				DisplayItem(child, listing);
		}
		if (select && iter != pieces.begin())
		{
#ifndef __WXMSW__
			// Prevent CalculatePositions from being called
			wxGenericTreeItem *anchor = m_anchor;
			m_anchor = 0;
#endif
			Expand(parent);
#ifndef __WXMSW__
			m_anchor = anchor;
#endif
		}

		parent = child;
	}

	return parent;
}
Esempio n. 10
0
void wxGenericDirCtrl::PopulateNode(wxTreeItemId parentId)
{
    wxDirItemData *data = GetItemData(parentId);

    if (data->m_isExpanded)
        return;

    data->m_isExpanded = true;

    if (parentId == m_treeCtrl->GetRootItem())
    {
        SetupSections();
        return;
    }

    wxASSERT(data);

    wxString search,path,filename;

    wxString dirName(data->m_path);

#if (defined(__WINDOWS__) && !defined(__WXWINCE__)) || defined(__DOS__) || defined(__OS2__)
    // Check if this is a root directory and if so,
    // whether the drive is avaiable.
    if (!wxIsDriveAvailable(dirName))
    {
        data->m_isExpanded = false;
        //wxMessageBox(wxT("Sorry, this drive is not available."));
        return;
    }
#endif

    // This may take a longish time. Go to busy cursor
    wxBusyCursor busy;

#if defined(__WINDOWS__) || defined(__DOS__) || defined(__OS2__)
    if (dirName.Last() == ':')
        dirName += wxString(wxFILE_SEP_PATH);
#endif

    wxArrayString dirs;
    wxArrayString filenames;

    wxDir d;
    wxString eachFilename;

    wxLogNull log;
    d.Open(dirName);

    if (d.IsOpened())
    {
        int style = wxDIR_DIRS;
        if (m_showHidden) style |= wxDIR_HIDDEN;
        if (d.GetFirst(& eachFilename, wxEmptyString, style))
        {
            do
            {
                if ((eachFilename != wxT(".")) && (eachFilename != wxT("..")))
                {
                    dirs.Add(eachFilename);
                }
            }
            while (d.GetNext(&eachFilename));
        }
    }
    dirs.Sort(wxDirCtrlStringCompareFunction);

    // Now do the filenames -- but only if we're allowed to
    if (!HasFlag(wxDIRCTRL_DIR_ONLY))
    {
        d.Open(dirName);

        if (d.IsOpened())
        {
            int style = wxDIR_FILES;
            if (m_showHidden) style |= wxDIR_HIDDEN;
            // Process each filter (ex: "JPEG Files (*.jpg;*.jpeg)|*.jpg;*.jpeg")
            wxStringTokenizer strTok;
            wxString curFilter;
            strTok.SetString(m_currentFilterStr,wxT(";"));
            while(strTok.HasMoreTokens())
            {
                curFilter = strTok.GetNextToken();
                if (d.GetFirst(& eachFilename, curFilter, style))
                {
                    do
                    {
                        if ((eachFilename != wxT(".")) && (eachFilename != wxT("..")))
                        {
                            filenames.Add(eachFilename);
                        }
                    }
                    while (d.GetNext(& eachFilename));
                }
            }
        }
        filenames.Sort(wxDirCtrlStringCompareFunction);
    }

    // Now we really know whether we have any children so tell the tree control
    // about it.
    m_treeCtrl->SetItemHasChildren(parentId, !dirs.empty() || !filenames.empty());

    // Add the sorted dirs
    size_t i;
    for (i = 0; i < dirs.GetCount(); i++)
    {
        eachFilename = dirs[i];
        path = dirName;
        if (!wxEndsWithPathSeparator(path))
            path += wxString(wxFILE_SEP_PATH);
        path += eachFilename;

        wxDirItemData *dir_item = new wxDirItemData(path,eachFilename,true);
        wxTreeItemId treeid = AppendItem( parentId, eachFilename,
                                      wxFileIconsTable::folder, -1, dir_item);
        m_treeCtrl->SetItemImage( treeid, wxFileIconsTable::folder_open,
                                  wxTreeItemIcon_Expanded );

        // assume that it does have children by default as it can take a long
        // time to really check for this (think remote drives...)
        //
        // and if we're wrong, we'll correct the icon later if
        // the user really tries to open this item
        m_treeCtrl->SetItemHasChildren(treeid);
    }

    // Add the sorted filenames
    if (!HasFlag(wxDIRCTRL_DIR_ONLY))
    {
        for (i = 0; i < filenames.GetCount(); i++)
        {
            eachFilename = filenames[i];
            path = dirName;
            if (!wxEndsWithPathSeparator(path))
                path += wxString(wxFILE_SEP_PATH);
            path += eachFilename;
            //path = dirName + wxString(wxT("/")) + eachFilename;
            wxDirItemData *dir_item = new wxDirItemData(path,eachFilename,false);
            int image_id = wxFileIconsTable::file;
            if (eachFilename.Find(wxT('.')) != wxNOT_FOUND)
                image_id = wxTheFileIconsTable->GetIconID(eachFilename.AfterLast(wxT('.')));
            (void) AppendItem( parentId, eachFilename, image_id, -1, dir_item);
        }
    }
}
void KeepControlPromises()
    
{ struct Constraint *cp;
  char rettype;
  void *retval;

CFD_MAXPROCESSES = 30;
MAXTRIES = 5;
CFD_INTERVAL = 0;
CHECKSUMUPDATES = true;
DENYBADCLOCKS = true;
CFRUNCOMMAND[0] = '\0';
CHECK_RFC931 = false;

/* Keep promised agent behaviour - control bodies */

Banner("Server control promises..");

HashControls();

/* Now expand */

for (cp = ControlBodyConstraints(cf_server); cp != NULL; cp=cp->next)
   {
   if (IsExcluded(cp->classes))
      {
      continue;
      }

   if (GetVariable("control_server",cp->lval,&retval,&rettype) == cf_notype)
      {
      CfOut(cf_error,"","Unknown lval %s in server control body",cp->lval);
      continue;
      }
   
   if (strcmp(cp->lval,CFS_CONTROLBODY[cfs_serverfacility].lval) == 0)
      {
      SetFacility(retval);
      continue;
      }
   
   if (strcmp(cp->lval,CFS_CONTROLBODY[cfs_denybadclocks].lval) == 0)
      {
      DENYBADCLOCKS = GetBoolean(retval);
      CfOut(cf_verbose,"","SET denybadclocks = %d\n",DENYBADCLOCKS);
      continue;
      }
   
   if (strcmp(cp->lval,CFS_CONTROLBODY[cfs_logencryptedtransfers].lval) == 0)
      {
      LOGENCRYPT = GetBoolean(retval);
      CfOut(cf_verbose,"","SET LOGENCRYPT = %d\n",LOGENCRYPT);
      continue;
      }
   
   if (strcmp(cp->lval,CFS_CONTROLBODY[cfs_logallconnections].lval) == 0)
      {
      LOGCONNS = GetBoolean(retval);
      CfOut(cf_verbose,"","SET LOGCONNS = %d\n",LOGCONNS);
      continue;
      }
   
   if (strcmp(cp->lval,CFS_CONTROLBODY[cfs_maxconnections].lval) == 0)
      {
      CFD_MAXPROCESSES = (int)Str2Int(retval);
      MAXTRIES = CFD_MAXPROCESSES / 3;
      CfOut(cf_verbose,"","SET maxconnections = %d\n",CFD_MAXPROCESSES);
      continue;
      }
   
   if (strcmp(cp->lval,CFS_CONTROLBODY[cfs_cfruncommand].lval) == 0)
      {
      strncpy(CFRUNCOMMAND,retval,CF_BUFSIZE-1);
      CfOut(cf_verbose,"","SET cfruncommand = %s\n",CFRUNCOMMAND);
      continue;
      }
   
   if (strcmp(cp->lval,CFS_CONTROLBODY[cfs_allowconnects].lval) == 0)
      {
      struct Rlist *rp;
      CfOut(cf_verbose,"","SET Allowing connections from ...\n");
      
      for (rp  = (struct Rlist *) retval; rp != NULL; rp = rp->next)
         {
         if (!IsItemIn(NONATTACKERLIST,rp->item))
            {
            AppendItem(&NONATTACKERLIST,rp->item,cp->classes);
            }
         }
      
      continue;
      }
   
   if (strcmp(cp->lval,CFS_CONTROLBODY[cfs_denyconnects].lval) == 0)
      {
      struct Rlist *rp;
      CfOut(cf_verbose,"","SET Denying connections from ...\n");
      
      for (rp  = (struct Rlist *) retval; rp != NULL; rp = rp->next)
         {
         if (!IsItemIn(ATTACKERLIST,rp->item))
            {
            AppendItem(&ATTACKERLIST,rp->item,cp->classes);
            }
         }
      
      continue;
      }
   
   if (strcmp(cp->lval,CFS_CONTROLBODY[cfs_skipverify].lval) == 0)
      {
      struct Rlist *rp;
      CfOut(cf_verbose,"","SET Skip verify connections from ...\n");
      
      for (rp  = (struct Rlist *) retval; rp != NULL; rp = rp->next)
         {
         if (!IsItemIn(SKIPVERIFY,rp->item))
            {
            AppendItem(&SKIPVERIFY,rp->item,cp->classes);
            }
         }
      
      continue;
      }
   
   if (strcmp(cp->lval,CFS_CONTROLBODY[cfs_dynamicaddresses].lval) == 0)
      {
      struct Rlist *rp;
      CfOut(cf_verbose,"","SET Dynamic addresses from ...\n");
      
      for (rp  = (struct Rlist *)retval; rp != NULL; rp = rp->next)
         {
         if (!IsItemIn(DHCPLIST,rp->item))
            {
            AppendItem(&DHCPLIST,rp->item,cp->classes);
            }
         }
      
      continue;
      }
   
   if (strcmp(cp->lval,CFS_CONTROLBODY[cfs_allowallconnects].lval) == 0)
      {
      struct Rlist *rp;
      CfOut(cf_verbose,"","SET Allowing multiple connections from ...\n");
      
      for (rp  = (struct Rlist *)retval; rp != NULL; rp = rp->next)
         {
         if (!IsItemIn(MULTICONNLIST,rp->item))
            {
            AppendItem(&MULTICONNLIST,rp->item,cp->classes);
            }
         }
      
      continue;
      }
   
   if (strcmp(cp->lval,CFS_CONTROLBODY[cfs_allowusers].lval) == 0)
      {
      struct Rlist *rp;
      CfOut(cf_verbose,"","SET Allowing users ...\n");
      
      for (rp  = (struct Rlist *)retval; rp != NULL; rp = rp->next)
         {
         if (!IsItemIn(ALLOWUSERLIST,rp->item))
            {
            AppendItem(&ALLOWUSERLIST,rp->item,cp->classes);
            }
         }
      
      continue;
      }
   
   if (strcmp(cp->lval,CFS_CONTROLBODY[cfs_trustkeysfrom].lval) == 0)
      {
      struct Rlist *rp;
      CfOut(cf_verbose,"","SET Trust keys from ...\n");
      
      for (rp  = (struct Rlist *)retval; rp != NULL; rp = rp->next)
         {
         if (!IsItemIn(TRUSTKEYLIST,rp->item))
            {
            AppendItem(&TRUSTKEYLIST,rp->item,cp->classes);
            }
         }
      
      continue;
      }

   if (strcmp(cp->lval,CFS_CONTROLBODY[cfs_portnumber].lval) == 0)
      {
      SHORT_CFENGINEPORT = (short)Str2Int(retval);
      strncpy(STR_CFENGINEPORT,retval,15);
      CfOut(cf_verbose,"","SET default portnumber = %u = %s = %s\n",(int)SHORT_CFENGINEPORT,STR_CFENGINEPORT,retval);
      SHORT_CFENGINEPORT = htons((short)Str2Int(retval));
      continue;
      }

   if (strcmp(cp->lval,CFS_CONTROLBODY[cfs_keyttl].lval) == 0)
      {
      KEYTTL = (short)Str2Int(retval);
      CfOut(cf_verbose,"","SET key TTL = %d\n",KEYTTL);
      continue;
      }

   if (strcmp(cp->lval,CFS_CONTROLBODY[cfs_bindtointerface].lval) == 0)
      {
      strncpy(BINDINTERFACE,retval,CF_BUFSIZE-1);
      CfOut(cf_verbose,"","SET bindtointerface = %s\n",BINDINTERFACE);
      continue;
      }
   }

if (GetVariable("control_common",CFG_CONTROLBODY[cfg_syslog_host].lval,&retval,&rettype) != cf_notype)
   {
   SYSLOGPORT = (unsigned short)Str2Int(retval);
   }

if (GetVariable("control_common",CFG_CONTROLBODY[cfg_syslog_port].lval,&retval,&rettype) != cf_notype)
   {
   strncpy(SYSLOGHOST,Hostname2IPString(retval),CF_MAXVARSIZE-1);
   }

if (GetVariable("control_common",CFG_CONTROLBODY[cfg_fips_mode].lval,&retval,&rettype) != cf_notype)
   {
   FIPS_MODE = GetBoolean(retval);
   CfOut(cf_verbose,"","SET FIPS_MODE = %d\n",FIPS_MODE);
   }
}
Esempio n. 12
0
static double SetClasses(char *name, double variable, double av_expect, double av_var, double localav_expect,
                         double localav_var, Item **classlist, char *timekey)
{
    char buffer[CF_BUFSIZE], buffer2[CF_BUFSIZE];
    double dev, delta, sigma, ldelta, lsigma, sig;

    delta = variable - av_expect;
    sigma = sqrt(av_var);
    ldelta = variable - localav_expect;
    lsigma = sqrt(localav_var);
    sig = sqrt(sigma * sigma + lsigma * lsigma);

    Log(LOG_LEVEL_DEBUG, "delta = %lf, sigma = %lf, lsigma = %lf, sig = %lf", delta, sigma, lsigma, sig);

    if ((sigma == 0.0) || (lsigma == 0.0))
    {
        Log(LOG_LEVEL_DEBUG, "No sigma variation .. can't measure class");

        snprintf(buffer, CF_MAXVARSIZE, "entropy_%s.*", name);
        MonEntropyPurgeUnused(buffer);

        return sig;
    }

    Log(LOG_LEVEL_DEBUG, "Setting classes for '%s'...", name);

    if (fabs(delta) < cf_noise_threshold)       /* Arbitrary limits on sensitivity  */
    {
        Log(LOG_LEVEL_DEBUG, "Sensitivity too high");

        buffer[0] = '\0';
        strcpy(buffer, name);

        if ((delta > 0) && (ldelta > 0))
        {
            strcat(buffer, "_high");
        }
        else if ((delta < 0) && (ldelta < 0))
        {
            strcat(buffer, "_low");
        }
        else
        {
            strcat(buffer, "_normal");
        }

        AppendItem(classlist, buffer, "0");

        dev = sqrt(delta * delta / (1.0 + sigma * sigma) + ldelta * ldelta / (1.0 + lsigma * lsigma));

        if (dev > 2.0 * sqrt(2.0))
        {
            strcpy(buffer2, buffer);
            strcat(buffer2, "_microanomaly");
            AppendItem(classlist, buffer2, "2");
            EvalContextHeapPersistentSave(buffer2, "measurements", CF_PERSISTENCE, CONTEXT_STATE_POLICY_PRESERVE);
        }

        return sig;             /* Granularity makes this silly */
    }
    else
    {
        buffer[0] = '\0';
        strcpy(buffer, name);

        if ((delta > 0) && (ldelta > 0))
        {
            strcat(buffer, "_high");
        }
        else if ((delta < 0) && (ldelta < 0))
        {
            strcat(buffer, "_low");
        }
        else
        {
            strcat(buffer, "_normal");
        }

        dev = sqrt(delta * delta / (1.0 + sigma * sigma) + ldelta * ldelta / (1.0 + lsigma * lsigma));

        if (dev <= sqrt(2.0))
        {
            strcpy(buffer2, buffer);
            strcat(buffer2, "_normal");
            AppendItem(classlist, buffer2, "0");
        }
        else
        {
            strcpy(buffer2, buffer);
            strcat(buffer2, "_dev1");
            AppendItem(classlist, buffer2, "0");
        }

        /* Now use persistent classes so that serious anomalies last for about
           2 autocorrelation lengths, so that they can be cross correlated and
           seen by normally scheduled cfagent processes ... */

        if (dev > 2.0 * sqrt(2.0))
        {
            strcpy(buffer2, buffer);
            strcat(buffer2, "_dev2");
            AppendItem(classlist, buffer2, "2");
            EvalContextHeapPersistentSave(buffer2, "measurements", CF_PERSISTENCE, CONTEXT_STATE_POLICY_PRESERVE);
        }

        if (dev > 3.0 * sqrt(2.0))
        {
            strcpy(buffer2, buffer);
            strcat(buffer2, "_anomaly");
            AppendItem(classlist, buffer2, "3");
            EvalContextHeapPersistentSave(buffer2, "measurements", CF_PERSISTENCE, CONTEXT_STATE_POLICY_PRESERVE);
        }

        return sig;
    }
}
Esempio n. 13
0
static void ArmClasses(Averages av, char *timekey)
{
    double sigma;
    Item *ip,*classlist = NULL;
    int i, j, k;
    char buff[CF_BUFSIZE], ldt_buff[CF_BUFSIZE], name[CF_MAXVARSIZE];
    static int anomaly[CF_OBSERVABLES][LDT_BUFSIZE];
    extern Item *ALL_INCOMING;
    extern Item *MON_UDP4, *MON_UDP6, *MON_TCP4, *MON_TCP6;

    for (i = 0; i < CF_OBSERVABLES; i++)
    {
        char desc[CF_BUFSIZE];

        GetObservable(i, name, desc);
        sigma = SetClasses(name, CF_THIS[i], av.Q[i].expect, av.Q[i].var, LOCALAV.Q[i].expect, LOCALAV.Q[i].var, &classlist, timekey);
        SetVariable(name, CF_THIS[i], av.Q[i].expect, sigma, &classlist);

        /* LDT */

        ldt_buff[0] = '\0';

        anomaly[i][LDT_POS] = false;

        if (!LDT_FULL)
        {
            anomaly[i][LDT_POS] = false;
        }

        if (LDT_FULL && (CHI[i] > CHI_LIMIT[i]))
        {
            anomaly[i][LDT_POS] = true; /* Remember the last anomaly value */

            Log(LOG_LEVEL_VERBOSE, "LDT(%d) in %s chi = %.2f thresh %.2f ", LDT_POS, name, CHI[i], CHI_LIMIT[i]);

            /* Last printed element is now */

            for (j = LDT_POS + 1, k = 0; k < LDT_BUFSIZE; j++, k++)
            {
                if (j == LDT_BUFSIZE)   /* Wrap */
                {
                    j = 0;
                }

                if (anomaly[i][j])
                {
                    snprintf(buff, CF_BUFSIZE, " *%.2f*", LDT_BUF[i][j]);
                }
                else
                {
                    snprintf(buff, CF_BUFSIZE, " %.2f", LDT_BUF[i][j]);
                }

                strcat(ldt_buff, buff);
            }

            if (CF_THIS[i] > av.Q[i].expect)
            {
                snprintf(buff, CF_BUFSIZE, "%s_high_ldt", name);
            }
            else
            {
                snprintf(buff, CF_BUFSIZE, "%s_high_ldt", name);
            }

            AppendItem(&classlist, buff, "2");
            EvalContextHeapPersistentSave(buff, "measurements", CF_PERSISTENCE, CONTEXT_STATE_POLICY_PRESERVE);
        }
        else
        {
            for (j = LDT_POS + 1, k = 0; k < LDT_BUFSIZE; j++, k++)
            {
                if (j == LDT_BUFSIZE)   /* Wrap */
                {
                    j = 0;
                }

                if (anomaly[i][j])
                {
                    snprintf(buff, CF_BUFSIZE, " *%.2f*", LDT_BUF[i][j]);
                }
                else
                {
                    snprintf(buff, CF_BUFSIZE, " %.2f", LDT_BUF[i][j]);
                }
                strcat(ldt_buff, buff);
            }
        }
    }

    SetMeasurementPromises(&classlist);

    // Report on the open ports, in various ways

    AddOpenPortsClasses("listening_ports", ALL_INCOMING, &classlist);
    AddOpenPortsClasses("listening_udp6_ports", MON_UDP6, &classlist);
    AddOpenPortsClasses("listening_udp4_ports", MON_UDP4, &classlist);
    AddOpenPortsClasses("listening_tcp6_ports", MON_TCP6, &classlist);
    AddOpenPortsClasses("listening_tcp4_ports", MON_TCP4, &classlist);

    // Port addresses

    if (ListLen(MON_TCP6) + ListLen(MON_TCP4) > 512)
    {
        Log(LOG_LEVEL_INFO, "Disabling address information of TCP ports in LISTEN state: more than 512 listening ports are detected");
    }
    else
    {
        for (ip = MON_TCP6; ip != NULL; ip=ip->next)
        {
            snprintf(buff,CF_BUFSIZE,"tcp6_port_addr[%s]=%s",ip->name,ip->classes);
            AppendItem(&classlist,buff,NULL);       
        }

        for (ip = MON_TCP4; ip != NULL; ip=ip->next)
        {
            snprintf(buff,CF_BUFSIZE,"tcp4_port_addr[%s]=%s",ip->name,ip->classes);
            AppendItem(&classlist,buff,NULL);       
        }
    }

    for (ip = MON_UDP6; ip != NULL; ip=ip->next)
    {
        snprintf(buff,CF_BUFSIZE,"udp6_port_addr[%s]=%s",ip->name,ip->classes);
        AppendItem(&classlist,buff,NULL);       
    }
    
    for (ip = MON_UDP4; ip != NULL; ip=ip->next)
    {
        snprintf(buff,CF_BUFSIZE,"udp4_port_addr[%s]=%s",ip->name,ip->classes);
        AppendItem(&classlist,buff,NULL);       
    }
    
    PublishEnvironment(classlist);

    DeleteItemList(classlist);
}
Esempio n. 14
0
void MonNetworkGatherData(double *cf_this)
{
FILE *pp;
char local[CF_BUFSIZE],remote[CF_BUFSIZE],comm[CF_BUFSIZE];
struct Item *in[ATTR],*out[ATTR];
char *sp;
int i;
char vbuff[CF_BUFSIZE];

Debug("GatherSocketData()\n");

for (i = 0; i < ATTR; i++)
   {
   in[i] = out[i] = NULL;
   }

if (ALL_INCOMING != NULL)
   {
   DeleteItemList(ALL_INCOMING);
   ALL_INCOMING = NULL;
   }

if (ALL_OUTGOING != NULL)
   {
   DeleteItemList(ALL_OUTGOING);
   ALL_OUTGOING = NULL;
   }

sscanf(VNETSTAT[VSYSTEMHARDCLASS],"%s",comm);

strcat(comm," -n");

if ((pp = cf_popen(comm,"r")) == NULL)
   {
   return;
   }

while (!feof(pp))
   {
   memset(local,0,CF_BUFSIZE);
   memset(remote,0,CF_BUFSIZE);

   CfReadLine(vbuff,CF_BUFSIZE,pp);

   if (strstr(vbuff,"UNIX"))
      {
      break;
      }

   if (!strstr(vbuff,"."))
      {
      continue;
      }

   /* Different formats here ... ugh.. */

   if (strncmp(vbuff,"tcp",3) == 0)
      {
      sscanf(vbuff,"%*s %*s %*s %s %s",local,remote); /* linux-like */
      }
   else
      {
      sscanf(vbuff,"%s %s",local,remote);             /* solaris-like */
      }

   if (strlen(local) == 0)
      {
      continue;
      }

   for (sp = local+strlen(local); (*sp != '.') && (sp > local); sp--)
      {
      }

   sp++;

   if ((strlen(sp) < 5) &&!IsItemIn(ALL_INCOMING,sp))
      {
      PrependItem(&ALL_INCOMING,sp,NULL);
      }

   for (sp = remote+strlen(remote); (sp >= remote) && !isdigit((int)*sp); sp--)
      {
      }

   sp++;

   if ((strlen(sp) < 5) && !IsItemIn(ALL_OUTGOING,sp))
      {
      PrependItem(&ALL_OUTGOING,sp,NULL);
      }

   for (i = 0; i < ATTR; i++)
      {
      char *spend;

      for (spend = local+strlen(local)-1; isdigit((int)*spend); spend--)
         {
         }

      spend++;

      if (strcmp(spend,ECGSOCKS[i].portnr) == 0)
         {
         cf_this[ECGSOCKS[i].in]++;
         AppendItem(&in[i],vbuff,"");
         }

      for (spend = remote+strlen(remote)-1; (sp >= remote) && isdigit((int)*spend); spend--)
         {
         }

      spend++;

      if (strcmp(spend,ECGSOCKS[i].portnr) == 0)
         {
         cf_this[ECGSOCKS[i].out]++;
         AppendItem(&out[i],vbuff,"");
         }
      }
   }

cf_pclose(pp);

/* Now save the state for ShowState() cf2 version alert function IFF
   the state is not smaller than the last or at least 40 minutes
   older. This mirrors the persistence of the maxima classes */


for (i = 0; i < ATTR; i++)
   {
   struct stat statbuf;
   time_t now = time(NULL);

   Debug("save incoming %s\n",ECGSOCKS[i].name);
   snprintf(vbuff,CF_MAXVARSIZE,"%s/state/cf_incoming.%s",CFWORKDIR,ECGSOCKS[i].name);
   if (cfstat(vbuff,&statbuf) != -1)
      {
      if ((ByteSizeList(in[i]) < statbuf.st_size) && (now < statbuf.st_mtime+40*60))
         {
         CfOut(cf_verbose,"","New state %s is smaller, retaining old for 40 mins longer\n",ECGSOCKS[i].name);
         DeleteItemList(in[i]);
         continue;
         }
      }

   SetNetworkEntropyClasses(ECGSOCKS[i].name,"in",in[i]);
   RawSaveItemList(in[i],vbuff);
   DeleteItemList(in[i]);
   Debug("Saved in netstat data in %s\n",vbuff);
   }

for (i = 0; i < ATTR; i++)
   {
   struct stat statbuf;
   time_t now = time(NULL);

   Debug("save outgoing %s\n",ECGSOCKS[i].name);
   snprintf(vbuff,CF_MAXVARSIZE,"%s/state/cf_outgoing.%s",CFWORKDIR,ECGSOCKS[i].name);

   if (cfstat(vbuff,&statbuf) != -1)
      {
      if ((ByteSizeList(out[i]) < statbuf.st_size) && (now < statbuf.st_mtime+40*60))
         {
         CfOut(cf_verbose,"","New state %s is smaller, retaining old for 40 mins longer\n",ECGSOCKS[i].name);
         DeleteItemList(out[i]);
         continue;
         }
      }

   SetNetworkEntropyClasses(ECGSOCKS[i].name,"out",out[i]);
   RawSaveItemList(out[i],vbuff);
   Debug("Saved out netstat data in %s\n",vbuff);
   DeleteItemList(out[i]);
   }
}