Пример #1
0
PGM_GNUC_INTERNAL
char*
pgm_if_indextoname (
	unsigned int		ifindex,
	char*			ifname
        )
{
#if !defined( _WIN32 )
/* Vista+ implements if_indextoname for IPv6 */
	return if_indextoname (ifindex, ifname);
#else
/* Windows maintains a few different numbers for each interface, the
 * number returned by GetIfEntry has shown to be the same as that 
 * determined by GetAdaptersAddresses and GetAdaptersInfo.
 */
	pgm_return_val_if_fail (NULL != ifname, NULL);

	MIB_IFROW ifRow = { .dwIndex = ifindex };
	const DWORD dwRetval = GetIfEntry (&ifRow);
	if (NO_ERROR != dwRetval)
		return NULL;
	strcpy (ifname, (char*)ifRow.wszName);
	return ifname;
#endif /* _WIN32 */
}
Пример #2
0
int
intf_get_src(intf_t *intf, struct intf_entry *entry, struct addr *src)
{
	MIB_IFROW ifrow;
	MIB_IPADDRROW *iprow;
	int i;

	if (src->addr_type != ADDR_TYPE_IP) {
		errno = EINVAL;
		return (-1);
	}
	if (_refresh_tables(intf) < 0)
		return (-1);
	
	for (i = 0; i < (int)intf->iptable->dwNumEntries; i++) {
		iprow = &intf->iptable->table[i];
		if (iprow->dwAddr == src->addr_ip) {
			ifrow.dwIndex = iprow->dwIndex;
			if (GetIfEntry(&ifrow) != NO_ERROR)
				return (-1);
			_ifrow_to_entry(intf, &ifrow, entry);
			return (0);
		}
	}
	errno = ENXIO;
	return (-1);
}
Пример #3
0
BOOL GetFirstMac(char * macStr)
{
   // Use IPHlpApi	
   BOOL bRet = FALSE;
   PIP_ADAPTER_INFO pAdapterInfo;
   PIP_ADAPTER_INFO pAdapter = NULL;
   PIP_ADAPTER_INFO pAdInfo = NULL;
   ULONG            ulSizeAdapterInfo = 0;  
   DWORD            dwStatus;  

   MIB_IFROW MibRow = {0};  
   if(NULL == macStr) return bRet;
   ulSizeAdapterInfo = sizeof(IP_ADAPTER_INFO); 
   pAdapterInfo = (PIP_ADAPTER_INFO)malloc(ulSizeAdapterInfo);


   if (GetAdaptersInfo( pAdapterInfo, &ulSizeAdapterInfo) != ERROR_SUCCESS) 
   {
      free (pAdapterInfo);
      pAdapterInfo = (PIP_ADAPTER_INFO)malloc(ulSizeAdapterInfo);
   }

   dwStatus = GetAdaptersInfo(pAdapterInfo,   &ulSizeAdapterInfo);  

   if(dwStatus != ERROR_SUCCESS)  
   {  
      free(pAdapterInfo);  
      return  bRet;  
   }  

   pAdInfo = pAdapterInfo; 
   while(pAdInfo)  
   {  	
      memset(&MibRow, 0, sizeof(MIB_IFROW));
      MibRow.dwIndex = pAdInfo->Index;  
      MibRow.dwType = pAdInfo->Type; 

      if(GetIfEntry(&MibRow) == NO_ERROR)  
      {  
         if (MibRow.dwOperStatus == MIB_IF_OPER_STATUS_OPERATIONAL)
         {

            sprintf(macStr, "%02X:%02X:%02X:%02X:%02X:%02X",
               MibRow.bPhysAddr[0],
               MibRow.bPhysAddr[1],
               MibRow.bPhysAddr[2],
               MibRow.bPhysAddr[3],
               MibRow.bPhysAddr[4],
               MibRow.bPhysAddr[5]);

            bRet = TRUE;
            break;
         }
      }
      pAdInfo = pAdInfo->Next; 
   }
   free(pAdapterInfo); 

   return bRet;
}
Пример #4
0
static void win32_log_interface_type(struct rtmp_stream *stream)
{
	RTMP *rtmp = &stream->rtmp;
	MIB_IPFORWARDROW route;
	uint32_t dest_addr, source_addr;
	char hostname[256];
	HOSTENT *h;

	if (rtmp->Link.hostname.av_len >= sizeof(hostname) - 1)
		return;

	strncpy(hostname, rtmp->Link.hostname.av_val, sizeof(hostname));
	hostname[rtmp->Link.hostname.av_len] = 0;

	h = gethostbyname(hostname);
	if (!h)
		return;

	dest_addr = *(uint32_t*)h->h_addr_list[0];

	if (rtmp->m_bindIP.addrLen == 0)
		source_addr = 0;
	else if (rtmp->m_bindIP.addr.ss_family = AF_INET)
		source_addr = (*(struct sockaddr_in*)&rtmp->m_bindIP)
			.sin_addr.S_un.S_addr;
	else
		return;

	if (!GetBestRoute(dest_addr, source_addr, &route)) {
		MIB_IFROW row;
		memset(&row, 0, sizeof(row));
		row.dwIndex = route.dwForwardIfIndex;

		if (!GetIfEntry(&row)) {
			uint32_t speed =row.dwSpeed / 1000000;
			char *type;
			struct dstr other = {0};

			if (row.dwType == IF_TYPE_ETHERNET_CSMACD) {
				type = "ethernet";
			} else if (row.dwType == IF_TYPE_IEEE80211) {
				type = "802.11";
			} else {
				dstr_printf(&other, "type %lu", row.dwType);
				type = other.array;
			}

			info("Interface: %s (%s, %lu mbps)", row.bDescr, type,
					speed);

			dstr_free(&other);
		}
	}
}
Пример #5
0
int scamper_if_getmtu(const int ifindex, uint16_t *ifmtu)
{
  MIB_IFROW row;
  row.dwIndex = ifindex;
  if(GetIfEntry(&row) != NO_ERROR)
    {
      printerror(errno,strerror,__func__, "could not GetIfEntry %d", ifindex);
      return -1;
    }
  *ifmtu = (uint16_t)row.dwMtu;
  return 0;
}
Пример #6
0
int scamper_if_getmac(const int ifindex, uint8_t *mac)
{
  MIB_IFROW row;
  row.dwIndex = ifindex;
  if(GetIfEntry(&row) != NO_ERROR)
    {
      printerror(errno,strerror,__func__, "could not GetIfEntry %d", ifindex);
      return -1;
    }
  memcpy(mac, row.bPhysAddr, 6);
  return 0;
}
Пример #7
0
/*
 * MS get mib row
 */
PMIB_IFROW getMibIfRow (int index) {

	PMIB_IFROW row = (PMIB_IFROW) malloc(sizeof(MIB_IFROW));

	row->dwIndex = index;

	// Get the require size of the structure
	if (row != NULL && GetIfEntry(row) == NO_ERROR) {
		return row;
	} else {
		return NULL;
	}
}
Пример #8
0
int scamper_if_getifname(char *str, size_t len, int ifindex)
{
  MIB_IFROW row;
  row.dwIndex = ifindex;
  if(GetIfEntry(&row) != NO_ERROR)
    {
      printerror(errno,strerror,__func__, "could not GetIfEntry %d", ifindex);
      return -1;
    }

  /* XXX: need to finish.  row.wszName is wide */
  _snprintf(str, len, "XXX");
  return -1;
}
Пример #9
0
static int  get_if_stats(const char *if_name, MIB_IFROW *pIfRow) {
    DWORD       dwSize, dwRetVal, i;
    int     ret = UGERR;
    /* variables used for GetIfTable and GetIfEntry */
    MIB_IFTABLE *pIfTable = NULL;
    MIB_IFROW   TmpIfRow;
    /* Allocate memory for our pointers. */
    dwSize = sizeof(MIB_IFTABLE);
    pIfTable = (MIB_IFTABLE *)zmalloc( dwSize);

    /* Before calling GetIfEntry, we call GetIfTable to make
       sure there are entries to get and retrieve the interface index.
       Make an initial call to GetIfTable to get the necessary size into dwSize */
    if (ERROR_INSUFFICIENT_BUFFER == GetIfTable(pIfTable, &dwSize, 0))
        pIfTable = (MIB_IFTABLE *)zrealloc(pIfTable, dwSize);

    /* Make a second call to GetIfTable to get the actual data we want. */
    if (NO_ERROR != (dwRetVal = GetIfTable(pIfTable, &dwSize, 0))) {
        LOG_DEBUG("GetIfTable failed with error: %s", xerrmsg());
        goto clean;
    }

    memset(pIfRow,0,sizeof(MIB_IFROW));
    for (i = 0; i < pIfTable->dwNumEntries; i++) {
        memset(&TmpIfRow,0,sizeof(MIB_IFROW));
        TmpIfRow.dwIndex = pIfTable->table[i].dwIndex;
        if (NO_ERROR != (dwRetVal = GetIfEntry(&TmpIfRow))) {
            LOG_DEBUG("GetIfEntry failed with error: %s",
                      xerrmsg());
            continue;
        }

        /* ignore loopback addr */
        if (0 == strcmp(if_name, TmpIfRow.bDescr))
            continue;
        pIfRow->dwInOctets+=TmpIfRow.dwInOctets;
        pIfRow->dwOutOctets+=TmpIfRow.dwOutOctets;
        pIfRow->dwInErrors+=TmpIfRow.dwInErrors;
        pIfRow->dwOutErrors+=TmpIfRow.dwOutErrors;
        pIfRow->dwInUcastPkts+=TmpIfRow.dwInUcastPkts;
        pIfRow->dwInNUcastPkts+=TmpIfRow.dwInNUcastPkts;
        pIfRow->dwOutUcastPkts+=TmpIfRow.dwOutUcastPkts;
        pIfRow->dwOutNUcastPkts+=TmpIfRow.dwOutNUcastPkts;
        ret = UGOK;
    }
clean:
    zfree(pIfTable);
    return ret;
}
Пример #10
0
int
intf_get(intf_t *intf, struct intf_entry *entry)
{
	MIB_IFROW ifrow;
	
	if (_refresh_tables(intf) < 0)
		return (-1);
	
	ifrow.dwIndex = _find_ifindex(intf, entry->intf_name);
	
	if (GetIfEntry(&ifrow) != NO_ERROR)
		return (-1);

	_ifrow_to_entry(intf, &ifrow, entry);
	
	return (0);
}
Пример #11
0
/* XXX - gross hack required by eth-win32:eth_open() */
const char *
intf_get_desc(intf_t *intf, const char *name)
{
	static char desc[MAXLEN_IFDESCR + 1];
	MIB_IFROW ifrow;
	
	if (_refresh_tables(intf) < 0)
		return (NULL);
	
	ifrow.dwIndex = _find_ifindex(intf, name);
	
	if (GetIfEntry(&ifrow) != NO_ERROR)
		return (NULL);

	
	return (desc);
}
Пример #12
0
void LogInterfaceType (RTMP *rtmp)
{
    MIB_IPFORWARDROW    route;
    DWORD               destAddr;
    CHAR                hostname[256];

    if (rtmp->Link.hostname.av_len >= sizeof(hostname)-1)
        return;

    strncpy (hostname, rtmp->Link.hostname.av_val, sizeof(hostname)-1);
    hostname[rtmp->Link.hostname.av_len] = 0;

    HOSTENT *h = gethostbyname(hostname);
    if (!h)
        return;

    destAddr = *(DWORD *)h->h_addr_list[0];

    if (!GetBestRoute (destAddr, rtmp->m_bindIP.addr.sin_addr.S_un.S_addr, &route))
    {
        MIB_IFROW row;
        zero (&row, sizeof(row));
        row.dwIndex = route.dwForwardIfIndex;

        if (!GetIfEntry (&row))
        {
            DWORD speed = row.dwSpeed / 1000000;
            TCHAR *type;
            String otherType;

            if (row.dwType == IF_TYPE_ETHERNET_CSMACD)
                type = TEXT("ethernet");
            else if (row.dwType == IF_TYPE_IEEE80211)
                type = TEXT("802.11");
            else
            {
                otherType = FormattedString (TEXT("type %d"), row.dwType);
                type = otherType.Array();
            }

            Log (TEXT("  Interface: %S (%s, %d mbps)"), row.bDescr, type, speed);
        }
    }
}
Пример #13
0
static MIB_IFROW QueryInterfaceRowXP(
    _Inout_ PPH_NETADAPTER_SYSINFO_CONTEXT Context
    )
{    
    MIB_IFROW interfaceRow;

    memset(&interfaceRow, 0, sizeof(MIB_IFROW));

    interfaceRow.dwIndex = Context->AdapterEntry->InterfaceIndex;

    GetIfEntry(&interfaceRow);

    //MIB_IPINTERFACE_ROW table;
    //memset(&table, 0, sizeof(MIB_IPINTERFACE_ROW));
    //table.Family = AF_INET;
    //table.InterfaceIndex = Context->AdapterEntry->InterfaceIndex;
    //GetIpInterfaceEntry(&table);

    return interfaceRow;
}
Пример #14
0
int
intf_get_dst(intf_t *intf, struct intf_entry *entry, struct addr *dst)
{
	MIB_IFROW ifrow;
	
	if (dst->addr_type != ADDR_TYPE_IP) {
		errno = EINVAL;
		return (-1);
	}
	if (GetBestInterface(dst->addr_ip, &ifrow.dwIndex) != NO_ERROR)
		return (-1);

	if (GetIfEntry(&ifrow) != NO_ERROR)
		return (-1);
	
	if (_refresh_tables(intf) < 0)
		return (-1);
	
	_ifrow_to_entry(intf, &ifrow, entry);
	
	return (0);
}
Пример #15
0
void GetNetworkInterfaces(CStringArray & interfaces, bool includeNames)
{
  // Get interfaces
  BYTE * buffer = NULL;
  ULONG size = 0;
  DWORD error = GetIpAddrTable(NULL, &size, FALSE);
  if (error == ERROR_INSUFFICIENT_BUFFER) {
    buffer = new BYTE[size];
    if (buffer != NULL)
      error = GetIpAddrTable((MIB_IPADDRTABLE *)buffer, &size, FALSE);
  }

  if (error == ERROR_SUCCESS) {
    const MIB_IPADDRTABLE * ipaddr = (const MIB_IPADDRTABLE *)buffer;
    for (unsigned i = 0; i < ipaddr->dwNumEntries; ++i) {
      in_addr ip;
      ip.S_un.S_addr = ipaddr->table[i].dwAddr;
      if (ntohl(ip.S_un.S_addr) != INADDR_LOOPBACK) {
        CStringA iface;
        if (ip.S_un.S_addr != INADDR_ANY)
          iface = inet_ntoa(ip);

        if (includeNames) {
          MIB_IFROW info;
          info.dwIndex = ipaddr->table[i].dwIndex;
          if (GetIfEntry(&info) == NO_ERROR && info.dwDescrLen > 0) {
            iface += '%';
            iface.Append((const char *)info.bDescr, info.dwDescrLen);
          }
        }

        if (!iface.IsEmpty())
          interfaces.Add(CString(iface));
      }
    }
  }
  delete [] buffer;
}
Пример #16
0
static int get_node_id(unsigned char *byMAC)
{
    DWORD               i, dwSize;
    PMIB_IPADDRTABLE    pAddr = NULL;
    MIB_IFROW           iInfo;
    PFIXED_INFO         pFI = NULL;

    /* Get all IP addresses held by this machine; if it's connected to a network, there's at least one
       that's not localhost */
    dwSize = 0;
    GetIpAddrTable(NULL, &dwSize, TRUE);
    pAddr = (PMIB_IPADDRTABLE)malloc(sizeof(BYTE) * dwSize);
    if (!GetIpAddrTable(pAddr, &dwSize, TRUE))
    {
        for (i = 0; i < pAddr->dwNumEntries; ++i)
        {
            if (IP_LOCALHOST != pAddr->table[i].dwAddr)
            {
                /* Not localhost, so get the interface */
                memset(&iInfo, 0, sizeof(MIB_IFROW));
                iInfo.dwIndex = pAddr->table[i].dwIndex;
                GetIfEntry(&iInfo);

                if (MIB_IF_TYPE_ETHERNET == iInfo.dwType)
                {
                    /*iInfo.bPhysAddr contains the MAC address of this interface*/
                    memcpy(byMAC, iInfo.bPhysAddr, iInfo.dwPhysAddrLen);
                    free(pAddr);
                    return 1;
                }
            }
        }
    }
    free(pAddr);
    return 0;
}
Пример #17
0
/*
 * Returns zero or more local interfaces to the requestor
 */
DWORD request_net_config_get_interfaces(Remote *remote, Packet *packet)
{
	Packet *response = packet_create_response(packet);
	DWORD result = ERROR_SUCCESS;
	DWORD entryCount;

#ifdef _WIN32
	Tlv entries[5];
	PMIB_IPADDRTABLE table = NULL;
	DWORD tableSize = sizeof(MIB_IPADDRROW) * 33;
	DWORD index;

	MIB_IFROW iface;

	do
	{
		// Allocate memory for reading addresses into
		if (!(table = (PMIB_IPADDRTABLE)malloc(tableSize)))
		{
			result = ERROR_NOT_ENOUGH_MEMORY;
			break;
		}

		// Get the IP address table
		if (GetIpAddrTable(table, &tableSize, TRUE) != NO_ERROR)
		{
			result = GetLastError();
			break;
		}

		// Enumerate the entries
		for (index = 0;
		     index < table->dwNumEntries;
		     index++)
		{
			entryCount = 0;

			entries[entryCount].header.length = sizeof(DWORD);
			entries[entryCount].header.type   = TLV_TYPE_IP;
			entries[entryCount].buffer        = (PUCHAR)&table->table[index].dwAddr;
			entryCount++;

			entries[entryCount].header.length = sizeof(DWORD);
			entries[entryCount].header.type   = TLV_TYPE_NETMASK;
			entries[entryCount].buffer        = (PUCHAR)&table->table[index].dwMask;
			entryCount++;

			iface.dwIndex = table->table[index].dwIndex;

			// If interface information can get gotten, use it.
			if (GetIfEntry(&iface) == NO_ERROR)
			{
				entries[entryCount].header.length = iface.dwPhysAddrLen;
				entries[entryCount].header.type   = TLV_TYPE_MAC_ADDR;
				entries[entryCount].buffer        = (PUCHAR)iface.bPhysAddr;
				entryCount++;

				if (iface.bDescr)
				{
					entries[entryCount].header.length = iface.dwDescrLen + 1;
					entries[entryCount].header.type   = TLV_TYPE_MAC_NAME;
					entries[entryCount].buffer        = (PUCHAR)iface.bDescr;
					entryCount++;
				}
			}

			// Add the interface group
			packet_add_tlv_group(response, TLV_TYPE_NETWORK_INTERFACE,
					entries, entryCount);
		}

	} while (0);

	if (table)
		free(table);

#else
	struct iface *ifaces;
	int count;
	int i;
	int if_error;
	Tlv entries[4];

	if_error = get_ifaces(&ifaces, &count);

	if (if_error) {
		result = if_error;
	} else {
		for (i = 0; i < count; i++) {

			entries[0].header.length = strlen(ifaces[i].name)+1;
			entries[0].header.type   = TLV_TYPE_MAC_NAME;
			entries[0].buffer        = (PUCHAR)ifaces[i].name;

			entries[1].header.length = 6;
			entries[1].header.type   = TLV_TYPE_MAC_ADDR;
			entries[1].buffer        = (PUCHAR)ifaces[i].hwaddr;

			entries[2].header.length = ifaces[i].addr_size;
			entries[2].header.type   = TLV_TYPE_IP;
			entries[2].buffer        = (PUCHAR)ifaces[i].addr;

			entries[3].header.length = ifaces[i].addr_size;
			entries[3].header.type   = TLV_TYPE_NETMASK;
			entries[3].buffer        = (PUCHAR)ifaces[i].netmask;
			
			packet_add_tlv_group(response, TLV_TYPE_NETWORK_INTERFACE, entries, 4);
		}
	}

	if (ifaces)
		free_ifaces(ifaces, count);
#endif

	// Transmit the response if valid
	packet_transmit_response(result, remote, response);

	return result;
}
Пример #18
0
VOID
UpdateLanStatus(HWND hwndDlg,  LANSTATUSUI_CONTEXT * pContext)
{
    MIB_IFROW IfEntry;
    HICON hIcon, hOldIcon = NULL;
    NOTIFYICONDATAW nid;
    NETCON_PROPERTIES * pProperties = NULL;

    ZeroMemory(&IfEntry, sizeof(IfEntry));
    IfEntry.dwIndex = pContext->dwAdapterIndex;
    if (GetIfEntry(&IfEntry) != NO_ERROR)
    {
        return;
    }

    hIcon = NULL;
    if (IfEntry.dwOperStatus == MIB_IF_OPER_STATUS_CONNECTED || IfEntry.dwOperStatus == MIB_IF_OPER_STATUS_OPERATIONAL)
    {
        if (pContext->dwInOctets == IfEntry.dwInOctets && pContext->dwOutOctets == IfEntry.dwOutOctets && pContext->Status  != 0)
        {
            hIcon = (HICON)LoadImage(netshell_hInstance, MAKEINTRESOURCE(IDI_NET_IDLE), IMAGE_ICON, 32, 32, LR_SHARED);
            pContext->Status = 0;
        }
        else if (pContext->dwInOctets != IfEntry.dwInOctets && pContext->dwOutOctets != IfEntry.dwOutOctets && pContext->Status  != 1)
        {
            hIcon = (HICON)LoadImage(netshell_hInstance, MAKEINTRESOURCE(IDI_NET_TRANSREC), IMAGE_ICON, 32, 32, LR_SHARED);
            pContext->Status = 1;
        }
        else if (pContext->dwInOctets != IfEntry.dwInOctets && pContext->Status  != 2)
        {
            hIcon = (HICON)LoadImage(netshell_hInstance, MAKEINTRESOURCE(IDI_NET_REC), IMAGE_ICON, 32, 32, LR_SHARED);
            pContext->Status = 2; 
        }
        else if (pContext->dwOutOctets != IfEntry.dwOutOctets && pContext->Status  != 3)
        {
            hIcon = (HICON)LoadImage(netshell_hInstance, MAKEINTRESOURCE(IDI_NET_TRANS), IMAGE_ICON, 32, 32, LR_SHARED);
            pContext->Status = 3;
        }
    }
    else if (IfEntry.dwOperStatus == MIB_IF_OPER_STATUS_UNREACHABLE || IfEntry.dwOperStatus == MIB_IF_OPER_STATUS_DISCONNECTED)
    {
        if (pContext->Status != 4)
        {
            hIcon = (HICON)LoadImage(netshell_hInstance, MAKEINTRESOURCE(IDI_NET_OFF), IMAGE_ICON, 32, 32, LR_SHARED);
            pContext->Status = 4;
        }
    }
    else if (IfEntry.dwOperStatus == MIB_IF_OPER_STATUS_NON_OPERATIONAL)
    {
        if (pContext->Status != 5)
        {
            hIcon = (HICON)LoadImage(netshell_hInstance, MAKEINTRESOURCE(IDI_NET_OFF), IMAGE_ICON, 32, 32, LR_SHARED);
            pContext->Status = 5;
        }
    }

    if (hwndDlg && hIcon)
    {
        hOldIcon = (HICON)SendDlgItemMessageW(hwndDlg, IDC_NETSTAT, STM_SETICON, (WPARAM)hIcon, 0);
        if (hOldIcon)
            DestroyIcon(hOldIcon);
    }

    ZeroMemory(&nid, sizeof(nid));
    nid.cbSize = sizeof(nid);
    nid.uID = pContext->uID;
    nid.hWnd = pContext->hwndStatusDlg;
    nid.uVersion = 3;

    if (pContext->pNet->GetProperties(&pProperties) == S_OK)
    {
        if (pProperties->dwCharacter & NCCF_SHOW_ICON)
        {
            if (hwndDlg)
                nid.hIcon = (HICON)CopyImage(hIcon, IMAGE_ICON, 16, 16, LR_COPYFROMRESOURCE);
            else
                nid.hIcon = hIcon;

            if (nid.hIcon)
                nid.uFlags |= NIF_ICON;

            nid.uFlags |= NIF_STATE;
            nid.dwState = 0;
            nid.dwStateMask = NIS_HIDDEN;

            if (pProperties->pszwName)
            {
                if (wcslen(pProperties->pszwName) * sizeof(WCHAR) < sizeof(nid.szTip))
                {
                    nid.uFlags |= NIF_TIP;
                    wcscpy(nid.szTip, pProperties->pszwName);
                }
                else
                {
                    CopyMemory(nid.szTip, pProperties->pszwName, sizeof(nid.szTip) - sizeof(WCHAR));
                    nid.szTip[(sizeof(nid.szTip)/sizeof(WCHAR))-1] = L'\0';
                    nid.uFlags |= NIF_TIP;
                }
            }
        }
        else
        {
            nid.uFlags |= NIF_STATE;
            nid.dwState = NIS_HIDDEN;
            nid.dwStateMask = NIS_HIDDEN;

        }
        NcFreeNetconProperties(pProperties);
    }

    Shell_NotifyIconW(NIM_MODIFY, &nid);

    if (nid.uFlags & NIF_ICON)
        DestroyIcon(nid.hIcon);

    pContext->dwInOctets = IfEntry.dwInOctets;
    pContext->dwOutOctets = IfEntry.dwOutOctets;

    if (hwndDlg)
        UpdateLanStatusUiDlg(hwndDlg, &IfEntry, pContext);
}
Пример #19
0
int	NET_IF_LIST(const char *cmd, const char *param, unsigned flags, AGENT_RESULT *result)
{
	DWORD		dwSize, dwRetVal, i, j;
	char		*buf = NULL;
	size_t		buf_alloc = 512, buf_offset = 0;
	int		ret = SYSINFO_RET_FAIL;
	/* variables used for GetIfTable and GetIfEntry */
	MIB_IFTABLE	*pIfTable = NULL;
	MIB_IFROW	pIfRow;
	/* variables used for GetIpAddrTable */
	MIB_IPADDRTABLE	*pIPAddrTable = NULL;
	IN_ADDR		in_addr;

	/* Allocate memory for our pointers. */
	dwSize = sizeof(MIB_IPADDRTABLE);
	pIPAddrTable = (MIB_IPADDRTABLE *)zbx_malloc(pIPAddrTable, sizeof(MIB_IPADDRTABLE));

	/* Make an initial call to GetIpAddrTable to get the
	   necessary size into the dwSize variable */
	if (ERROR_INSUFFICIENT_BUFFER == GetIpAddrTable(pIPAddrTable, &dwSize, 0))
		pIPAddrTable = (MIB_IPADDRTABLE *)zbx_realloc(pIPAddrTable, dwSize);

	/* Make a second call to GetIpAddrTable to get the
	   actual data we want */
	if (NO_ERROR != (dwRetVal = GetIpAddrTable(pIPAddrTable, &dwSize, 0)))
	{
		zabbix_log(LOG_LEVEL_DEBUG, "GetIpAddrTable failed with error: %s", strerror_from_system(dwRetVal));
		goto clean;
	}

	/* Allocate memory for our pointers. */
	dwSize = sizeof(MIB_IFTABLE);
	pIfTable = (MIB_IFTABLE *)zbx_malloc(pIfTable, dwSize);

	/* Before calling GetIfEntry, we call GetIfTable to make
	   sure there are entries to get and retrieve the interface index.
	   Make an initial call to GetIfTable to get the necessary size into dwSize */
	if (ERROR_INSUFFICIENT_BUFFER == GetIfTable(pIfTable, &dwSize, 0))
		pIfTable = (MIB_IFTABLE *)zbx_realloc(pIfTable, dwSize);

	/* Make a second call to GetIfTable to get the actual data we want. */
	if (NO_ERROR != (dwRetVal = GetIfTable(pIfTable, &dwSize, 0)))
	{
		zabbix_log(LOG_LEVEL_DEBUG, "GetIfTable failed with error: %s", strerror_from_system(dwRetVal));
		goto clean;
	}

	buf = (char *)zbx_malloc(buf, sizeof(char) * buf_alloc);

	if (pIfTable->dwNumEntries > 0)
	{
		for (i = 0; i < (int)pIfTable->dwNumEntries; i++)
		{
			LPTSTR	wdescr;
			LPSTR	utf8_descr;

			pIfRow.dwIndex = pIfTable->table[i].dwIndex;
			if (NO_ERROR != (dwRetVal = GetIfEntry(&pIfRow)))
			{
				zabbix_log(LOG_LEVEL_DEBUG, "GetIfEntry failed with error: %s",
						strerror_from_system(dwRetVal));
				continue;
			}

			zbx_snprintf_alloc(&buf, &buf_alloc, &buf_offset,
					"%-25s", get_if_type_string(pIfRow.dwType));

			zbx_snprintf_alloc(&buf, &buf_alloc, &buf_offset,
					" %-8s", get_if_adminstatus_string(pIfRow.dwAdminStatus));

			for (j = 0; j < pIPAddrTable->dwNumEntries; j++)
				if (pIPAddrTable->table[j].dwIndex == pIfRow.dwIndex)
				{
					in_addr.S_un.S_addr = pIPAddrTable->table[j].dwAddr;
					zbx_snprintf_alloc(&buf, &buf_alloc, &buf_offset,
							" %-15s", inet_ntoa(in_addr));
					break;
				}

			if (j == pIPAddrTable->dwNumEntries)
				zbx_strcpy_alloc(&buf, &buf_alloc, &buf_offset, " -");

			wdescr = zbx_acp_to_unicode(pIfRow.bDescr);
			utf8_descr = zbx_unicode_to_utf8(wdescr);
			zbx_snprintf_alloc(&buf, &buf_alloc, &buf_offset, " %s\n", utf8_descr);
			zbx_free(utf8_descr);
			zbx_free(wdescr);
		}
	}

	SET_TEXT_RESULT(result, buf);

	ret = SYSINFO_RET_OK;
clean:
	zbx_free(pIfTable);
	zbx_free(pIPAddrTable);

	return ret;
}
Пример #20
0
/*
 * returns interface statistics by IP address or interface name
 */
static int	get_if_stats(const char *if_name, MIB_IFROW *pIfRow)
{
	DWORD		dwSize, dwRetVal, i, j;
	int		ret = FAIL;
	char		ip[16];
	/* variables used for GetIfTable and GetIfEntry */
	MIB_IFTABLE	*pIfTable = NULL;
	/* variables used for GetIpAddrTable */
	MIB_IPADDRTABLE	*pIPAddrTable = NULL;
	IN_ADDR		in_addr;

	/* Allocate memory for our pointers. */
	dwSize = sizeof(MIB_IPADDRTABLE);
	pIPAddrTable = (MIB_IPADDRTABLE *)zbx_malloc(pIPAddrTable, sizeof(MIB_IPADDRTABLE));

	/* Make an initial call to GetIpAddrTable to get the
	   necessary size into the dwSize variable */
	if (ERROR_INSUFFICIENT_BUFFER == GetIpAddrTable(pIPAddrTable, &dwSize, 0))
		pIPAddrTable = (MIB_IPADDRTABLE *)zbx_realloc(pIPAddrTable, dwSize);

	/* Make a second call to GetIpAddrTable to get the
	   actual data we want */
	if (NO_ERROR != (dwRetVal = GetIpAddrTable(pIPAddrTable, &dwSize, 0)))
	{
		zabbix_log(LOG_LEVEL_DEBUG, "GetIpAddrTable failed with error: %s", strerror_from_system(dwRetVal));
		goto clean;
	}

	/* Allocate memory for our pointers. */
	dwSize = sizeof(MIB_IFTABLE);
	pIfTable = (MIB_IFTABLE *)zbx_malloc(pIfTable, dwSize);

	/* Before calling GetIfEntry, we call GetIfTable to make
	   sure there are entries to get and retrieve the interface index.
	   Make an initial call to GetIfTable to get the necessary size into dwSize */
	if (ERROR_INSUFFICIENT_BUFFER == GetIfTable(pIfTable, &dwSize, 0))
		pIfTable = (MIB_IFTABLE *)zbx_realloc(pIfTable, dwSize);

	/* Make a second call to GetIfTable to get the actual data we want. */
	if (NO_ERROR != (dwRetVal = GetIfTable(pIfTable, &dwSize, 0)))
	{
		zabbix_log(LOG_LEVEL_DEBUG, "GetIfTable failed with error: %s", strerror_from_system(dwRetVal));
		goto clean;
	}

	for (i = 0; i < pIfTable->dwNumEntries; i++)
	{
		LPTSTR	wdescr;
		LPSTR	utf8_descr;

		pIfRow->dwIndex = pIfTable->table[i].dwIndex;
		if (NO_ERROR != (dwRetVal = GetIfEntry(pIfRow)))
		{
			zabbix_log(LOG_LEVEL_DEBUG, "GetIfEntry failed with error: %s",
					strerror_from_system(dwRetVal));
			continue;
		}

		wdescr = zbx_acp_to_unicode(pIfRow->bDescr);
		utf8_descr = zbx_unicode_to_utf8(wdescr);
		if (0 == strcmp(if_name, utf8_descr))
			ret = SUCCEED;
		zbx_free(utf8_descr);
		zbx_free(wdescr);

		if (SUCCEED == ret)
			break;

		for (j = 0; j < pIPAddrTable->dwNumEntries; j++)
		{
			if (pIPAddrTable->table[j].dwIndex == pIfRow->dwIndex)
			{
				in_addr.S_un.S_addr = pIPAddrTable->table[j].dwAddr;
				zbx_snprintf(ip, sizeof(ip), "%s", inet_ntoa(in_addr));
				if (0 == strcmp(if_name, ip))
				{
					ret = SUCCEED;
					break;
				}
			}
		}

		if (SUCCEED == ret)
			break;
	}
clean:
	zbx_free(pIfTable);
	zbx_free(pIPAddrTable);

	return ret;
}
Пример #21
0
int	NET_IF_DISCOVERY(const char *cmd, const char *param, unsigned flags, AGENT_RESULT *result)
{
	DWORD		dwSize, dwRetVal, i;
	int		ret = SYSINFO_RET_FAIL;
	/* variables used for GetIfTable and GetIfEntry */
	MIB_IFTABLE	*pIfTable = NULL;
	MIB_IFROW	pIfRow;
	struct zbx_json	j;
	LPTSTR		wdescr;
	LPSTR		utf8_descr;

	zbx_json_init(&j, ZBX_JSON_STAT_BUF_LEN);

	zbx_json_addarray(&j, ZBX_PROTO_TAG_DATA);

	/* Allocate memory for our pointers. */
	dwSize = sizeof(MIB_IFTABLE);
	pIfTable = (MIB_IFTABLE *)zbx_malloc(pIfTable, dwSize);

	/* Before calling GetIfEntry, we call GetIfTable to make
	   sure there are entries to get and retrieve the interface index.
	   Make an initial call to GetIfTable to get the necessary size into dwSize */
	if (ERROR_INSUFFICIENT_BUFFER == GetIfTable(pIfTable, &dwSize, 0))
		pIfTable = (MIB_IFTABLE *)zbx_realloc(pIfTable, dwSize);

	/* Make a second call to GetIfTable to get the actual data we want. */
	if (NO_ERROR != (dwRetVal = GetIfTable(pIfTable, &dwSize, 0)))
	{
		zabbix_log(LOG_LEVEL_DEBUG, "GetIfTable failed with error: %s", strerror_from_system(dwRetVal));
		goto clean;
	}

	for (i = 0; i < pIfTable->dwNumEntries; i++)
	{
		pIfRow.dwIndex = pIfTable->table[i].dwIndex;
		if (NO_ERROR != (dwRetVal = GetIfEntry(&pIfRow)))
		{
			zabbix_log(LOG_LEVEL_DEBUG, "GetIfEntry failed with error: %s", strerror_from_system(dwRetVal));
			continue;
		}

		zbx_json_addobject(&j, NULL);

		wdescr = zbx_acp_to_unicode(pIfRow.bDescr);
		utf8_descr = zbx_unicode_to_utf8(wdescr);
		zbx_json_addstring(&j, "{#IFNAME}", utf8_descr, ZBX_JSON_TYPE_STRING);
		zbx_free(utf8_descr);
		zbx_free(wdescr);

		zbx_json_close(&j);
	}

	zbx_json_close(&j);

	SET_STR_RESULT(result, strdup(j.buffer));

	zbx_json_free(&j);

	ret = SYSINFO_RET_OK;
clean:
	zbx_free(pIfTable);

	return ret;
}
Пример #22
0
DWORD get_interfaces_windows_mib(Remote *remote, Packet *response)
{
	DWORD result = ERROR_SUCCESS;
	DWORD tlv_cnt;

	Tlv entries[6];
	PMIB_IPADDRTABLE table = NULL;
	DWORD tableSize = sizeof(MIB_IPADDRROW) * 33;
	DWORD index;
	DWORD mtu_bigendian;
	DWORD interface_index_bigendian;
	MIB_IFROW iface;

	do
	{
		// Allocate memory for reading addresses into
		if (!(table = (PMIB_IPADDRTABLE)malloc(tableSize)))
		{
			result = ERROR_NOT_ENOUGH_MEMORY;
			break;
		}

		// Get the IP address table
		if (GetIpAddrTable(table, &tableSize, TRUE) != NO_ERROR)
		{
			result = GetLastError();
			break;
		}

		// Enumerate the entries
		for (index = 0; index < table->dwNumEntries; index++)
		{
			tlv_cnt = 0;

			interface_index_bigendian = htonl(table->table[index].dwIndex);
			entries[tlv_cnt].header.length = sizeof(DWORD);
			entries[tlv_cnt].header.type = TLV_TYPE_INTERFACE_INDEX;
			entries[tlv_cnt].buffer = (PUCHAR)&interface_index_bigendian;
			tlv_cnt++;

			entries[tlv_cnt].header.length = sizeof(DWORD);
			entries[tlv_cnt].header.type = TLV_TYPE_IP;
			entries[tlv_cnt].buffer = (PUCHAR)&table->table[index].dwAddr;
			tlv_cnt++;

			entries[tlv_cnt].header.length = sizeof(DWORD);
			entries[tlv_cnt].header.type = TLV_TYPE_NETMASK;
			entries[tlv_cnt].buffer = (PUCHAR)&table->table[index].dwMask;
			tlv_cnt++;

			iface.dwIndex = table->table[index].dwIndex;

			// If interface information can get gotten, use it.
			if (GetIfEntry(&iface) == NO_ERROR)
			{
				entries[tlv_cnt].header.length = iface.dwPhysAddrLen;
				entries[tlv_cnt].header.type = TLV_TYPE_MAC_ADDR;
				entries[tlv_cnt].buffer = (PUCHAR)iface.bPhysAddr;
				tlv_cnt++;

				mtu_bigendian = htonl(iface.dwMtu);
				entries[tlv_cnt].header.length = sizeof(DWORD);
				entries[tlv_cnt].header.type = TLV_TYPE_INTERFACE_MTU;
				entries[tlv_cnt].buffer = (PUCHAR)&mtu_bigendian;
				tlv_cnt++;

				if (iface.bDescr)
				{
					entries[tlv_cnt].header.length = iface.dwDescrLen + 1;
					entries[tlv_cnt].header.type = TLV_TYPE_MAC_NAME;
					entries[tlv_cnt].buffer = (PUCHAR)iface.bDescr;
					tlv_cnt++;
				}
			}

			// Add the interface group
			packet_add_tlv_group(response, TLV_TYPE_NETWORK_INTERFACE,
			entries, tlv_cnt);
		}

	} while (0);

	if (table)
		free(table);

	return result;
}
Пример #23
0
bool NetworkObserver::ppl_dns_get_local_fqdn (char **servername, char **serverip,char **netmask, unsigned int WIN32_interface)
{
	unsigned int pos;

	*servername = NULL; /* no name on win32? */
	*serverip   = NULL;
	*netmask    = NULL;

	/* First, try to get the interface where we should listen */
	{
		DWORD size_of_iptable = 0;
		PMIB_IPADDRTABLE ipt;
		PMIB_IFROW ifrow;

		if (GetIpAddrTable(NULL, &size_of_iptable, TRUE) == ERROR_INSUFFICIENT_BUFFER)
		{
			ifrow = (PMIB_IFROW) _alloca (sizeof(MIB_IFROW));
			ipt = (PMIB_IPADDRTABLE) _alloca (size_of_iptable);
			if (ifrow==NULL || ipt==NULL)
			{
				/* not very usefull to continue */
				return true;
			}

			if (!GetIpAddrTable(ipt, &size_of_iptable, TRUE))
			{
				/* look for the best public interface */

				for (pos=0; pos < ipt->dwNumEntries && *netmask==NULL ; ++pos)
				{
					/* index is */
					struct in_addr addr;
					struct in_addr mask;
					ifrow->dwIndex = ipt->table[pos].dwIndex;
					if (GetIfEntry(ifrow) == NO_ERROR)
					{
						switch(ifrow->dwType)
						{
						case MIB_IF_TYPE_LOOPBACK:
						  /*	break; */
						case MIB_IF_TYPE_ETHERNET:
						default:
							addr.s_addr = ipt->table[pos].dwAddr;
							mask.s_addr = ipt->table[pos].dwMask;
							if (ipt->table[pos].dwIndex == WIN32_interface)
							{
								*servername = NULL; /* no name on win32? */
								*serverip   = inet_ntoa(addr);
								*netmask    = inet_ntoa(mask);
								break;
							}
						}
					}
				}
			}
		}
	}

	if (*serverip==NULL || *netmask==NULL)
	{
		return false;
	}

	return true;
}
Пример #24
0
bool CNetWatcher::GetNewStatus ()
{
	//log.WriteFormat (_T("[CNetWatcher] GetNewStatus begins"), PEL_INFO);

    int newlistsize = 0;
    NetworkList * newlist = 0;

    if (m_getAdaptersAddresses)
    {
        // IPv6-supporting version (XP, Vista+)

        #define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x)) 
        #define FREE(x) HeapFree(GetProcessHeap(), 0, (x))

        PIP_ADAPTER_ADDRESSES AdapterAddresses = NULL;
        ULONG OutBufferLength = 0;
        ULONG RetVal = 0, i;    

        for (i = 0; i < 5; i++) 
        {
            RetVal = SafeGetAdaptersAddresses(m_getAdaptersAddresses, AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX, NULL, AdapterAddresses, &OutBufferLength);
            
            if (RetVal != ERROR_BUFFER_OVERFLOW) 
                break;

            if (AdapterAddresses != NULL) { FREE(AdapterAddresses); }
            
            AdapterAddresses = (PIP_ADAPTER_ADDRESSES) MALLOC(OutBufferLength);
            if (AdapterAddresses == NULL)
            {
                RetVal = GetLastError();
                break;
            }
        }
        
        if (RetVal == NO_ERROR) 
        {
            int entries = 0;
            for (PIP_ADAPTER_ADDRESSES Adapter1 = AdapterAddresses; Adapter1; Adapter1 = Adapter1->Next)
            {
                entries++;
            }

            newlistsize = sizeof(CKAHFW::Network)*entries + sizeof(int);

            newlist = (NetworkList *) new unsigned char [ newlistsize ];
            memset(newlist, 0, newlistsize);

            int entry = 0;
            PIP_ADAPTER_ADDRESSES Adapter = AdapterAddresses;

            while (Adapter) 
            {
                newlist->list[entry].HasIPv4 = FALSE;
                newlist->list[entry].HasIPv6 = FALSE;

                memset(newlist->list[entry].AdapterName, 0, CKAHFW::ADAPTERNAMELEN);
                strncpy(newlist->list[entry].AdapterName, __LPSTR(Adapter->FriendlyName), CKAHFW::ADAPTERNAMELEN);
                newlist->list[entry].AdapterName[CKAHFW::ADAPTERNAMELEN - 1] = 0;

                memset(newlist->list[entry].AdapterDesc, 0, CKAHFW::ADAPTERDESCLEN);
                strncpy(newlist->list[entry].AdapterDesc, __LPSTR(Adapter->Description), CKAHFW::ADAPTERDESCLEN);
                newlist->list[entry].AdapterDesc[CKAHFW::ADAPTERDESCLEN - 1] = 0;

                memset(newlist->list[entry].Phys, 0, CKAHFW::PHYSLEN);
                memcpy(newlist->list[entry].Phys, Adapter->PhysicalAddress, min(Adapter->PhysicalAddressLength, CKAHFW::PHYSLEN));

                memcpy(newlist->list[entry].Zones, Adapter->ZoneIndices, sizeof(Adapter->ZoneIndices));

                bool  HasIPv4 = false;
                DWORD IPv4 = 0;
                DWORD Maskv4 = 0;

                bool  HasIPv6 = false;
                CKAHUM::IPv6 IPv6;   IPv6.SetZero();
                CKAHUM::IPv6 Maskv6; Maskv6.SetZero();

                IP_ADAPTER_UNICAST_ADDRESS* UnicastAddress = Adapter->FirstUnicastAddress;
                while (UnicastAddress)
                {
                    if (UnicastAddress->Address.lpSockaddr->sa_family == AF_INET)
                    {
                        if (!HasIPv4)
                        {
                            DWORD ipv4 = ntohl(((sockaddr_in*)UnicastAddress->Address.lpSockaddr)->sin_addr.S_un.S_addr);

                            DWORD maxmaskv4 = CKAHUM::IPv4Mask(32);
                            DWORD maxlength = 32;

                            IP_ADAPTER_PREFIX* Prefix = Adapter->FirstPrefix;
                            while (Prefix)
                            {
                                if (Prefix->Address.lpSockaddr->sa_family == AF_INET &&
                                    Prefix->PrefixLength > 0 &&
                                    Prefix->PrefixLength < maxlength)
                                {
                                    DWORD netv4 = ntohl(((sockaddr_in*)Prefix->Address.lpSockaddr)->sin_addr.S_un.S_addr);
                                    DWORD maskv4 = CKAHUM::IPv4Mask( Prefix->PrefixLength );
                                    if ((netv4 & maskv4) == (ipv4 & maskv4))
                                    {
                                        maxmaskv4 = maskv4;
                                        maxlength = Prefix->PrefixLength;
                                    }
                                }

                                Prefix = Prefix->Next;
                            }
                            HasIPv4 = TRUE;
                            IPv4 = ipv4;
                            Maskv4 = maxmaskv4;
                        }
                    }
                    else if (UnicastAddress->Address.lpSockaddr->sa_family == AF_INET6 )
                    {
                        if (!IPv6.IsValid())
                        {
                            CKAHUM::IPv6 ipv6;
                            ipv6.Set( ((CKAHUM::OWord*)((sockaddr_in6*)UnicastAddress->Address.lpSockaddr)->sin6_addr.u.Byte)->ntoh(),
                                      ((sockaddr_in6*)UnicastAddress->Address.lpSockaddr)->sin6_scope_id);

                            CKAHUM::IPv6::Scope scope = ipv6.GetScope();

                            if (ipv6.GetScope() == CKAHUM::IPv6::ScopeGlobal)
                            {
                                CKAHUM::IPv6 maxmaskv6; 

                                maxmaskv6.SetMask(128, 0);
                                DWORD maxlength = 128;

                                IP_ADAPTER_PREFIX* Prefix = Adapter->FirstPrefix;
                                while (Prefix)
                                {
                                    if (Prefix->Address.lpSockaddr->sa_family == AF_INET6 &&
                                        Prefix->PrefixLength > 0 &&
                                        Prefix->PrefixLength < maxlength)
                                    {
                                        CKAHUM::IPv6 netv6;
                                        CKAHUM::IPv6 maskv6;

                                        netv6.Set( ((CKAHUM::OWord*)((sockaddr_in6*)Prefix->Address.lpSockaddr)->sin6_addr.u.Byte)->ntoh(),
                                                   ((sockaddr_in6*)Prefix->Address.lpSockaddr)->sin6_scope_id );
                                        maskv6.SetMask(Prefix->PrefixLength, 0);

                                        if ((netv6 & maskv6) == (ipv6 & maskv6))
                                        {
                                            maxmaskv6= maskv6;
                                            maxlength = Prefix->PrefixLength;
                                        }
                                    }

                                    Prefix = Prefix->Next;
                                }
                                IPv6 = ipv6;
                                Maskv6 = maxmaskv6;
                            }
                        }

                        if (!HasIPv6)
                        {
                            HasIPv6 = TRUE;
                        }
                    }

                    UnicastAddress = UnicastAddress->Next;
                }

                newlist->list[entry].HasIPv4 = HasIPv4;
                newlist->list[entry].IPv4    = IPv4;
                newlist->list[entry].Maskv4  = Maskv4;
                newlist->list[entry].HasIPv6 = HasIPv6;
                newlist->list[entry].IPv6    = IPv6;
                newlist->list[entry].Maskv6  = Maskv6;

                Adapter = Adapter->Next;
                entry++;
            }
            newlist->size = entry;
        }

        if (AdapterAddresses != NULL) 
        {
            FREE(AdapterAddresses);
        }
    }
    else
    {
        // pre-IPv6 version (2K-)

        DWORD size = 0;

        DWORD err = ::GetIpAddrTable(0, &size, FALSE);

        BYTE * ipaddrbuffer = new BYTE[size];
        if (! ipaddrbuffer)
        {
	        //log.WriteFormat (_T("[CNetWatcher] GetNewStatus failed - no memory"), PEL_INFO);
            return false;
        }

        PMIB_IPADDRTABLE table = (PMIB_IPADDRTABLE) ipaddrbuffer;
        
        table->dwNumEntries = 0;

        err = ::GetIpAddrTable(table, &size, FALSE);
        if (err != NO_ERROR)
        {
            delete [] ipaddrbuffer;
	        //log.WriteFormat (_T("[CNetWatcher] GetNewStatus failed - GetIpAddrTable returned error"), PEL_INFO);
            return false;
        }

        int entries = 0;

	    DWORD i;
        for (i = 0; i < table->dwNumEntries; ++i)
        {
            if (table->table[i].dwAddr != 0) entries ++;
        }

        newlistsize = sizeof(CKAHFW::Network)*entries + sizeof(int);

        newlist = (NetworkList *) new unsigned char [ newlistsize ];
        memset(newlist, 0, newlistsize);

        newlist->size = entries;

        int entry = 0;
        for (i = 0; i < table->dwNumEntries && entry < entries; ++i)
        {
            if (table->table[i].dwAddr != 0)
            {
                newlist->list[entry].HasIPv4 = TRUE;
                newlist->list[entry].IPv4    = ntohl(table->table[i].dwAddr);
                newlist->list[entry].Maskv4  = ntohl(table->table[i].dwMask);
                newlist->list[entry].HasIPv6 = FALSE;

                int ifacenum = table->table[i].dwIndex;

                newlist->list[entry].PhysLength = 0;
                memset(newlist->list[entry].Phys, 0, CKAHFW::PHYSLEN);

                memset(newlist->list[entry].AdapterName, 0, CKAHFW::ADAPTERNAMELEN);
                memset(newlist->list[entry].AdapterDesc, 0, CKAHFW::ADAPTERDESCLEN);

                strcpy(newlist->list[entry].AdapterDesc, "Unknown");

                MIB_IFROW ifrow;
                memset(&ifrow, 0, sizeof(ifrow));

                ifrow.dwIndex = table->table[i].dwIndex;

                if (GetIfEntry(&ifrow) == NO_ERROR)
                {
                    memcpy(newlist->list[entry].Phys, ifrow.bPhysAddr, min(ifrow.dwPhysAddrLen, CKAHFW::PHYSLEN));

                    strncpy(newlist->list[entry].AdapterDesc, (char*)ifrow.bDescr, CKAHFW::ADAPTERDESCLEN);
                    newlist->list[entry].AdapterDesc[CKAHFW::ADAPTERDESCLEN - 1] = 0;
                }

                entry++;
            }
        }

        delete [] ipaddrbuffer;
    }

    if ( newlistsize && newlist &&
         newlistsize != m_listsize || 
         memcmp(m_list, newlist, newlistsize ) !=0 )
    {
        delete [] (unsigned char *) m_list;

        m_list     = newlist;
        m_listsize = newlistsize;

        //log.WriteFormat (_T("[CNetWatcher] GetNewStatus succeeded, list changed"), PEL_INFO);
        return true;
    }
    else
    {
        delete [] (unsigned char *) newlist;

        //log.WriteFormat (_T("[CNetWatcher] GetNewStatus succeeded, list not changed"), PEL_INFO);
        return false;
    }
}
Пример #25
0
int
ppl_dns_get_local_fqdn (char **servername, char **serverip,
			char **netmask, unsigned int WIN32_interface)
{
	unsigned int pos;

	*servername = NULL; /* no name on win32? */
	*serverip   = NULL;
	*netmask    = NULL;

	/* First, try to get the interface where we should listen */
	{
		DWORD size_of_iptable = 0;
		PMIB_IPADDRTABLE ipt;
		PMIB_IFROW ifrow;

		if (GetIpAddrTable(NULL, &size_of_iptable, TRUE) == ERROR_INSUFFICIENT_BUFFER)
		{
			ifrow = (PMIB_IFROW) _alloca (sizeof(MIB_IFROW));
			ipt = (PMIB_IPADDRTABLE) _alloca (size_of_iptable);
			if (ifrow==NULL || ipt==NULL)
			{
				/* not very usefull to continue */
				OSIP_TRACE (osip_trace (__FILE__, __LINE__, OSIP_INFO4, NULL,
					"ERROR alloca failed\r\n"));
				return -1;
			}

			if (!GetIpAddrTable(ipt, &size_of_iptable, TRUE))
			{
				/* look for the best public interface */

				for (pos=0; pos < ipt->dwNumEntries && *netmask==NULL ; ++pos)
				{
					/* index is */
					struct in_addr addr;
					struct in_addr mask;
					ifrow->dwIndex = ipt->table[pos].dwIndex;
					if (GetIfEntry(ifrow) == NO_ERROR)
					{
						switch(ifrow->dwType)
						{
						case MIB_IF_TYPE_LOOPBACK:
						  /*	break; */
						case MIB_IF_TYPE_ETHERNET:
						default:
							addr.s_addr = ipt->table[pos].dwAddr;
							mask.s_addr = ipt->table[pos].dwMask;
							if (ipt->table[pos].dwIndex == WIN32_interface)
							{
								*servername = NULL; /* no name on win32? */
								*serverip   = osip_strdup(inet_ntoa(addr));
								*netmask    = osip_strdup(inet_ntoa(mask));
								OSIP_TRACE (osip_trace (__FILE__, __LINE__, OSIP_INFO4, NULL,
									"Interface ethernet: %s/%s\r\n", *serverip, *netmask));
								break;
							}
						}
					}
				}
			}
		}
	}

	if (*serverip==NULL || *netmask==NULL)
	{
		OSIP_TRACE (osip_trace (__FILE__, __LINE__, OSIP_WARNING, NULL,
			"ERROR No network interface found\r\n"));
		return -1;
	}

	return 0;
}
Пример #26
0
/* jShadow: black magic!  here we merge IP Helper with WinPCAP - we go through all 
 * IP addresses via IP Helper and check if some of them matches one of the addresses
 * of WinPCAP adapter address list. if a match is found we get MAC via IP Helper
 */
bool TWinPCAP::GetAdapterMAC(int adapter, unsigned char * mac)
{
   bool ok = false;

   /* Preparation: PCAP */
   pcap_if_t * d = GetAdapter(adapter);
   if (!d) return false;

   /* Preparation: IPHlpAPI */
   PMIB_IPADDRTABLE mib_ip_table = NULL;
   ULONG mib_ip_table_size = 0;
   
   /* walk through adapters via IPHelper API*/
   GetIpAddrTable(mib_ip_table, &mib_ip_table_size, FALSE);
   if (mib_ip_table_size != 0)
   {
      mib_ip_table = (PMIB_IPADDRTABLE) new unsigned char[mib_ip_table_size];
      if (mib_ip_table)
      {
         if (GetIpAddrTable(mib_ip_table, &mib_ip_table_size, FALSE) == NO_ERROR)
         {
            for (unsigned int i = 0; i < mib_ip_table->dwNumEntries && !ok; i++)
            {

               /* walk through adapter addresses */
               for (pcap_addr_t * addr = d->addresses; addr && !ok; addr = addr->next)
               {
                  /* we are interested only in AF_INET (IPv4) 'cause ARP is defined in IPv4 stack */
                  if (addr->addr->sa_family == AF_INET && ((struct sockaddr_in *)addr->addr)->sin_addr.S_un.S_addr == mib_ip_table->table[i].dwAddr)
                  {
                     /* gotcha - fetch HW address! */

                     MIB_IFROW mib_if_entry;

                     mib_if_entry.dwIndex = mib_ip_table->table[i].dwIndex;
                     if (GetIfEntry(&mib_if_entry) == NO_ERROR)
                     {
                        ok = true;
                        memcpy(mac, mib_if_entry.bPhysAddr, 6);
                     } /* if */
                  } /* if */
               } /* for on winpcap adapter list */

            } /* for each of IP address matches */
         } /* if GetIpAddrTable */

         /* cleanup */
         delete [] mib_ip_table;
      }
   }

   /* hack: we fill mac address with FF-s if we failed to find it. this
    * workaround is needed to avoid 3 more lines of code in send_packet -
    * if we failed to figure out mac address, we'll send from broadcast 
    * address (we'll most likely get a responce in that case). To speed 
    * up send_packet code we move invariant MAC workaroud here.
    */

   if (!ok)
   {
      memset(mac, 0xff, 6);
   }

   return ok;
}
Пример #27
0
DWORD WINAPI WsControl(DWORD protocol,
                       DWORD action,
                       LPVOID pRequestInfo,
                       LPDWORD pcbRequestInfoLen,
                       LPVOID pResponseInfo,
                       LPDWORD pcbResponseInfoLen)
{

   /* Get the command structure into a pointer we can use,
      rather than void */
   TDIObjectID *pcommand = pRequestInfo;

   /* validate input parameters.  Error codes are from winerror.h, not from
    * winsock.h.  pcbResponseInfoLen is apparently allowed to be NULL for some
    * commands, since winipcfg.exe fails if we ensure it's non-NULL in every
    * case.
    */
   if (protocol != IPPROTO_TCP) return ERROR_INVALID_PARAMETER;
   if (!pcommand) return ERROR_INVALID_PARAMETER;
   if (!pcbRequestInfoLen) return ERROR_INVALID_ACCESS;
   if (*pcbRequestInfoLen < sizeof(TDIObjectID)) return ERROR_INVALID_ACCESS;
   if (!pResponseInfo) return ERROR_INVALID_PARAMETER;
   if (pcommand->toi_type != INFO_TYPE_PROVIDER) return ERROR_INVALID_PARAMETER;

   TRACE ("   WsControl TOI_ID=>0x%lx<, {TEI_ENTITY=0x%lx, TEI_INSTANCE=0x%lx}, TOI_CLASS=0x%lx, TOI_TYPE=0x%lx\n",
      pcommand->toi_id, pcommand->toi_entity.tei_entity,
      pcommand->toi_entity.tei_instance,
      pcommand->toi_class, pcommand->toi_type );

   switch (action)
   {
   case WSCNTL_TCPIP_QUERY_INFO:
   {
      if (pcommand->toi_class != INFO_CLASS_GENERIC &&
       pcommand->toi_class != INFO_CLASS_PROTOCOL)
      {
         ERR("Unexpected class %ld for WSCNTL_TCPIP_QUERY_INFO\n",
          pcommand->toi_class);
         return ERROR_BAD_ENVIRONMENT;
      }

      switch (pcommand->toi_id)
      {
         /* ENTITY_LIST_ID gets the list of "entity IDs", where an entity
            may represent an interface, or a datagram service, or address
            translation, or other fun things.  Typically an entity ID represents
            a class of service, which is further queried for what type it is.
            Different types will then have more specific queries defined.
         */
         case ENTITY_LIST_ID:
         {
            TDIEntityID *baseptr = pResponseInfo;
            DWORD numInt, i, ifTable, spaceNeeded;
            PMIB_IFTABLE table;

            if (!pcbResponseInfoLen)
               return ERROR_BAD_ENVIRONMENT;
            if (pcommand->toi_class != INFO_CLASS_GENERIC)
            {
               FIXME ("Unexpected Option for ENTITY_LIST_ID request -> toi_class=0x%lx\n",
                    pcommand->toi_class);
               return (ERROR_BAD_ENVIRONMENT);
            }

            GetNumberOfInterfaces(&numInt);
            spaceNeeded = sizeof(TDIEntityID) * (numInt * 2 + 3);

            if (*pcbResponseInfoLen < spaceNeeded)
               return (ERROR_LOCK_VIOLATION);

            ifTable = 0;
            GetIfTable(NULL, &ifTable, FALSE);
            table = HeapAlloc( GetProcessHeap(), 0, ifTable );
            if (!table)
               return ERROR_NOT_ENOUGH_MEMORY;
            GetIfTable(table, &ifTable, FALSE);

            spaceNeeded = sizeof(TDIEntityID) * (table->dwNumEntries + 4);
            if (*pcbResponseInfoLen < spaceNeeded)
            {
               HeapFree( GetProcessHeap(), 0, table );
               return ERROR_LOCK_VIOLATION;
            }

            memset(baseptr, 0, spaceNeeded);

            for (i = 0; i < table->dwNumEntries; i++)
            {
               /* Return IF_GENERIC and CL_NL_ENTITY on every interface, and
                * AT_ENTITY, CL_TL_ENTITY, and CO_TL_ENTITY on the first
                * interface.  MS returns them only on the loopback interface,
                * but it doesn't seem to matter.
                */
               if (i == 0)
               {
                  baseptr->tei_entity = CO_TL_ENTITY;
                  baseptr->tei_instance = table->table[i].dwIndex;
                  baseptr++;
                  baseptr->tei_entity = CL_TL_ENTITY;
                  baseptr->tei_instance = table->table[i].dwIndex;
                  baseptr++;
                  baseptr->tei_entity = AT_ENTITY;
                  baseptr->tei_instance = table->table[i].dwIndex;
                  baseptr++;
               }
               baseptr->tei_entity = CL_NL_ENTITY;
               baseptr->tei_instance = table->table[i].dwIndex;
               baseptr++;
               baseptr->tei_entity = IF_GENERIC;
               baseptr->tei_instance = table->table[i].dwIndex;
               baseptr++;
            }

            *pcbResponseInfoLen = spaceNeeded;
            HeapFree( GetProcessHeap(), 0, table );
            break;
         }

         /* Returns MIB-II statistics for an interface */
         case ENTITY_TYPE_ID:
            switch (pcommand->toi_entity.tei_entity)
            {
            case IF_GENERIC:
               if (pcommand->toi_class == INFO_CLASS_GENERIC)
               {
                  if (!pcbResponseInfoLen)
                     return ERROR_BAD_ENVIRONMENT;
                  *((ULONG *)pResponseInfo) = IF_MIB;
                  *pcbResponseInfoLen = sizeof(ULONG);
               }
               else if (pcommand->toi_class == INFO_CLASS_PROTOCOL)
               {
                  MIB_IFROW row;
                  DWORD index = pcommand->toi_entity.tei_instance, ret;
                  DWORD size = sizeof(row) - sizeof(row.wszName) -
                   sizeof(row.bDescr);

                  if (!pcbResponseInfoLen)
                     return ERROR_BAD_ENVIRONMENT;
                  if (*pcbResponseInfoLen < size)
                     return (ERROR_LOCK_VIOLATION);
                  row.dwIndex = index;
                  ret = GetIfEntry(&row);
                  if (ret != NO_ERROR)
                  {
                     /* FIXME: Win98's arp.exe insists on querying index 1 for
                      * its MIB-II stats, regardless of the tei_instances
                      * returned in the ENTITY_LIST query above.  If the query
                      * fails, arp.exe fails.  So, I do this hack return value
                      * if index is 1 and the query failed just to get arp.exe
                      * to continue.
                      */
                     if (index == 1)
                        return NO_ERROR;
                     ERR ("Error retrieving data for interface index %u\n",
                      index);
                     return ret;
                  }
                  size = sizeof(row) - sizeof(row.wszName) -
                   sizeof(row.bDescr) + row.dwDescrLen;
                  if (*pcbResponseInfoLen < size)
                     return (ERROR_LOCK_VIOLATION);
                  memcpy(pResponseInfo, &row.dwIndex, size);
                  *pcbResponseInfoLen = size;
               }
               break;

            /* Returns address-translation related data.  In our case, this is
             * ARP.
             */
            case AT_ENTITY:
               if (pcommand->toi_class == INFO_CLASS_GENERIC)
               {
                  if (!pcbResponseInfoLen)
                     return ERROR_BAD_ENVIRONMENT;
                  *((ULONG *)pResponseInfo) = AT_ARP;
                  *pcbResponseInfoLen = sizeof(ULONG);
               }
               else if (pcommand->toi_class == INFO_CLASS_PROTOCOL)
               {
                  PMIB_IPNETTABLE table;
                  DWORD size;
                  PULONG output = pResponseInfo;

                  if (!pcbResponseInfoLen)
                     return ERROR_BAD_ENVIRONMENT;
                  if (*pcbResponseInfoLen < sizeof(ULONG) * 2)
                     return (ERROR_LOCK_VIOLATION);
                  GetIpNetTable(NULL, &size, FALSE);
                  table = HeapAlloc( GetProcessHeap(), 0, size );
                  if (!table)
                     return ERROR_NOT_ENOUGH_MEMORY;
                  GetIpNetTable(table, &size, FALSE);
                  /* FIXME: I don't understand the meaning of the ARP output
                   * very well, but it seems to indicate how many ARP entries
                   * exist.  I don't know whether this should reflect the
                   * number per interface, as I'm only testing with a single
                   * interface.  So, I lie and say all ARP entries exist on
                   * a single interface--the first one that appears in the
                   * ARP table.
                   */
                  *(output++) = table->dwNumEntries;
                  *output = table->table[0].dwIndex;
                  HeapFree( GetProcessHeap(), 0, table );
                  *pcbResponseInfoLen = sizeof(ULONG) * 2;
               }
               break;

            /* Returns connectionless network layer statistics--in our case,
             * this is IP.
             */
            case CL_NL_ENTITY:
               if (pcommand->toi_class == INFO_CLASS_GENERIC)
               {
                  if (!pcbResponseInfoLen)
                     return ERROR_BAD_ENVIRONMENT;
                  *((ULONG *)pResponseInfo) = CL_NL_IP;
                  *pcbResponseInfoLen = sizeof(ULONG);
               }
               else if (pcommand->toi_class == INFO_CLASS_PROTOCOL)
               {
                  if (!pcbResponseInfoLen)
                     return ERROR_BAD_ENVIRONMENT;
                  if (*pcbResponseInfoLen < sizeof(MIB_IPSTATS))
                     return ERROR_LOCK_VIOLATION;
                  GetIpStatistics(pResponseInfo);

                  *pcbResponseInfoLen = sizeof(MIB_IPSTATS);
               }
               break;

            /* Returns connectionless transport layer statistics--in our case,
             * this is UDP.
             */
            case CL_TL_ENTITY:
               if (pcommand->toi_class == INFO_CLASS_GENERIC)
               {
                  if (!pcbResponseInfoLen)
                     return ERROR_BAD_ENVIRONMENT;
                  *((ULONG *)pResponseInfo) = CL_TL_UDP;
                  *pcbResponseInfoLen = sizeof(ULONG);
               }
               else if (pcommand->toi_class == INFO_CLASS_PROTOCOL)
               {
                  if (!pcbResponseInfoLen)
                     return ERROR_BAD_ENVIRONMENT;
                  if (*pcbResponseInfoLen < sizeof(MIB_UDPSTATS))
                     return ERROR_LOCK_VIOLATION;
                  GetUdpStatistics(pResponseInfo);
                  *pcbResponseInfoLen = sizeof(MIB_UDPSTATS);
               }
               break;

            /* Returns connection-oriented transport layer statistics--in our
             * case, this is TCP.
             */
            case CO_TL_ENTITY:
               if (pcommand->toi_class == INFO_CLASS_GENERIC)
               {
                  if (!pcbResponseInfoLen)
                     return ERROR_BAD_ENVIRONMENT;
                  *((ULONG *)pResponseInfo) = CO_TL_TCP;
                  *pcbResponseInfoLen = sizeof(ULONG);
               }
               else if (pcommand->toi_class == INFO_CLASS_PROTOCOL)
               {
                  if (!pcbResponseInfoLen)
                     return ERROR_BAD_ENVIRONMENT;
                  if (*pcbResponseInfoLen < sizeof(MIB_TCPSTATS))
                     return ERROR_LOCK_VIOLATION;
                  GetTcpStatistics(pResponseInfo);
                  *pcbResponseInfoLen = sizeof(MIB_TCPSTATS);
               }
               break;

            default:
               ERR("Unknown entity %ld for ENTITY_TYPE_ID query\n",
                pcommand->toi_entity.tei_entity);
         }
         break;

         /* This call returns the IP address, subnet mask, and broadcast
          * address for an interface.  If there are multiple IP addresses for
          * the interface with the given index, returns the "first" one.
          */
         case IP_MIB_ADDRTABLE_ENTRY_ID:
         {
            DWORD index = pcommand->toi_entity.tei_instance;
            PMIB_IPADDRROW baseIPInfo = pResponseInfo;
            PMIB_IPADDRTABLE table;
            DWORD tableSize, i;

            if (!pcbResponseInfoLen)
               return ERROR_BAD_ENVIRONMENT;
            if (*pcbResponseInfoLen < sizeof(MIB_IPADDRROW))
               return (ERROR_LOCK_VIOLATION);

            /* get entire table, because there isn't an exported function that
               gets just one entry. */
            tableSize = 0;
            GetIpAddrTable(NULL, &tableSize, FALSE);
            table = HeapAlloc( GetProcessHeap(), 0, tableSize );
            if (!table)
               return ERROR_NOT_ENOUGH_MEMORY;
            GetIpAddrTable(table, &tableSize, FALSE);
            for (i = 0; i < table->dwNumEntries; i++)
            {
               if (table->table[i].dwIndex == index)
               {
                  TRACE("Found IP info for tei_instance 0x%x:\n", index);
                  TRACE("IP 0x%08x, mask 0x%08x\n", table->table[i].dwAddr,
                   table->table[i].dwMask);
                  *baseIPInfo = table->table[i];
                  break;
               }
            }
            HeapFree( GetProcessHeap(), 0, table );

            *pcbResponseInfoLen = sizeof(MIB_IPADDRROW);
            break;
         }

         case IP_MIB_TABLE_ENTRY_ID:
         {
            switch (pcommand->toi_entity.tei_entity)
            {
            /* This call returns the routing table.
             * No official documentation found, even the name of the command is unknown.
             * Work is based on
             * http://www.cyberport.com/~tangent/programming/winsock/articles/wscontrol.html
             * and testings done with winipcfg.exe, route.exe and ipconfig.exe.
             * pcommand->toi_entity.tei_instance seems to be the interface number
             * but route.exe outputs only the information for the last interface
             * if only the routes for the pcommand->toi_entity.tei_instance
             * interface are returned. */
               case CL_NL_ENTITY:
               {
                  DWORD routeTableSize, numRoutes, ndx, ret;
                  PMIB_IPFORWARDTABLE table;
                  IPRouteEntry *winRouteTable  = pResponseInfo;

                  if (!pcbResponseInfoLen)
                     return ERROR_BAD_ENVIRONMENT;
                  ret = GetIpForwardTable(NULL, &routeTableSize, FALSE);
                  if (ret != ERROR_INSUFFICIENT_BUFFER)
                      return ret;
                  numRoutes = (routeTableSize - sizeof(MIB_IPFORWARDTABLE))
                   / sizeof(MIB_IPFORWARDROW) + 1;
                  if (*pcbResponseInfoLen < sizeof(IPRouteEntry) * numRoutes)
                     return (ERROR_LOCK_VIOLATION);
                  table = HeapAlloc( GetProcessHeap(), 0, routeTableSize );
                  if (!table)
                     return ERROR_NOT_ENOUGH_MEMORY;
                  ret = GetIpForwardTable(table, &routeTableSize, FALSE);
                  if (ret != NO_ERROR) {
                     HeapFree( GetProcessHeap(), 0, table );
                     return ret;
                  }

                  memset(pResponseInfo, 0, sizeof(IPRouteEntry) * numRoutes);
                  for (ndx = 0; ndx < table->dwNumEntries; ndx++)
                  {
                     winRouteTable->ire_addr = table->table[ndx].dwForwardDest;
                     winRouteTable->ire_index =
                      table->table[ndx].dwForwardIfIndex;
                     winRouteTable->ire_metric =
                      table->table[ndx].dwForwardMetric1;
                     /* winRouteTable->ire_option4 =
                     winRouteTable->ire_option5 =
                     winRouteTable->ire_option6 = */
                     winRouteTable->ire_gw = table->table[ndx].dwForwardNextHop;
                     /* winRouteTable->ire_option8 =
                     winRouteTable->ire_option9 =
                     winRouteTable->ire_option10 = */
                     winRouteTable->ire_mask = table->table[ndx].dwForwardMask;
                     /* winRouteTable->ire_option12 = */
                     winRouteTable++;
                  }

                  /* calculate the length of the data in the output buffer */
                  *pcbResponseInfoLen = sizeof(IPRouteEntry) *
                   table->dwNumEntries;

                  HeapFree( GetProcessHeap(), 0, table );
               }
               break;

               case AT_ARP:
               {
                  DWORD arpTableSize, numEntries, ret;
                  PMIB_IPNETTABLE table;

                  if (!pcbResponseInfoLen)
                     return ERROR_BAD_ENVIRONMENT;
                  ret = GetIpNetTable(NULL, &arpTableSize, FALSE);
                  if (ret != ERROR_INSUFFICIENT_BUFFER)
                      return ret;
                  numEntries = (arpTableSize - sizeof(MIB_IPNETTABLE))
                   / sizeof(MIB_IPNETROW) + 1;
                  if (*pcbResponseInfoLen < sizeof(MIB_IPNETROW) * numEntries)
                     return (ERROR_LOCK_VIOLATION);
                  table = HeapAlloc( GetProcessHeap(), 0, arpTableSize );
                  if (!table)
                     return ERROR_NOT_ENOUGH_MEMORY;
                  ret = GetIpNetTable(table, &arpTableSize, FALSE);
                  if (ret != NO_ERROR) {
                     HeapFree( GetProcessHeap(), 0, table );
                     return ret;
                  }
                  if (*pcbResponseInfoLen < sizeof(MIB_IPNETROW) *
                   table->dwNumEntries)
                  {
                     HeapFree( GetProcessHeap(), 0, table );
                     return ERROR_LOCK_VIOLATION;
                  }
                  memcpy(pResponseInfo, table->table, sizeof(MIB_IPNETROW) *
                   table->dwNumEntries);

                  /* calculate the length of the data in the output buffer */
                  *pcbResponseInfoLen = sizeof(MIB_IPNETROW) *
                   table->dwNumEntries;

                  HeapFree( GetProcessHeap(), 0, table );
               }
               break;

               case CO_TL_ENTITY:
               {
                  DWORD tcpTableSize, numEntries, ret;
                  PMIB_TCPTABLE table;
                  DWORD i;

                  if (!pcbResponseInfoLen)
                     return ERROR_BAD_ENVIRONMENT;
                  ret = GetTcpTable(NULL, &tcpTableSize, FALSE);
                  if (ret != ERROR_INSUFFICIENT_BUFFER)
                      return ret;
                  numEntries = (tcpTableSize - sizeof(MIB_TCPTABLE))
                   / sizeof(MIB_TCPROW) + 1;
                  if (*pcbResponseInfoLen < sizeof(MIB_TCPROW) * numEntries)
                     return (ERROR_LOCK_VIOLATION);
                  table = HeapAlloc( GetProcessHeap(), 0, tcpTableSize );
                  if (!table)
                     return ERROR_NOT_ENOUGH_MEMORY;
                  ret = GetTcpTable(table, &tcpTableSize, FALSE);
                  if (ret != NO_ERROR) {
                     HeapFree( GetProcessHeap(), 0, table );
                     return ret;
                  }
                  if (*pcbResponseInfoLen < sizeof(MIB_TCPROW) *
                   table->dwNumEntries)
                  {
                     HeapFree( GetProcessHeap(), 0, table );
                     return ERROR_LOCK_VIOLATION;
                  }
                  for (i = 0; i < table->dwNumEntries; i++)
                  {
                     USHORT sPort;

                     sPort = ntohs((USHORT)table->table[i].dwLocalPort);
                     table->table[i].dwLocalPort = (DWORD)sPort;
                     sPort = ntohs((USHORT)table->table[i].dwRemotePort);
                     table->table[i].dwRemotePort = (DWORD)sPort;
                  }
                  memcpy(pResponseInfo, table->table, sizeof(MIB_TCPROW) *
                   table->dwNumEntries);

                  /* calculate the length of the data in the output buffer */
                  *pcbResponseInfoLen = sizeof(MIB_TCPROW) *
                   table->dwNumEntries;

                  HeapFree( GetProcessHeap(), 0, table );
               }
               break;

               default:
               {
                  FIXME ("Command ID Not Supported -> toi_id=0x%lx, toi_entity={tei_entity=0x%lx, tei_instance=0x%lx}, toi_class=0x%lx\n",
                     pcommand->toi_id, pcommand->toi_entity.tei_entity,
                     pcommand->toi_entity.tei_instance, pcommand->toi_class);

                  return (ERROR_BAD_ENVIRONMENT);
               }
            }
         }
         break;


         default:
         {
            FIXME ("Command ID Not Supported -> toi_id=0x%lx, toi_entity={tei_entity=0x%lx, tei_instance=0x%lx}, toi_class=0x%lx\n",
               pcommand->toi_id, pcommand->toi_entity.tei_entity,
               pcommand->toi_entity.tei_instance, pcommand->toi_class);

            return (ERROR_BAD_ENVIRONMENT);
         }
      }

      break;
   }

   case WSCNTL_TCPIP_ICMP_ECHO:
   {
      unsigned int addr = *(unsigned int*)pRequestInfo;
#if 0
         int timeout= *(unsigned int*)(inbuf+4);
         short x1 = *(unsigned short*)(inbuf+8);
         short sendbufsize = *(unsigned short*)(inbuf+10);
         char x2 = *(unsigned char*)(inbuf+12);
         char ttl = *(unsigned char*)(inbuf+13);
         char service = *(unsigned char*)(inbuf+14);
         char type= *(unsigned char*)(inbuf+15); /* 0x2: don't fragment*/
#endif

      FIXME("(ICMP_ECHO) to 0x%08x stub\n", addr);
      break;
   }

   default:
      FIXME("Protocol Not Supported -> protocol=0x%x, action=0x%x, Request=%p, RequestLen=%p, Response=%p, ResponseLen=%p\n",
       protocol, action, pRequestInfo, pcbRequestInfoLen, pResponseInfo, pcbResponseInfoLen);

      return (WSAEOPNOTSUPP);

   }

   return (WSCTL_SUCCESS);
}
Пример #28
0
bool Win32Vif::FindIPAddr(ProtoAddress vifAddr)
{
    // Iterate through addresses looking for an address match
    ULONG bufferSize = 0;
    ULONG index = 0;
    if (ERROR_INSUFFICIENT_BUFFER == GetIpAddrTable(NULL, &bufferSize, FALSE))
    {
        char* tableBuffer = new char[bufferSize];
        if (NULL == tableBuffer)
        {   
            PLOG(PL_ERROR, "ProtoSocket::GetInterfaceName() new tableBuffer error: %s\n", ::GetErrorString());
            return false;
        }
        MIB_IPADDRTABLE* addrTable = (MIB_IPADDRTABLE*)tableBuffer;
        if (ERROR_SUCCESS == GetIpAddrTable(addrTable, &bufferSize, FALSE))
        {
            for (DWORD i = 0; i < addrTable->dwNumEntries; i++)
            {
                MIB_IPADDRROW* entry = &(addrTable->table[i]);
                ProtoAddress tempAddress;
                tempAddress.SetRawHostAddress(ProtoAddress::IPv4, (char*)&entry->dwAddr, 4);
                if (tempAddress.HostIsEqual(vifAddr))
                {
                    return true; // ljt fix me
                    MIB_IFROW ifEntry;  
                    index = entry->dwIndex;
                    if (NO_ERROR != GetIfEntry(&ifEntry))
                    {   
                        PLOG(PL_ERROR, "ProtoSocket::GetInterfaceName() GetIfEntry(%d) error: %s\n", i, ::GetErrorString());
                        return false;
                    }
                    delete[] tableBuffer;
                    break;
                }
            }
        }
        else
        {
            PLOG(PL_WARN, "ProtoSocket::GetInterfaceName(%s) warning GetIpAddrTable() error: %s\n", vifAddr.GetHostString(), GetErrorString());
        }
        delete[] tableBuffer;
    }

    if (index)
    {
        // we found one - add another address
        // ljt need to check if this is a vif etc
        // maybe don't do this at all? just fail
        // if we've found one?

        ULONG status = TRUE;
        UINT tmpIPAddr;
        UINT tmpIPMask;
        ULONG NTEContext = 0;
        ULONG NTEInstance = 0;
        tmpIPAddr = inet_addr(vifAddr.GetHostString());
        tmpIPMask = inet_addr("255.255.255.0");
        if ((status = AddIPAddress(tmpIPAddr,
                                   tmpIPMask,
                                   index,
                                   &NTEContext,
                                   &NTEInstance)) != NO_ERROR)
        {
            PLOG(PL_ERROR,"Win32Vif::Open() AddIPAddress call failed with %d\n",status);
            return false;
        }
        return true;
    }
    return false;
} // end Win32Vif::FindIPAddr()
Пример #29
0
/*
 * Returns zero or more local interfaces to the requestor
 */
DWORD request_net_config_get_interfaces(Remote *remote, Packet *packet)
{
    Packet *response = packet_create_response(packet);
    DWORD result = ERROR_SUCCESS;
    DWORD entryCount;

#ifdef _WIN32
    Tlv entries[5];
    PMIB_IPADDRTABLE table = NULL;
    DWORD tableSize = sizeof(MIB_IPADDRROW) * 33;
    DWORD index;

    MIB_IFROW iface;

    do
    {
        // Allocate memory for reading addresses into
        if (!(table = (PMIB_IPADDRTABLE)malloc(tableSize)))
        {
            result = ERROR_NOT_ENOUGH_MEMORY;
            break;
        }

        // Get the IP address table
        if (GetIpAddrTable(table, &tableSize, TRUE) != NO_ERROR)
        {
            result = GetLastError();
            break;
        }

        // Enumerate the entries
        for (index = 0;
                index < table->dwNumEntries;
                index++)
        {
            entryCount = 0;

            entries[entryCount].header.length = sizeof(DWORD);
            entries[entryCount].header.type   = TLV_TYPE_IP;
            entries[entryCount].buffer        = (PUCHAR)&table->table[index].dwAddr;
            entryCount++;

            entries[entryCount].header.length = sizeof(DWORD);
            entries[entryCount].header.type   = TLV_TYPE_NETMASK;
            entries[entryCount].buffer        = (PUCHAR)&table->table[index].dwMask;
            entryCount++;

            iface.dwIndex = table->table[index].dwIndex;

            // If interface information can get gotten, use it.
            if (GetIfEntry(&iface) == NO_ERROR)
            {
                entries[entryCount].header.length = iface.dwPhysAddrLen;
                entries[entryCount].header.type   = TLV_TYPE_MAC_ADDR;
                entries[entryCount].buffer        = (PUCHAR)iface.bPhysAddr;
                entryCount++;

                if (iface.bDescr)
                {
                    entries[entryCount].header.length = iface.dwDescrLen + 1;
                    entries[entryCount].header.type   = TLV_TYPE_MAC_NAME;
                    entries[entryCount].buffer        = (PUCHAR)iface.bDescr;
                    entryCount++;
                }
            }

            // Add the interface group
            packet_add_tlv_group(response, TLV_TYPE_NETWORK_INTERFACE,
                                 entries, entryCount);
        }

    } while (0);

    if (table)
        free(table);

#else
    Tlv entries[5]; // xxx, we can probably support more. ip aliases, etc.
    char errbuf[PCAP_ERRBUF_SIZE+4];
    pcap_if_t *interfaces, *iter;
    pcap_addr_t *addresses;
    unsigned char mac[6];

    interfaces = iter = NULL;

    memset(entries, 0, sizeof(entries));

    do {
        if(pcap_findalldevs(&interfaces, errbuf) == -1) {
            result = ENOMEM; // xxx, send errbuf to remote
            break;
        }

        for(iter = interfaces; iter != NULL ; iter = iter->next ) {
            entryCount = 0;

            if(strcmp(iter->name, "any") == 0) continue;

            dprintf("[%s] Processing %s", __FUNCTION__, iter->name);

            entries[entryCount].header.length = strlen(iter->name)+1;
            entries[entryCount].header.type   = TLV_TYPE_MAC_NAME;
            entries[entryCount].buffer        = (PUCHAR)iter->name;
            entryCount++;

            for(addresses = iter->addresses ; addresses != NULL ; addresses = addresses->next) {
                struct sockaddr_in *sin;

                dprintf("[%s/%s] addr = %p, netmask = %p, broadaddr = %p, dstaddr = %p", __FUNCTION__, iter->name);
                dprintf("[%s/%s] addresses->addr.sa_family = %d", __FUNCTION__, iter->name, addresses->addr->sa_family);

                if(addresses->addr == NULL) {
                    dprintf("[%s/%s] addresses->addr = NULL ?", __FUNCTION__, iter->name);
                    break;
                }

                if(addresses->addr->sa_family == AF_INET) {
                    sin = (struct sockaddr_in *)(addresses->addr);

                    entries[entryCount].header.length = sizeof(DWORD);
                    entries[entryCount].header.type   = TLV_TYPE_IP;
                    entries[entryCount].buffer	  = (PUCHAR)&sin->sin_addr.s_addr;
                    entryCount++;

                    if(addresses->netmask) {
                        sin = (struct sockaddr_in *)(addresses->netmask);
                        entries[entryCount].header.length = sizeof(DWORD);
                        entries[entryCount].header.type   = TLV_TYPE_NETMASK;
                        entries[entryCount].buffer        = (PUCHAR)&sin->sin_addr.s_addr;
                        entryCount++;
                    }



                    break;
                }

            }

            get_interface_mac_addr(iter->name, mac);

            entries[entryCount].header.length = 6;
            entries[entryCount].header.type   = TLV_TYPE_MAC_ADDR;
            entries[entryCount].buffer        = (PUCHAR)(mac);
            entryCount++;


            dprintf("[%s] adding response with %d entries", __FUNCTION__, entryCount);
            packet_add_tlv_group(response, TLV_TYPE_NETWORK_INTERFACE, entries, entryCount);
            dprintf("[%s] done with adding", __FUNCTION__);
        }

    } while(0);

    if(interfaces) {
        dprintf("[%s] calling pcap_freealldevs()", __FUNCTION__);
        pcap_freealldevs(interfaces);
    }

    dprintf("[%s] and done!", __FUNCTION__);

#endif

    // Transmit the response if valid
    packet_transmit_response(result, remote, response);

    return result;
}
Пример #30
0
int GetAllMacs(char macsStr[][20], int n)
{
   int iRet = -1;
   PIP_ADAPTER_INFO pAdapterInfo;
   PIP_ADAPTER_INFO pAdapter = NULL;
   PIP_ADAPTER_INFO pAdInfo = NULL;
   ULONG            ulSizeAdapterInfo = 0;  
   DWORD            dwStatus;  

   MIB_IFROW MibRow = {0}; 
   int macIndex = 0;
   if(n <= 0) return iRet;
   ulSizeAdapterInfo = sizeof(IP_ADAPTER_INFO); 
   pAdapterInfo = (PIP_ADAPTER_INFO)malloc(ulSizeAdapterInfo);


   if (GetAdaptersInfo( pAdapterInfo, &ulSizeAdapterInfo) != ERROR_SUCCESS) 
   {
      free (pAdapterInfo);
      pAdapterInfo = (PIP_ADAPTER_INFO)malloc(ulSizeAdapterInfo);
   }

   dwStatus = GetAdaptersInfo(pAdapterInfo,   &ulSizeAdapterInfo);  

   if(dwStatus != ERROR_SUCCESS)  
   {  
      free(pAdapterInfo);  
      return  iRet;  
   }  

   pAdInfo = pAdapterInfo; 
   while(pAdInfo)  
   {  	
      if(pAdInfo->Type != MIB_IF_TYPE_ETHERNET && pAdInfo->Type != IF_TYPE_IEEE80211) 
      {
         pAdInfo = pAdInfo->Next; 
         continue;
      }

      memset(&MibRow, 0, sizeof(MIB_IFROW));
      MibRow.dwIndex = pAdInfo->Index;  
      MibRow.dwType = pAdInfo->Type;  

      if(GetIfEntry(&MibRow) == NO_ERROR)  
      {  
         //if (MibRow.dwOperStatus == MIB_IF_OPER_STATUS_OPERATIONAL)
         {

            sprintf(macsStr[macIndex], "%02X:%02X:%02X:%02X:%02X:%02X",
               MibRow.bPhysAddr[0],
               MibRow.bPhysAddr[1],
               MibRow.bPhysAddr[2],
               MibRow.bPhysAddr[3],
               MibRow.bPhysAddr[4],
               MibRow.bPhysAddr[5]);
            macIndex++;
            if(macIndex >= n) break;
         }
      }
      pAdInfo = pAdInfo->Next; 
   }
   free(pAdapterInfo); 
   iRet = macIndex;
   return iRet;
}