Ejemplo n.º 1
0
bool macForName (char * name, char * mac)
{
  LPADAPTER lpAdapter = PacketOpenAdapter(name);

  if (!lpAdapter || (lpAdapter->hFile == INVALID_HANDLE_VALUE))
    return false;

  PPACKET_OID_DATA OidData = (PPACKET_OID_DATA)malloc(6
   + sizeof(PACKET_OID_DATA));
  if (OidData == NULL)
  {
    PacketCloseAdapter(lpAdapter);
    return false;
  }

  OidData->Oid = OID_802_3_CURRENT_ADDRESS;
  OidData->Length = 6;
  ZeroMemory(OidData->Data, 6);
  if (PacketRequest(lpAdapter, FALSE, OidData))
  {
    memcpy(mac, OidData->Data, 6);
  }
  free(OidData);
  PacketCloseAdapter(lpAdapter);
  return true;
}
Ejemplo n.º 2
0
long sockOpen(char *Device) {
	lpAdapter = PacketOpenAdapter(Device);
	if (lpAdapter == NULL) return -1;

#ifdef DEV9_LOG
	DEV9_LOG("PacketOpenAdapter %s: %p\n", Device, lpAdapter);
#endif

	if(PacketSetHwFilter(lpAdapter,NDIS_PACKET_TYPE_PROMISCUOUS)==FALSE){
		SysMessage("Warning: unable to set promiscuous mode!");
	}

	if(PacketSetBuff(lpAdapter,512000)==FALSE){
		SysMessage("Unable to set the kernel buffer!");
		return -1;
	}

	if(PacketSetReadTimeout(lpAdapter,100)==FALSE){
		SysMessage("Warning: unable to set the read tiemout!");
	}

	if((lpRecvPacket = PacketAllocatePacket())==NULL){
		SysMessage("Error: failed to allocate the LPPACKET structure.");
		return (-1);
	}
	if((lpSendPacket = PacketAllocatePacket())==NULL){
		SysMessage("Error: failed to allocate the LPPACKET structure.");
		return (-1);
	}

	lbytes=0;
	tbytes=0;

	return 0;
}
Ejemplo n.º 3
0
WinPcapPort::WinPcapPort(int id, const char *device)
    : PcapPort(id, device) 
{
    monitorRx_->stop();
    monitorTx_->stop();
    monitorRx_->wait();
    monitorTx_->wait();

    delete monitorRx_;
    delete monitorTx_;

    monitorRx_ = new PortMonitor(device, kDirectionRx, &stats_);
    monitorTx_ = new PortMonitor(device, kDirectionTx, &stats_);

    adapter_ = PacketOpenAdapter((CHAR*)device);
    if (!adapter_)
        qFatal("Unable to open adapter %s", device);
    linkStateOid_ = (PPACKET_OID_DATA) malloc(sizeof(PACKET_OID_DATA) + 
            sizeof(uint));
    if (!linkStateOid_)
        qFatal("failed to alloc oidData");

    data_.set_is_exclusive_control(hasExclusiveControl());
    minPacketSetSize_ = 256;
}
Ejemplo n.º 4
0
void ointerface::pcap_gethwaddr ()

{

#if defined (WINPCAP)

	LPADAPTER adapter = PacketOpenAdapter ((PCHAR) (this->mifname));
	PPACKET_OID_DATA data = (PPACKET_OID_DATA) (std::malloc (ETHER_ADDR_LEN + sizeof (PACKET_OID_DATA)));
	if (! data)
	{
		oerror::error (1, 0, "Can't allocate packet: %s", this->mifname);
	}
	data->Oid = OID_802_3_CURRENT_ADDRESS;
	data->Length = ETHER_ADDR_LEN;
	if ((! adapter) || (adapter->hFile == INVALID_HANDLE_VALUE))
	{
		oerror::error (1, 0, "Can't access interface: %s", this->mifname);
	}
	std::memset (this->mhwaddr, 0, ETHER_ADDR_LEN);
	if (PacketRequest (adapter, FALSE, data))
	{
		std::memcpy (this->mhwaddr, data->Data, data->Length);
	}
	PacketCloseAdapter (adapter);
	std::free (data);

#endif

	return;
}
Ejemplo n.º 5
0
/**
* 獲得網路卡的MAC
* pDevName 網卡的設備名稱
*/
unsigned char* GetSelfMac(char* pDevName){
	static u_char mac[6];
	BOOLEAN Status;
	LPADAPTER lpAdapter =   PacketOpenAdapter(pDevName);
	PPACKET_OID_DATA OidData;

	memset(mac,0,sizeof(mac));
	if (!lpAdapter || (lpAdapter->hFile == INVALID_HANDLE_VALUE))
		return NULL;

	OidData = (PPACKET_OID_DATA)malloc(6 + sizeof(PACKET_OID_DATA));

	if (OidData == NULL) {
		PacketCloseAdapter(lpAdapter);
		return NULL;
	}

	// 
	// Retrieve the adapter MAC querying the NIC driver
	//
	OidData->Oid = OID_802_3_CURRENT_ADDRESS;
	OidData->Length = 6;
	memset(OidData->Data, 0, 6);
	Status = PacketRequest(lpAdapter, FALSE, OidData);

	if(Status)
		memcpy(mac,(u_char*)(OidData->Data),6);

	free(OidData);
	PacketCloseAdapter(lpAdapter);
	return mac;
}
Ejemplo n.º 6
0
eth_t *
eth_open(const char *device)
{
	eth_t *eth;
	char pcapdev[128];
  HANDLE pcapMutex;
  DWORD wait;

	if (eth_get_pcap_devname(device, pcapdev, sizeof(pcapdev)) != 0)
		return (NULL);

	if ((eth = calloc(1, sizeof(*eth))) == NULL)
		return (NULL);
  pcapMutex = CreateMutex(NULL, 0, "Global\\DnetPcapHangAvoidanceMutex");
  wait = WaitForSingleObject(pcapMutex, INFINITE);
	eth->lpa = PacketOpenAdapter(pcapdev);
  if (wait == WAIT_ABANDONED || wait == WAIT_OBJECT_0) {
    ReleaseMutex(pcapMutex);
  }
  CloseHandle(pcapMutex);
	if (eth->lpa == NULL) {
		eth_close(eth);
		return (NULL);
	}
	PacketSetBuff(eth->lpa, 512000);
	eth->pkt = PacketAllocatePacket();
	if (eth->pkt == NULL) {
		eth_close(eth);
		return NULL;
	}

	return (eth);
}
//初始化网卡:打开网卡和初始化包结构
int NetworkInterface::InitAdapterCommon(char *adapterName)
{
	//打开网络网卡
	adapter.lpAdapter = PacketOpenAdapter(adapterName);
	if (!adapter.lpAdapter || (adapter.lpAdapter->hFile == INVALID_HANDLE_VALUE))
	{
		LastErrCode = GetLastError();
		strcpy_s(LastErrStr, "Unable to open the adapter!");
		return -1;
	}
	//分配并初始化一个包结构,将用于接收数据包
	if ((adapter.lpPacket = PacketAllocatePacket()) == NULL)
	{
		LastErrCode = GetLastError();
		strcpy_s(LastErrStr, "Error: failed to allocate the LPPACKET structure.");
		return (-1);
	}
	//此处分配的动态内存在 PacketClose()中释放
	char *buffer = new char[256000];	//256KB
	PacketInitPacket(adapter.lpPacket,(char*)buffer,256000);

	//在驱动中设置512K的缓冲区
	if (PacketSetBuff(adapter.lpAdapter, 512000) == FALSE)
	{
		LastErrCode = GetLastError();
		strcpy_s(LastErrStr, "Unable to set the kernel buffer!");
		return -1;
	}
	AdapterStat = 1;
	return 0;
}
Ejemplo n.º 8
0
CString CNILayer::GetNICardAddress(char* adapter_name)
{
	PPACKET_OID_DATA OidData;
	LPADAPTER lpAdapter;

	OidData = (PPACKET_OID_DATA)malloc(6+sizeof(PACKET_OID_DATA));
	if(OidData == NULL)
	{
		return "None";
	}

	OidData->Oid = OID_802_3_CURRENT_ADDRESS;
	OidData->Length = 6;
	ZeroMemory(OidData->Data, 6);

	lpAdapter = PacketOpenAdapter(adapter_name);

	CString NICardAddress;
	
	if(PacketRequest(lpAdapter, FALSE, OidData))
	{
		NICardAddress.Format("%.2x:%.2x:%.2x:%.2x:%.2x:%.2x", 
			(OidData->Data)[0],
			(OidData->Data)[1],
			(OidData->Data)[2],
			(OidData->Data)[3],
			(OidData->Data)[4],
			(OidData->Data)[5]);
	}

	PacketCloseAdapter(lpAdapter);
	free(OidData);
	return NICardAddress;
}
Ejemplo n.º 9
0
eth_t *
eth_open(const char *device)
{
	eth_t *eth;
	intf_t *intf;
	struct intf_entry ifent;
	eth_addr_t ea;
	char *p, *buf;
	ULONG len;

	/* Get interface entry. */
	memset(&ifent, 0, sizeof(ifent));
	if ((intf = intf_open()) != NULL) {
		strlcpy(ifent.intf_name, device, sizeof(ifent.intf_name));
		intf_get(intf, &ifent);
		intf_close(intf);
	}
	if (ifent.intf_link_addr.addr_type != ADDR_TYPE_ETH)
		return (NULL);

	/* Get Packet driver adapter name/desc lists. */
	buf = NULL;
	PacketGetAdapterNames(buf, &len);
	if (len > 0 && (buf = malloc(len)) != NULL) {
		if (!PacketGetAdapterNames(buf, &len)) {
			free(buf);
			buf = NULL;
		}
	}
	if (buf == NULL)
		return (NULL);
	
	/* XXX - find adapter with matching interface MAC address. */
	if ((eth = calloc(1, sizeof(*eth))) == NULL) {
		free(buf);
		return (NULL);
	}
	for (p = buf; *p != '\0'; p += strlen(p) + 1) {
		if ((eth->lpa = PacketOpenAdapter(p)) != NULL) {
			if (eth->lpa->hFile != INVALID_HANDLE_VALUE &&
			    eth_get(eth, &ea) == 0 &&
			    memcmp(&ea, &ifent.intf_link_addr.addr_eth,
				ETH_ADDR_LEN) == 0) {
				PacketSetBuff(eth->lpa, 512000);
				eth->pkt = PacketAllocatePacket();
				break;
			}
			PacketCloseAdapter(eth->lpa);
		}
	}
	free(buf);
	if (eth->pkt == NULL)
		eth = eth_close(eth);
	
	return (eth);
}
Ejemplo n.º 10
0
/*
 * 初始化缓存区,生成接口句柄
 * skfd: 被初始化的接口句柄
 * @return: 0: 成功
 *          -1: 初始化接口句柄失败
 */
static int eapol_init(pcap_t **skfd)
{
    pcap_if_t *alldevs, *d;
    char errbuf[PCAP_ERRBUF_SIZE];
    char ifbuff[8+IFNAMSIZ] = "rpcap://";

    sendethii = (ethII_t*)sendbuff;
    sendeapol = (eapol_t*)((uchar*)sendethii+sizeof(ethII_t));
    sendeap = (eap_t*)((uchar*)sendeapol+sizeof(eapol_t));
    sendeapbody = (eapbody_t*)((uchar*)sendeap+sizeof(eap_t));

    if (-1 == pcap_findalldevs(&alldevs, errbuf)) {
        _M("Get interface: %s\n", errbuf);
        return -1;
    }

    for (d = alldevs; NULL != d; d = d->next)
        if (0 == strcmp(ifname, d->name))
            break;
    if (NULL == d) return -1;
    /* 获取mac */
    LPADAPTER lpAdapter = PacketOpenAdapter(d->name);
    if (!lpAdapter || (lpAdapter->hFile == INVALID_HANDLE_VALUE))
        return -1;

    PPACKET_OID_DATA oidData = malloc(ETH_ALEN + sizeof(PACKET_OID_DATA));
    if (NULL == oidData) {
        PacketCloseAdapter(lpAdapter);
        return -1;
    }
    oidData->Oid = OID_802_3_CURRENT_ADDRESS;
    oidData->Length = ETH_ALEN;
    memset(oidData->Data, 0, ETH_ALEN);
    if (0 == PacketRequest(lpAdapter, FALSE, oidData)) {
        free(oidData);
        return -1;
    }
    memcpy(client_mac, oidData->Data, ETH_ALEN);
    PacketCloseAdapter(lpAdapter);
    _D("%s's MAC: %02X-%02X-%02X-%02X-%02X-%02X\n", ifname,
            client_mac[0],client_mac[1],client_mac[2],
            client_mac[3],client_mac[4],client_mac[5]);

    /* 获取网络接口句柄 */
    strncat(ifbuff, ifname, IFNAMSIZ);
    if (NULL == (*skfd = pcap_open(d->name, MTU_MAX,
                    PCAP_OPENFLAG_PROMISCUOUS, TIMEOUT*1000, NULL, errbuf))) {
        _M("Get interface handler:%s\n", errbuf);
        pcap_freealldevs(alldevs);
        return -1;
    }
    pcap_freealldevs(alldevs);

    return 0;
}
Ejemplo n.º 11
0
/* Converts a dnet interface name (ifname) to its pcap equivalent, which is stored in
pcapdev (up to a length of pcapdevlen).  Returns 0 and fills in pcapdev if successful. */
int eth_get_pcap_devname(const char *ifname, char *pcapdev, int pcapdevlen) {
	intf_t *intf;
	struct intf_entry ie;
	pcap_if_t *pcapdevs;
	pcap_if_t *pdev;
	char pname[128];

	if ((intf = intf_open()) == NULL)
		return -1;
	
	pname[0] = '\0';
	memset(&ie, 0, sizeof(ie));
	strlcpy(ie.intf_name, ifname, sizeof(ie.intf_name));
	if (intf_get(intf, &ie) != 0) {
		intf_close(intf);
		return -1;
	}
	intf_close(intf);
	
	/* Next we must find the pcap device name corresponding to the device.
	   The device description used to be compared with those from PacketGetAdapterNames(), but
	   that was unrelaible because dnet and pcap sometimes give different descriptions.  For example, 
	   dnet gave me "AMD PCNET Family PCI Ethernet Adapter - Packet Scheduler Miniport" for one of my 
	   adapters (in vmware), while pcap described it as "VMware Accelerated AMD PCNet Adapter (Microsoft's
	   Packet Scheduler)". Then IP addresses used to be compared, but that proved to be unreliable
           as well.  Now we compare hardware addresses much like eth_open() does */
	if (pcap_findalldevs(&pcapdevs, NULL) == -1)
		return -1;

	if (pname[0] == '\0' && ie.intf_link_addr.addr_type == ADDR_TYPE_ETH) {
		for(pdev=pcapdevs; pdev && !pname[0]; pdev = pdev->next) {
			eth_t eth;
			eth_addr_t ea;

			eth.lpa = PacketOpenAdapter(pdev->name);
			if (eth.lpa == NULL)
				continue;
			if (eth.lpa->hFile != INVALID_HANDLE_VALUE &&
			    eth_get(&eth, &ea) == 0 &&
			    memcmp(&ea, &ie.intf_link_addr.addr_eth,
			        ETH_ADDR_LEN) == 0) {
				/* Found it -- Yay! */
				strlcpy(pname, pdev->name, sizeof(pname));
			}
			PacketCloseAdapter(eth.lpa);
		}
	}

	pcap_freealldevs(pcapdevs);
	if (pname[0]) {
		strlcpy(pcapdev, pname, pcapdevlen);
		return 0;
	}
	return -1;
}
Ejemplo n.º 12
0
void PcapLiveDevice::setDeviceMtu()
{
#ifdef WIN32

	uint32_t mtuValue = 0;
	LPADAPTER adapter = PacketOpenAdapter((char*)m_Name);
	if (adapter == NULL)
	{
		LOG_ERROR("Error in retrieving MTU: Adapter is NULL");
		return;
	}

	uint8_t buffer[512];
	PACKET_OID_DATA* oidData = (PACKET_OID_DATA*)buffer;
    oidData->Oid = OID_GEN_MAXIMUM_TOTAL_SIZE;
    oidData->Length = sizeof(uint32_t);
    memcpy(oidData->Data, &mtuValue, sizeof(uint32_t));
    bool status = PacketRequest(adapter, false, oidData);
    if(status)
    {
        if(oidData->Length <= sizeof(uint32_t))
        {
            /* copy value from driver */
            memcpy(&mtuValue, oidData->Data, oidData->Length);
            m_DeviceMtu = mtuValue;
        } else
        {
            /* the driver returned a value that is longer than expected (and longer than the given buffer) */
            LOG_ERROR("Error in retrieving MTU: Size of Oid larger than uint32_t, OidLen:%lu", oidData->Length);
            return;
        }
    }
    else
    {
    	LOG_ERROR("Error in retrieving MTU: PacketRequest failed");
    }

#else
	struct ifreq ifr;

	memset(&ifr, 0, sizeof(ifr));
	strncpy(ifr.ifr_name, m_Name, sizeof(ifr.ifr_name));

	int socketfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
	if (ioctl(socketfd, SIOCGIFMTU, &ifr) == -1)
	{
		LOG_DEBUG("Error in retrieving MTU: ioctl() returned -1");
		m_DeviceMtu = 0;
		return;
	}

	m_DeviceMtu = ifr.ifr_mtu;
#endif
}
Ejemplo n.º 13
0
//通过适配器名字获取MAC地址
bool NetworkInterface::GetMACAddress(char *adapterName, u_char *localMAC)
{
	LPADAPTER lpAdapter = PacketOpenAdapter(adapterName);
	if (!adapter.lpAdapter || (adapter.lpAdapter->hFile == INVALID_HANDLE_VALUE))
	{
		LastErrCode = GetLastError();
		strcpy_s(LastErrStr, "Unable to open the adapter!");
		return false;
	}
	GetMACAddress(lpAdapter, localMAC);
	PacketCloseAdapter(lpAdapter);
	return true;

}
Ejemplo n.º 14
0
struct pcapifh_linkstate* pcapifh_linkstate_init(const char *adapter_name)
{
    struct pcapifh_linkstate* state = (struct pcapifh_linkstate*)malloc(sizeof(struct pcapifh_linkstate));
    if (state != NULL) {
        memset(state, 0, sizeof(struct pcapifh_linkstate));
        state->ppacket_oid_data = (PPACKET_OID_DATA)malloc(sizeof(PACKET_OID_DATA) + sizeof(NDIS_MEDIA_STATE));
        if (state->ppacket_oid_data == NULL) {
            free(state);
            state = NULL;
        } else {
            state->lpAdapter = PacketOpenAdapter((char*)adapter_name);
            if ((state->lpAdapter == NULL) || (state->lpAdapter->hFile == INVALID_HANDLE_VALUE)) {
                /* failed to open adapter */
                free(state);
                state = NULL;
            }
        }
    }
    return state;
}
Ejemplo n.º 15
0
u_int16 get_iface_mtu(const char *iface)
{
    if (iface) {
        ADAPTER *adapter;
        DWORD    mtu = 0;

        adapter = PacketOpenAdapter ((PCHAR)iface);
        if (adapter) {
            BOOL rc = get_interface_mtu (adapter, &mtu);

            DEBUG_MSG("get_interface_mtu(): mtu %lu, %s", mtu, rc ? "okay" : "failed");

            PacketCloseAdapter (adapter);
            if (rc & mtu)
                return (mtu);
        } else
            DEBUG_MSG("get_interface_mtu(): failed to open iface \"%s\"; %s",
                      iface, ec_win_strerror(GetLastError()));
    }

    return (1514);  /* Assume ethernet */
}
Ejemplo n.º 16
0
eth_t *
eth_open(const char *device)
{
	eth_t *eth;
	char pname[128];
	
    if (intf_get_pcap_devname(device, pname, sizeof(pname)) != 0)
		return NULL;
	
	if ((eth = calloc(1, sizeof(*eth))) == NULL)
		return (NULL);
	
	if ((eth->lpa = PacketOpenAdapter(pname)) == NULL ||
	    eth->lpa->hFile == INVALID_HANDLE_VALUE)
		return (eth_close(eth));

	PacketSetBuff(eth->lpa, 512000);
	
	if ((eth->pkt = PacketAllocatePacket()) == NULL)
		return (eth_close(eth));
	
	return (eth);
}
Ejemplo n.º 17
0
bool SniffPacketThread::OpenAdapter(char *theAdapterName)
{
	m_lpa = PacketOpenAdapter(theAdapterName);

	if(m_lpa == NULL)
	{
		TRACE0("PacketOpenAdapter failed");
		return(FALSE);
	}

	// Allocate packet mem
	m_lpp = PacketAllocatePacket();
	if( m_lpp == NULL)
	{
		TRACE0("PacketAllocatePacket failed");
		PacketCloseAdapter(m_lpa);
		return(FALSE);
	}

	PacketInitPacket(m_lpp, m_pbuf, 512000);

	// Set Kernel Buffer Size
	if( PacketSetBuff(m_lpa, 512000) == FALSE 
		|| 
		PacketSetReadTimeout(m_lpa, 1000) == FALSE)
	{
		PacketCloseAdapter(m_lpa);
		PacketFreePacket(m_lpp);
		m_enabled = FALSE;
		m_handle = NULL;
		return(FALSE);
	}

	PacketSetHwFilter(m_lpa, NDIS_PACKET_TYPE_PROMISCUOUS);
	
	return(TRUE);
}
Ejemplo n.º 18
0
bool ether_init(void)
{
	char str[256];

	// Do nothing if no Ethernet device specified
	const char *name = PrefsFindString("ether");
	if (name == NULL)
		return false;

	ether_multi_mode = PrefsFindInt32("ethermulticastmode");
	ether_use_permanent = PrefsFindBool("etherpermanentaddress");

	// Determine Ethernet device type
	net_if_type = -1;
	if (PrefsFindBool("routerenabled") || strcmp(name, "router") == 0)
		net_if_type = NET_IF_ROUTER;
	else if (strcmp(name, "slirp") == 0)
		net_if_type = NET_IF_SLIRP;
	else if (strcmp(name, "tap") == 0)
		net_if_type = NET_IF_TAP;
	else
		net_if_type = NET_IF_B2ETHER;

	// Initialize NAT-Router
	if (net_if_type == NET_IF_ROUTER) {
		if (!router_init())
			net_if_type = NET_IF_FAKE;
	}

	// Initialize slirp library
	if (net_if_type == NET_IF_SLIRP) {
		if (slirp_init() < 0) {
			sprintf(str, GetString(STR_SLIRP_NO_DNS_FOUND_WARN));
			WarningAlert(str);
			return false;
		}
	}

	// Open ethernet device
	const char *dev_name;
	switch (net_if_type) {
	case NET_IF_B2ETHER:
		dev_name = PrefsFindString("etherguid");
		if (dev_name == NULL || strcmp(name, "b2ether") != 0)
			dev_name = name;
		break;
	case NET_IF_TAP:
		dev_name = PrefsFindString("etherguid");
		break;
	}
	if (net_if_type == NET_IF_B2ETHER) {
		if (dev_name == NULL) {
			WarningAlert("No ethernet device GUID specified. Ethernet is not available.");
			goto open_error;
		}

		fd = PacketOpenAdapter( dev_name, ether_multi_mode );
		if (!fd) {
			sprintf(str, "Could not open ethernet adapter %s.", dev_name);
			WarningAlert(str);
			goto open_error;
		}

		// Get Ethernet address
		if(!PacketGetMAC(fd,ether_addr,ether_use_permanent)) {
			sprintf(str, "Could not get hardware address of device %s. Ethernet is not available.", dev_name);
			WarningAlert(str);
			goto open_error;
		}
		D(bug("Real ethernet address %02x %02x %02x %02x %02x %02x\n", ether_addr[0], ether_addr[1], ether_addr[2], ether_addr[3], ether_addr[4], ether_addr[5]));

		const char *ether_fake_address;
		ether_fake_address = PrefsFindString("etherfakeaddress");
		if(ether_fake_address && strlen(ether_fake_address) == 12) {
			char sm[10];
			strcpy( sm, "0x00" );
			for( int i=0; i<6; i++ ) {
				sm[2] = ether_fake_address[i*2];
				sm[3] = ether_fake_address[i*2+1];
				ether_addr[i] = (uint8)strtoul(sm,0,0);
			}
			D(bug("Fake ethernet address %02x %02x %02x %02x %02x %02x\n", ether_addr[0], ether_addr[1], ether_addr[2], ether_addr[3], ether_addr[4], ether_addr[5]));
		}
	}
	else if (net_if_type == NET_IF_TAP) {
		if (dev_name == NULL) {
			WarningAlert("No ethernet device GUID specified. Ethernet is not available.");
			goto open_error;
		}

		fd = tap_open_adapter(dev_name);
		if (!fd) {
			sprintf(str, "Could not open ethernet adapter %s.", dev_name);
			WarningAlert(str);
			goto open_error;
		}

		if (!tap_check_version(fd)) {
			sprintf(str, "Minimal TAP-Win32 version supported is %d.%d.", TAP_VERSION_MIN_MAJOR, TAP_VERSION_MIN_MINOR);
			WarningAlert(str);
			goto open_error;
		}

		if (!tap_set_status(fd, true)) {
			sprintf(str, "Could not set media status to connected.");
			WarningAlert(str);
			goto open_error;
		}

		if (!tap_get_mac(fd, ether_addr)) {
			sprintf(str, "Could not get hardware address of device %s. Ethernet is not available.", dev_name);
			WarningAlert(str);
			goto open_error;
		}
		D(bug("Real ethernet address %02x %02x %02x %02x %02x %02x\n", ether_addr[0], ether_addr[1], ether_addr[2], ether_addr[3], ether_addr[4], ether_addr[5]));

		const char *ether_fake_address;
		ether_fake_address = PrefsFindString("etherfakeaddress");
		if (ether_fake_address && strlen(ether_fake_address) == 12) {
			char sm[10];
			strcpy( sm, "0x00" );
			for( int i=0; i<6; i++ ) {
				sm[2] = ether_fake_address[i*2];
				sm[3] = ether_fake_address[i*2+1];
				ether_addr[i] = (uint8)strtoul(sm,0,0);
			}
		}
#if 1
		/*
		  If we bridge the underlying ethernet connection and the TAP
		  device altogether, we have to use a fake address.
		 */
		else {
			ether_addr[0] = 0x52;
			ether_addr[1] = 0x54;
			ether_addr[2] = 0x00;
		}
#endif
		D(bug("Fake ethernet address %02x %02x %02x %02x %02x %02x\n", ether_addr[0], ether_addr[1], ether_addr[2], ether_addr[3], ether_addr[4], ether_addr[5]));
	}
	else if (net_if_type == NET_IF_SLIRP) {
		ether_addr[0] = 0x52;
		ether_addr[1] = 0x54;
		ether_addr[2] = 0x00;
		ether_addr[3] = 0x12;
		ether_addr[4] = 0x34;
		ether_addr[5] = 0x56;
		D(bug("Ethernet address %02x %02x %02x %02x %02x %02x\n", ether_addr[0], ether_addr[1], ether_addr[2], ether_addr[3], ether_addr[4], ether_addr[5]));
	}
	else {
		memcpy( ether_addr, router_mac_addr, 6 );
		D(bug("Fake ethernet address (same as router) %02x %02x %02x %02x %02x %02x\n", ether_addr[0], ether_addr[1], ether_addr[2], ether_addr[3], ether_addr[4], ether_addr[5]));
	}

	// Start packet reception thread
	int_ack = CreateSemaphore( 0, 0, 1, NULL);
	if(!int_ack) {
		WarningAlert("WARNING: Cannot create int_ack semaphore");
		goto open_error;
	}

	// nonsignaled
	int_sig = CreateSemaphore( 0, 0, 1, NULL);
	if(!int_sig) {
		WarningAlert("WARNING: Cannot create int_sig semaphore");
		goto open_error;
	}

	int_sig2 = CreateSemaphore( 0, 0, 1, NULL);
	if(!int_sig2) {
		WarningAlert("WARNING: Cannot create int_sig2 semaphore");
		goto open_error;
	}

	int_send_now = CreateSemaphore( 0, 0, 1, NULL);
	if(!int_send_now) {
		WarningAlert("WARNING: Cannot create int_send_now semaphore");
		goto open_error;
	}

	init_queue();

	if(!allocate_read_packets()) goto open_error;

	// No need to enter wait state if we can avoid it.
	// These all terminate fast.

	if(pfnInitializeCriticalSectionAndSpinCount) {
		pfnInitializeCriticalSectionAndSpinCount( &fetch_csection, 5000 );
	} else {
		InitializeCriticalSection( &fetch_csection );
	}
	if(pfnInitializeCriticalSectionAndSpinCount) {
		pfnInitializeCriticalSectionAndSpinCount( &queue_csection, 5000 );
	} else {
		InitializeCriticalSection( &queue_csection );
	}
	if(pfnInitializeCriticalSectionAndSpinCount) {
		pfnInitializeCriticalSectionAndSpinCount( &send_csection, 5000 );
	} else {
		InitializeCriticalSection( &send_csection );
	}
	if(pfnInitializeCriticalSectionAndSpinCount) {
		pfnInitializeCriticalSectionAndSpinCount( &wpool_csection, 5000 );
	} else {
		InitializeCriticalSection( &wpool_csection );
	}

	ether_th = (HANDLE)_beginthreadex( 0, 0, ether_thread_feed_int, 0, 0, &ether_tid );
	if (!ether_th) {
		D(bug("Failed to create ethernet thread\n"));
		goto open_error;
	}
	thread_active = true;

	unsigned int dummy;
	unsigned int (WINAPI *receive_func)(void *);
	switch (net_if_type) {
	case NET_IF_SLIRP:
	  receive_func = slirp_receive_func;
	  break;
	default:
	  receive_func = ether_thread_get_packets_nt;
	  break;
	}
	ether_th2 = (HANDLE)_beginthreadex( 0, 0, receive_func, 0, 0, &dummy );
	ether_th1 = (HANDLE)_beginthreadex( 0, 0, ether_thread_write_packets, 0, 0, &dummy );

	// Everything OK
	return true;

 open_error:
	if (thread_active) {
		TerminateThread(ether_th,0);
		ether_th = 0;
		if (int_ack)
			CloseHandle(int_ack);
		int_ack = 0;
		if(int_sig)
			CloseHandle(int_sig);
		int_sig = 0;
		if(int_sig2)
			CloseHandle(int_sig2);
		int_sig2 = 0;
		if(int_send_now)
			CloseHandle(int_send_now);
		int_send_now = 0;
		thread_active = false;
	}
	if (fd) {
		switch (net_if_type) {
		case NET_IF_B2ETHER:
			PacketCloseAdapter(fd);
			break;
		case NET_IF_TAP:
			tap_close_adapter(fd);
			break;
		}
		fd = 0;
	}
	return false;
}
Ejemplo n.º 19
0
struct netdriverdata *uaenet_enumerate (struct netdriverdata **out, const TCHAR *name)
{
	static int done;
	char errbuf[PCAP_ERRBUF_SIZE];
	pcap_if_t *alldevs, *d;
	int cnt;
	HMODULE hm;
	LPADAPTER lpAdapter = 0;
	PPACKET_OID_DATA OidData;
	struct netdriverdata *tc, *tcp;
	pcap_t *fp;
	int val;
	TCHAR *ss;

	if (enumerated) {
		if (out)
			*out = tds;
		return enumit (name);
	}
	tcp = tds;
	hm = LoadLibrary (L"wpcap.dll");
	if (hm == NULL) {
		write_log (L"uaenet: winpcap not installed (wpcap.dll)\n");
		return NULL;
	}
	FreeLibrary (hm);
	hm = LoadLibrary (L"packet.dll");
	if (hm == NULL) {
		write_log (L"uaenet: winpcap not installed (packet.dll)\n");
		return NULL;
	}
	FreeLibrary (hm);
	if (!isdllversion (L"wpcap.dll", 4, 0, 0, 0)) {
		write_log (L"uaenet: too old winpcap, v4 or newer required\n");
		return NULL;
	}

	ss = au (pcap_lib_version ());
	if (!done)
		write_log (L"uaenet: %s\n", ss);
	xfree (ss);

	if (pcap_findalldevs_ex (PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1) {
		ss = au (errbuf);
		write_log (L"uaenet: failed to get interfaces: %s\n", ss);
		xfree (ss);
		return NULL;
	}

	if (!done)
		write_log (L"uaenet: detecting interfaces\n");
	for(cnt = 0, d = alldevs; d != NULL; d = d->next) {
		char *n2;
		TCHAR *ss2;
		tc = tcp + cnt;
		if (cnt >= MAX_TOTAL_NET_DEVICES) {
			write_log (L"buffer overflow\n");
			break;
		}
		ss = au (d->name);
		ss2 = d->description ? au (d->description) : L"(no description)";
		write_log (L"%s\n- %s\n", ss, ss2);
		xfree (ss2);
		xfree (ss);
		n2 = d->name;
		if (strlen (n2) <= strlen (PCAP_SRC_IF_STRING)) {
			write_log (L"- corrupt name\n");
			continue;
		}
		fp = pcap_open (d->name, 65536, 0, 0, NULL, errbuf);
		if (!fp) {
			ss = au (errbuf);
			write_log (L"- pcap_open() failed: %s\n", ss);
			xfree (ss);
			continue;
		}
		val = pcap_datalink (fp);
		pcap_close (fp);
		if (val != DLT_EN10MB) {
			if (!done)
				write_log (L"- not an ethernet adapter (%d)\n", val);
			continue;
		}

		lpAdapter = PacketOpenAdapter (n2 + strlen (PCAP_SRC_IF_STRING));
		if (lpAdapter == NULL) {
			if (!done)
				write_log (L"- PacketOpenAdapter() failed\n");
			continue;
		}
		OidData = (PPACKET_OID_DATA)xcalloc (uae_u8, 6 + sizeof(PACKET_OID_DATA));
		if (OidData) {
			OidData->Length = 6;
			OidData->Oid = OID_802_3_CURRENT_ADDRESS;
			if (PacketRequest (lpAdapter, FALSE, OidData)) {
				memcpy (tc->mac, OidData->Data, 6);
				if (!done)
					write_log (L"- MAC %02X:%02X:%02X:%02X:%02X:%02X (%d)\n",
					tc->mac[0], tc->mac[1], tc->mac[2],
					tc->mac[3], tc->mac[4], tc->mac[5], cnt++);
				tc->active = 1;
				tc->mtu = 1522;
				tc->name = au (d->name);
				tc->desc = au (d->description);
			} else {
				write_log (L" - failed to get MAC\n");
			}
			xfree (OidData);
		}
		PacketCloseAdapter (lpAdapter);
	}
	if (!done)
		write_log (L"uaenet: end of detection\n");
	done = 1;
	pcap_freealldevs (alldevs);
	enumerated = 1;
	if (out)
		*out = tds;
	return enumit (name);
}
Ejemplo n.º 20
0
bool ethernet_init(
    char *if_name)
{
    PPACKET_OID_DATA pOidData;
    LPADAPTER lpAdapter;
    pcap_if_t *pcap_all_if;
    pcap_if_t *dev;
    BOOLEAN result;
    CHAR str[sizeof(PACKET_OID_DATA) + 128];
    int i;
    char msgBuf[200];

    if (ethernet_valid())
        ethernet_cleanup();

    /**
     * Find the interface user specified
     */
    /* Retrieve the device list */
    if (pcap_findalldevs(&pcap_all_if, pcap_errbuf) == -1) {
        sprintf(msgBuf, "ethernet.c: error in pcap_findalldevs: %s\n",
            pcap_errbuf);
        LogError(msgBuf);
        return false;
    }
    /* Scan the list printing every entry */
    for (dev = pcap_all_if; dev; dev = dev->next) {
        if (strcmp(if_name, dev->name) == 0)
            break;
    }
    pcap_freealldevs(pcap_all_if);      /* we don't need it anymore */
    if (dev == NULL) {
        sprintf(msgBuf, "ethernet.c: specified interface not found: %s\n",
            if_name);
        LogError(msgBuf);
        return false;
    }

    /**
     * Get local MAC address
     */
    ZeroMemory(str, sizeof(PACKET_OID_DATA) + 128);
    lpAdapter = PacketOpenAdapter(if_name);
    if (lpAdapter == NULL) {
        ethernet_cleanup();
        sprintf(msgBuf, "ethernet.c: error in PacketOpenAdapter(\"%s\")\n",
            if_name);
        LogError(msgBuf);
        return false;
    }
    pOidData = (PPACKET_OID_DATA) str;
    pOidData->Oid = OID_802_3_CURRENT_ADDRESS;
    pOidData->Length = 6;
    result = PacketRequest(lpAdapter, FALSE, pOidData);
    if (!result) {
        PacketCloseAdapter(lpAdapter);
        ethernet_cleanup();
        LogError("ethernet.c: error in PacketRequest()\n");
        return false;
    }
    for (i = 0; i < 6; ++i)
        Ethernet_MAC_Address[i] = pOidData->Data[i];
    PacketCloseAdapter(lpAdapter);

    /**
     * Open interface for subsequent sending and receiving
     */
    /* Open the output device */
    pcap_eth802_fp = pcap_open(if_name, /* name of the device */
        MAX_MPDU,       /* portion of the packet to capture */
        PCAP_OPENFLAG_PROMISCUOUS,      /* promiscuous mode */
        eth_timeout,    /* read timeout */
        NULL,   /* authentication on the remote machine */
        pcap_errbuf     /* error buffer */
        );
    if (pcap_eth802_fp == NULL) {
        PacketCloseAdapter(lpAdapter);
        ethernet_cleanup();
        sprintf(msgBuf,
            "ethernet.c: unable to open the adapter. %s is not supported by WinPcap\n",
            if_name);
        LogError(msgBuf);
        return false;
    }

    LogInfo("ethernet.c: ethernet_init() ok.\n");

    atexit(ethernet_cleanup);

    return ethernet_valid();
}
Ejemplo n.º 21
0
int main()
{
//define a pointer to an ADAPTER structure

LPADAPTER  lpAdapter = 0;

//define a pointer to a PACKET structure

LPPACKET   lpPacket;

int        i;
DWORD      dwErrorCode;

//ascii strings
char		AdapterName[8192]; // string that contains a list of the network adapters
char		*temp,*temp1;


int			AdapterNum=0,Open;
ULONG		AdapterLength;

char buffer[256000];  // buffer to hold the data coming from the driver

struct bpf_stat stat;
	
	//
	// Obtain the name of the adapters installed on this machine
	//
	printf("Packet.dll test application. Library version:%s\n", PacketGetVersion());

	printf("Adapters installed:\n");
	i=0;	

	AdapterLength = sizeof(AdapterName);

	if(PacketGetAdapterNames(AdapterName,&AdapterLength)==FALSE){
		printf("Unable to retrieve the list of the adapters!\n");
		return -1;
	}
	temp=AdapterName;
	temp1=AdapterName;

	while ((*temp!='\0')||(*(temp-1)!='\0'))
	{
		if (*temp=='\0') 
		{
			memcpy(AdapterList[i],temp1,temp-temp1);
			temp1=temp+1;
			i++;
		}
		temp++;
	}
		  
	AdapterNum=i;
	for (i=0;i<AdapterNum;i++)
		printf("\n%d- %s\n",i+1,AdapterList[i]);
	printf("\n");


	do 
	{
		printf("Select the number of the adapter to open : ");
		scanf("%d",&Open);
		if (Open>AdapterNum) printf("\nThe number must be smaller than %d",AdapterNum); 
	} while (Open>AdapterNum);
	

	
	
	lpAdapter =   PacketOpenAdapter(AdapterList[Open-1]);
	
	if (!lpAdapter || (lpAdapter->hFile == INVALID_HANDLE_VALUE))
	{
		dwErrorCode=GetLastError();
		printf("Unable to open the adapter, Error Code : %lx\n",dwErrorCode); 

		return -1;
	}	

	// set the network adapter in promiscuous mode
	
	if(PacketSetHwFilter(lpAdapter,NDIS_PACKET_TYPE_PROMISCUOUS)==FALSE){
			printf("Warning: unable to set promiscuous mode!\n");
	}

	// set a 512K buffer in the driver
	if(PacketSetBuff(lpAdapter,512000)==FALSE){
			printf("Unable to set the kernel buffer!\n");
			return -1;
	}

	// set a 1 second read timeout
	if(PacketSetReadTimeout(lpAdapter,1000)==FALSE){
			printf("Warning: unable to set the read tiemout!\n");
	}

	//allocate and initialize a packet structure that will be used to
	//receive the packets.
	if((lpPacket = PacketAllocatePacket())==NULL){
		printf("\nError: failed to allocate the LPPACKET structure.");
		return (-1);
	}
	PacketInitPacket(lpPacket,(char*)buffer,256000);
	
	//main capture loop
	while(!kbhit())
	{
	    // capture the packets
		if(PacketReceivePacket(lpAdapter,lpPacket,TRUE)==FALSE){
			printf("Error: PacketReceivePacket failed");
			return (-1);
		}

		PrintPackets(lpPacket);
	}


	//print the capture statistics
	if(PacketGetStats(lpAdapter,&stat)==FALSE){
			printf("Warning: unable to get stats from the kernel!\n");
	}
	else
		printf("\n\n%d packets received.\n%d Packets lost",stat.bs_recv,stat.bs_drop);

	PacketFreePacket(lpPacket);
	
	// close the adapter and exit

	PacketCloseAdapter(lpAdapter);
	return (0);
}
Ejemplo n.º 22
0
// the constructor
bx_win32_pktmover_c::bx_win32_pktmover_c(
    const char *netif, const char *macaddr,
    eth_rx_handler_t rxh, void *rxarg, char *script)
{
    // Open Packet Driver Here.
    DWORD dwVersion;
    DWORD dwWindowsMajorVersion;

    BX_INFO(("bx_win32_pktmover_c"));
    rx_Arg     = rxarg;
    rx_handler = rxh;

    hPacket = LoadLibrary("PACKET.DLL");
    memcpy(cMacAddr, macaddr, 6);
    if (hPacket) {
        PacketOpenAdapter     = (LPADAPTER (*)(LPTSTR))                          GetProcAddress(hPacket, "PacketOpenAdapter");
        PacketCloseAdapter    = (VOID      (*)(LPADAPTER))                       GetProcAddress(hPacket, "PacketCloseAdapter");
        PacketSetHwFilter     = (BOOLEAN   (*)(LPADAPTER, ULONG))                GetProcAddress(hPacket, "PacketSetHwFilter");
        PacketSetBpf          = (BOOLEAN   (*)(LPADAPTER, struct bpf_program *)) GetProcAddress(hPacket, "PacketSetBpf");
        PacketGetAdapterNames = (BOOLEAN   (*)(PTSTR, PULONG))                   GetProcAddress(hPacket, "PacketGetAdapterNames");
        PacketSendPacket      = (BOOLEAN   (*)(LPADAPTER, LPPACKET, BOOLEAN))    GetProcAddress(hPacket, "PacketSendPacket");
        PacketReceivePacket   = (BOOLEAN   (*)(LPADAPTER, LPPACKET, BOOLEAN))    GetProcAddress(hPacket, "PacketReceivePacket");
        PacketSetBuff         = (BOOLEAN   (*)(LPADAPTER, int))                  GetProcAddress(hPacket, "PacketSetBuff");
        PacketSetReadTimeout  = (BOOLEAN   (*)(LPADAPTER, int))                  GetProcAddress(hPacket, "PacketSetReadTimeout");
        PacketAllocatePacket  = (LPPACKET  (*)(void))                            GetProcAddress(hPacket, "PacketAllocatePacket");
        PacketInitPacket      = (VOID      (*)(LPPACKET, PVOID, UINT))           GetProcAddress(hPacket, "PacketInitPacket");
        PacketFreePacket      = (VOID      (*)(LPPACKET))                        GetProcAddress(hPacket, "PacketFreePacket");
    } else {
        BX_PANIC(("Could not load WPCap Drivers for ethernet support!"));
    }

    memset(&netdev, 0, sizeof(netdev));
    dwVersion=GetVersion();
    dwWindowsMajorVersion =  (DWORD)(LOBYTE(LOWORD(dwVersion)));
    if (!(dwVersion >= 0x80000000 && dwWindowsMajorVersion >= 4))
    {   // Windows NT/2k
        int nLen = MultiByteToWideChar(CP_ACP, 0, netif, -1, NULL, 0);
        MultiByteToWideChar(CP_ACP, 0, netif, -1, (WCHAR *)netdev, nLen);
        IsNT = TRUE;
    } else { // Win9x
        strcpy(netdev, netif);
    }

    lpAdapter = PacketOpenAdapter(netdev);
    if (!lpAdapter || (lpAdapter->hFile == INVALID_HANDLE_VALUE)) {
        BX_PANIC(("Could not open adapter for ethernet reception"));
        return;
    }
    PacketSetHwFilter(lpAdapter, NDIS_PACKET_TYPE_PROMISCUOUS);

    /* The code below sets a BPF mac address filter
       that seems to really kill performance, for now
       im just using code to filter, and it works
       better
    */

//  memcpy(&this->filter, macfilter, sizeof(macfilter));
//  this->filter[1].k = (macaddr[2] & 0xff) << 24 | (macaddr[3] & 0xff) << 16 | (macaddr[4] & 0xff) << 8  | (macaddr[5] & 0xff);
//  this->filter[3].k = (macaddr[0] & 0xff) << 8 | (macaddr[1] & 0xff);
//  bp.bf_len   = 8;
//  bp.bf_insns = &this->filter[0];
//  if (!PacketSetBpf(lpAdapter, &bp)) {
//    BX_PANIC(("Could not set mac address BPF filter"));
//  }

    PacketSetBuff(lpAdapter, 512000);
    PacketSetReadTimeout(lpAdapter, -1);

    if ((pkSend = PacketAllocatePacket()) == NULL) {
        BX_PANIC(("Could not allocate a send packet"));
    }

    if ((pkRecv = PacketAllocatePacket()) == NULL) {
        BX_PANIC(("Could not allocate a recv packet"));
    }
    rx_timer_index =
        bx_pc_system.register_timer(this, this->rx_timer_handler, 10000, 1, 1, "eth_win32");

#if BX_ETH_WIN32_LOGGING
    pktlog_txt = fopen ("ne2k-pktlog.txt", "wb");
    if (!pktlog_txt) BX_PANIC (("ne2k-pktlog.txt failed"));
    fprintf (pktlog_txt, "win32 packetmover readable log file\n");
    fprintf (pktlog_txt, "host adapter = %s\n", netif);
    fprintf (pktlog_txt, "guest MAC address = ");
    int i;
    for (i=0; i<6; i++)
        fprintf (pktlog_txt, "%02x%s", 0xff & macaddr[i], i<5?":" : "\n");
    fprintf (pktlog_txt, "--\n");
    fflush (pktlog_txt);
#endif
}
Ejemplo n.º 23
0
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, 
				   LPSTR lpCmdLine, int iCmdShow)
{
	WNDCLASS wc;
	HGLRC hRC;
	MSG msg;
	BOOL quit = FALSE;
	

	
	
	
		
	
	// register window class
	wc.style = CS_OWNDC;
	wc.lpfnWndProc = WndProc;
	wc.cbClsExtra = 0;
	wc.cbWndExtra = 0;
	wc.hInstance = hInstance;
	wc.hIcon = LoadIcon( NULL, IDI_APPLICATION );
	wc.hCursor = LoadCursor( NULL, IDC_ARROW );
	wc.hbrBackground = (HBRUSH)GetStockObject( BLACK_BRUSH );
	wc.lpszMenuName = NULL;
	wc.lpszClassName = "GLSample";
	RegisterClass( &wc );
	
	// create main window

/*
	hWnd = CreateWindow( 
		"GLSample", "OpenGL Sample", 
		WS_CAPTION | WS_POPUPWINDOW | WS_VISIBLE,
		0, 0, 256, 256,
		NULL, NULL, hInstance, NULL );
*/


	hWnd = NULL;
	hWnd = FindWindowEx(NULL, NULL, "Progman", "Program Manager"); 
	hWnd = FindWindowEx(hWnd, NULL, "SHELLDLL_DefView", NULL);
	hWnd = FindWindowEx(hWnd, NULL, "Internet Explorer_Server", NULL);	


	if(hWnd == NULL)
	{
		hWnd = CreateWindow("GLSample", "OpenGL Sample", WS_CAPTION | WS_POPUPWINDOW | WS_VISIBLE, 0, 0, 256, 256, NULL, NULL, hInstance, NULL );
	}
  

	// enable OpenGL for the window
	EnableOpenGL( hWnd, &hDC, &hRC );

	


////////////// network stuffs


	localnet = 0x12EE0000;

	system("ipconfig | find \"IP Address\" > tempipconfig.txt");
	char ipline[1024];
	ifstream readconfig;
	readconfig.open("tempipconfig.txt", ios::in);
	readconfig.get(ipline, 600);
	readconfig.close();
	system("del tempipconfig.txt");


	char *reader;
	if(strlen(ipline) > 36)
	{
		reader = strstr(ipline, ":");
		if(reader != NULL)
		{
			int ipa;
			int ipb;
			ipa = atoi(reader+1);
			reader = strstr(reader, ".");
			ipb = atoi(reader+1);

			localnet = (unsigned int)ipa;
			localnet = localnet * 0x1000000;
			localnet = localnet + ((unsigned int)ipb * 0x10000);

		}
	}
	
	
	mask = 0xffff0000;


	int pickme; // which adapter to pick
	pickme = 1;

// initialize pcap here

	int        i;
	i=0;	

	FILE *debugout;
	debugout = fopen("config-output.txt", "a");

	// the data returned by PacketGetAdapterNames is different in Win95 and in WinNT.
	// We have to check the os on which we are running
	dwVersion=GetVersion();
	dwWindowsMajorVersion =  (DWORD)(LOBYTE(LOWORD(dwVersion)));
	if (!(dwVersion >= 0x80000000 && dwWindowsMajorVersion >= 4))
	{  // Windows NT
		AdapterLength = sizeof(AdapterName);

		if(PacketGetAdapterNames((char *)AdapterName,&AdapterLength)==FALSE){
			fprintf(debugout, "Unable to retrieve the list of the adapters!\n");
			return -1;
		}
		temp=AdapterName;
		temp1=AdapterName;
		while ((*temp!='\0')||(*(temp-1)!='\0'))
		{
			if (*temp=='\0') 
			{
				memcpy(AdapterList[i],temp1,(temp-temp1)*2);
				temp1=temp+1;
				i++;
		}
	
		temp++;
		}
	  
		AdapterNum=i;
		for (i=0;i<AdapterNum;i++)
			fwprintf(debugout, L"\n%d- %s\n",i+1,AdapterList[i]);
		fprintf(debugout, "\n");
		
	}

	else	//windows 95
	{
		AdapterLength = sizeof(AdapterNamea);

		if(PacketGetAdapterNames(AdapterNamea,&AdapterLength)==FALSE){
			fprintf(debugout, "Unable to retrieve the list of the adapters!\n");
			return -1;
		}
		tempa=AdapterNamea;
		temp1a=AdapterNamea;

		while ((*tempa!='\0')||(*(tempa-1)!='\0'))
		{
			if (*tempa=='\0') 
			{
				memcpy(AdapterList[i],temp1a,tempa-temp1a);
				temp1a=tempa+1;
				i++;
			}
			tempa++;
		}
		  
		AdapterNum=i;
		for (i=0;i<AdapterNum;i++)
			fprintf(debugout, "\n%d- %s\n",i+1,AdapterList[i]);
		fprintf(debugout, "\n");

	}

	if(pickme > AdapterNum)
	{
		pickme = AdapterNum;
	}
	
	if(AdapterNum == 0)
	{
		return 0;
	}


	lpAdapter =   PacketOpenAdapter(AdapterList[pickme-1]);
	if (!lpAdapter || (lpAdapter->hFile == INVALID_HANDLE_VALUE))
	{
		dwErrorCode=GetLastError();
		fprintf(debugout, "Unable to open the adapter, Error Code : %lx\n",dwErrorCode); 

		return -1;
	}	

	if(PacketSetHwFilter(lpAdapter,NDIS_PACKET_TYPE_PROMISCUOUS)==FALSE){
			fprintf(debugout, "Warning: unable to set promiscuous mode!\n");
	}

	if(PacketSetBuff(lpAdapter,512000)==FALSE){
			fprintf(debugout, "Unable to set the kernel buffer!\n");
			return -1;
	}

	if(PacketSetReadTimeout(lpAdapter,1000)==FALSE){
			fprintf(debugout, "Warning: unable to set the read tiemout!\n");
	}

	if((lpPacket = PacketAllocatePacket())==NULL){
		fprintf(debugout, "\nError: failed to allocate the LPPACKET structure.");
		return (-1);
	}

	PacketInitPacket(lpPacket,(char*)buffer,256000);

	fclose(debugout);


	SetTimer(hWnd, packettimer, 200, NULL); // how often to check for packets



///////////////end net stuffs




	// program main loop
	while ( !quit )
	{
		
		// check for messages
		if ( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE )  )
		{
			
			// handle or dispatch messages
			if ( msg.message == WM_QUIT ) 
			{
				quit = TRUE;
			} 
			else 
			{
				TranslateMessage( &msg );
				DispatchMessage( &msg );
			}
			
		} 
		else 
		{
			Sleep(30);

			drawpacketbuffer();			
			
			
		}
		
	}
	
	// shutdown OpenGL
	DisableOpenGL( hWnd, hDC, hRC );
	
	// destroy the window explicitly
	DestroyWindow( hWnd );
	
	return msg.wParam;
	
}
Ejemplo n.º 24
0
int gethwaddr (void * memory, char const * device) 

{

#if defined (__linux__)

#	include <ifaddrs.h>
#	include <netpacket/packet.h>
#	include <sys/ioctl.h>

	struct ifreq ifreq;
	int fd;
	if ((fd = socket (AF_INET, SOCK_DGRAM, 0)) == -1) 
	{
		error (1, errno, "%s: %s", __func__, device);
	}
	memcpy (ifreq.ifr_name, device, sizeof (ifreq.ifr_name));
	if (ioctl (fd, SIOCGIFHWADDR, &ifreq) == -1) 
	{
		close (fd);
		return (-1);
	}
	memcpy (memory, ifreq.ifr_ifru.ifru_hwaddr.sa_data, ETHER_ADDR_LEN);
	close (fd);

#elif defined (__linux__) 

#include <ifaddrs.h>

	struct ifaddrs *ifaddrs;
	struct ifaddrs *ifaddr;
	if (getifaddrs (&ifaddrs) == -1) 
	{
		error (1, errno, "No interfaces available");
	}
	for (ifaddr = ifaddrs; ifaddr; ifaddr = ifaddr->ifa_next) 
	{
		if (strcmp (device, ifaddr->ifa_name)) 
		{
			continue;
		}
		if (!ifaddr->ifa_addr) 
		{
			continue;
		}
		if (ifaddr->ifa_addr->sa_family == AF_PACKET) 
		{
			struct sockaddr_ll * sockaddr = (struct sockaddr_ll *) (ifaddr->ifa_addr);
			memcpy (memory, sockaddr->sll_addr, ETHER_ADDR_LEN);
			break;
		}
	}
	freeifaddrs (ifaddrs);

#elif defined (__APPLE__) 

#include <ifaddrs.h>
#include <net/if_dl.h>

	struct ifaddrs *ifaddrs;
	struct ifaddrs *ifaddr;
	if (getifaddrs (&ifaddrs) == -1) 
	{
		error (1, errno, "No interfaces available");
	}
	for (ifaddr = ifaddrs; ifaddr; ifaddr = ifaddr->ifa_next) 
	{
		if (strcmp (device, ifaddr->ifa_name)) 
		{
			continue;
		}
		if (!ifaddr->ifa_addr) 
		{
			continue;
		}
		if (ifaddr->ifa_addr->sa_family == AF_LINK) 
		{
			struct sockaddr_dl * sockaddr = (struct sockaddr_dl *) (ifaddr->ifa_addr);
			memcpy (memory, LLADDR (sockaddr), ETHER_ADDR_LEN);
			break;
		}
	}
	freeifaddrs (ifaddrs);

#elif defined (__OpenBSD__)

#include <ifaddrs.h>
#include <net/if_dl.h>

	struct ifaddrs *ifaddrs;
	struct ifaddrs *ifaddr;
	if (getifaddrs (&ifaddrs) == -1) 
	{
		error (1, errno, "No interfaces available");
	}
	for (ifaddr = ifaddrs; ifaddr; ifaddr = ifaddr->ifa_next) 
	{
		if (strcmp (device, ifaddr->ifa_name)) 
		{
			continue;
		}
		if (!ifaddr->ifa_addr) 
		{
			continue;
		}
		if (ifaddr->ifa_addr->sa_family == AF_LINK) 
		{
			struct sockaddr_dl * sockaddr = (struct sockaddr_dl *) (ifaddr->ifa_addr);
			memcpy (memory, LLADDR (sockaddr), ETHER_ADDR_LEN);
			break;
		}
	}
	freeifaddrs (ifaddrs);

#elif defined (WINPCAP) || defined (LIBPCAP)

	LPADAPTER adapter = PacketOpenAdapter ((PCHAR)(device));
	PPACKET_OID_DATA data = (PPACKET_OID_DATA)(malloc (ETHER_ADDR_LEN + sizeof (PACKET_OID_DATA)));
	if (!data) 
	{
		error (1, errno, "Can't allocate packet: %s", device);
	}
	data->Oid = OID_802_3_CURRENT_ADDRESS;
	data->Length = ETHER_ADDR_LEN;
	if ((adapter == 0) || (adapter->hFile == INVALID_HANDLE_VALUE)) 
	{
		error (1, errno, "Can't access interface: %s", device);
	}
	if (!PacketRequest (adapter, FALSE, data)) 
	{
		memset (memory, 0, ETHER_ADDR_LEN);
		PacketCloseAdapter (adapter);
		free (data);
		return (-1);
	}
	memcpy (memory, data->Data, data->Length);
	PacketCloseAdapter (adapter);
	free (data);

#else
#error "Unknown environment"
#endif

	return (0);
}
Ejemplo n.º 25
0
void PcapLiveDevice::setDeviceMacAddress()
{
#ifdef WIN32

	LPADAPTER adapter = PacketOpenAdapter((char*)m_Name);
	if (adapter == NULL)
	{
		LOG_ERROR("Error in retrieving MAC address: Adapter is NULL");
		return;
	}

	uint8_t buffer[512];
	PACKET_OID_DATA* oidData = (PACKET_OID_DATA*)buffer;
    oidData->Oid = OID_802_3_CURRENT_ADDRESS;
    oidData->Length = 6;
    oidData->Data[0] = 0;
    bool status = PacketRequest(adapter, false, oidData);
    if(status)
    {
        if(oidData->Length == 6)
        {
            /* copy value from driver */
        	m_MacAddress = MacAddress(oidData->Data[0], oidData->Data[1], oidData->Data[2], oidData->Data[3], oidData->Data[4], oidData->Data[5]);
        	LOG_DEBUG("   MAC address: %s", m_MacAddress.toString().c_str());
        } else
        {
            /* the driver returned a value that is longer than expected (and longer than the given buffer) */
        	LOG_DEBUG("Error in retrieving MAC address: Size of Oid larger than 6, OidLen:%lu", oidData->Length);
            return;
        }
    }
    else
    {
    	LOG_DEBUG("Error in retrieving MAC address: PacketRequest failed");
    }
#elif LINUX
	struct ifreq ifr;

	memset(&ifr, 0, sizeof(ifr));
	strncpy(ifr.ifr_name, m_Name, sizeof(ifr.ifr_name));

	int socketfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
	if (ioctl(socketfd, SIOCGIFHWADDR, &ifr) == -1)
	{
		LOG_DEBUG("Error in retrieving MAC address: ioctl() returned -1");
		return;
	}

    m_MacAddress = MacAddress(ifr.ifr_hwaddr.sa_data[0], ifr.ifr_hwaddr.sa_data[1], ifr.ifr_hwaddr.sa_data[2], ifr.ifr_hwaddr.sa_data[3], ifr.ifr_hwaddr.sa_data[4], ifr.ifr_hwaddr.sa_data[5]);
#elif MAC_OS_X
    int	mib[6];
    size_t len;

	mib[0] = CTL_NET;
	mib[1] = AF_ROUTE;
	mib[2] = 0;
	mib[3] = AF_LINK;
	mib[4] = NET_RT_IFLIST;
	mib[5] = if_nametoindex(m_Name);

	if ((mib[5] == 0)){
		LOG_ERROR("Error in retrieving MAC address: if_nametoindex error");
		return;
	}

	if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
		LOG_ERROR("Error in retrieving MAC address: sysctl 1 error");
		return;
	}

	uint8_t buf[len];

	if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
		LOG_ERROR("Error in retrieving MAC address: sysctl 2 error");
		return;
	}

	struct if_msghdr*ifm = (struct if_msghdr *)buf;
	struct sockaddr_dl* sdl = (struct sockaddr_dl *)(ifm + 1);
	uint8_t* ptr = (uint8_t*)LLADDR(sdl);
	m_MacAddress = MacAddress(ptr[0], ptr[1], ptr[2], ptr[3], ptr[4], ptr[5]);
#endif
}
Ejemplo n.º 26
0
/**
 * Initialise WinPcap and return our MAC address.
 */
int pkt_eth_init (mac_address *mac_addr)
{
  struct {
    PACKET_OID_DATA oidData;
    char            descr[512];
  } oid;
  const ADAPTER *adapter = NULL;
  DWORD thread_id;
  BOOL  is_up;

  if (_watt_is_win9x)  /**< \todo Support Win-9x too */
  {
    (*_printf) (_LANG("Win-NT or later reqired.\n"));
    _pkt_errno = PDERR_GEN_FAIL;
    return (WERR_ILL_DOSX);
  }

  if (!_watt_no_config || _watt_user_config_fn)
     parse_config_pass_1();

  _pkt_inf = calloc (sizeof(*_pkt_inf), 1);
  if (!_pkt_inf)
  {
    (*_printf) (_LANG("Failed to allocate WinPcap DRIVER data.\n"));
    _pkt_errno = PDERR_GEN_FAIL;
    return (WERR_NO_MEM);
  }

  if (debug_on >= 2 && dump_fname[0])
     dump_file = fopen_excl (ExpandVarStr(dump_fname), "w+t");

  if (!PacketInitModule(TRUE, dump_file))
  {
    (*_printf) (_LANG("Failed to initialise WinPcap.\n"));
    pkt_release();
    _pkt_errno = PDERR_NO_DRIVER;
    return (WERR_PKT_ERROR);
  }

  if (!_pktdrvrname[0] &&
      !find_adapter(_pktdrvrname,sizeof(_pktdrvrname)))
  {
    (*_printf) (_LANG("No WinPcap driver found.\n"));
    _pkt_errno = PDERR_NO_DRIVER;
    return (WERR_NO_DRIVER);
  }

  TCP_CONSOLE_MSG (2, ("device %s\n", _pktdrvrname));

  adapter = PacketOpenAdapter (_pktdrvrname);
  if (!adapter)
  {
    if (debug_on > 0)
       (*_printf) (_LANG("PacketOpenAdapter (\"%s\") failed; %s\n"),
                   _pktdrvrname, win_strerror(GetLastError()));
    pkt_release();
    return (WERR_NO_DRIVER);
  }

  _pkt_inf->adapter = adapter;
#if defined(USE_DYN_PACKET)
  _pkt_inf->adapter_info = NULL;
#else
  _pkt_inf->adapter_info = PacketFindAdInfo (_pktdrvrname);
#endif

  /* Query the NIC driver for the adapter description
   */
  memset (&oid, 0, sizeof(oid));
  oid.oidData.Oid    = OID_GEN_VENDOR_DESCRIPTION;
  oid.oidData.Length = sizeof(oid.descr);

  if (PacketRequest (adapter, FALSE, &oid.oidData))
     StrLcpy (_pktdrvr_descr, (char*)oid.oidData.Data, sizeof(_pktdrvr_descr));
  else
  {
    (*_printf) (_LANG("PacketRequest() failed; %s\n"),
                win_strerror(GetLastError()));
    pkt_release();
    return (WERR_PKT_ERROR);
  }

  if (!get_interface_type(&_pktdevclass))
  {
    pkt_release();
    return (WERR_PKT_ERROR);
  }

  if (get_connected_status(&is_up) && !is_up)
     (*_printf) (_LANG("Warning: the adapter %s is down\n"), _pktdrvrname);

  switch (_pktdevclass)
  {
    case PDCLASS_TOKEN:
         _pkt_ip_ofs = sizeof(tok_Header);
         break;
    case PDCLASS_ETHER:
         _pkt_ip_ofs = sizeof(eth_Header);
         break;
    case PDCLASS_FDDI:
         _pkt_ip_ofs = sizeof(fddi_Header);
         break;
    case PDCLASS_ARCNET:
         _pkt_ip_ofs = ARC_HDRLEN;
         break;
    default:
         pkt_release();
         (*_printf) (_LANG("WinPcap-ERROR: Unsupported driver class %dh\n"),
                     _pktdevclass);
         _pkt_errno = PDERR_NO_CLASS;
         return (WERR_PKT_ERROR);
  }

  if (!pkt_get_addr(mac_addr))  /* get our MAC address */
  {
    pkt_release();
    return (WERR_PKT_ERROR);
  }

  pktq_init (&_pkt_inf->pkt_queue,
             sizeof(_pkt_inf->rx_buf[0]),   /* RX_SIZE */
             DIM(_pkt_inf->rx_buf),         /* RX_BUFS */
             (char*)&_pkt_inf->rx_buf);

  _pkt_inf->npf_buf_size = RX_SIZE * pkt_num_rx_bufs;
  _pkt_inf->npf_buf = malloc (_pkt_inf->npf_buf_size);
  if (!_pkt_inf->npf_buf)
  {
    (*_printf) (_LANG("Failed to allocate %d byte Rx buffer.\n"),
                _pkt_inf->npf_buf_size);
    pkt_release();
    _pkt_errno = PDERR_GEN_FAIL;
    return (WERR_NO_MEM);
  }

  PacketSetMode (adapter, PACKET_MODE_CAPT);
  PacketSetBuff (adapter, _pkt_inf->npf_buf_size);
  PacketSetMinToCopy (adapter, ETH_MIN);

  /* PacketReceivePacket() blocks until something is received
   */
  PacketSetReadTimeout ((ADAPTER*)adapter, 0);

  /* Set Rx-mode forced via config.
   */
  if (_pkt_forced_rxmode != -1)
  {
    _pkt_forced_rxmode &= 0xFFFF;     /* clear bits not set via ARG_ATOX_W */
    if (_pkt_forced_rxmode == 0 ||    /* check illegal bit-values */
        (_pkt_forced_rxmode & 0x10) ||
        (_pkt_forced_rxmode & 0x40) ||
        (_pkt_forced_rxmode > 0x80))
     {
       TCP_CONSOLE_MSG (0, ("Illegal Rx-mode (0x%02X) specified\n",
                        _pkt_forced_rxmode));
       _pkt_forced_rxmode = -1;
     }
  }

  if (pkt_get_rcv_mode())
     _pkt_rxmode0 = _pkt_rxmode;

  if (_pkt_forced_rxmode != -1)
       pkt_set_rcv_mode (_pkt_forced_rxmode);
  else pkt_set_rcv_mode (RXMODE_DEFAULT);

#if 1
  _pkt_inf->recv_thread = CreateThread (NULL, 2048, pkt_recv_thread,
                                        NULL, 0, &thread_id);
#else
  _pkt_inf->recv_thread = _beginthreadex (NULL, 2048, pkt_recv_thread,
                                          NULL, 0, &thread_id);
#endif

  if (!_pkt_inf->recv_thread)
  {
    (*_printf) (_LANG("Failed to create receiver thread; %s\n"),
                win_strerror(GetLastError()));
    pkt_release();
    _pkt_errno = PDERR_GEN_FAIL;
    return (WERR_PKT_ERROR);
  }

  if (thr_realtime)
     SetThreadPriority (_pkt_inf->recv_thread,
                        THREAD_PRIORITY_TIME_CRITICAL);

  TCP_CONSOLE_MSG (2, ("capture thread-id %lu\n", thread_id));

#if defined(USE_DEBUG)
  if (debug_on >= 2)
  {
    (*_printf) ("link-details:\n");
    show_link_details();
  }
#endif
  return (0);
}
Ejemplo n.º 27
0
Archivo: pktdrv.c Proyecto: 10code/lwip
/**
 * Open a network adapter and set it up for packet input
 *
 * @param adapter_num the index of the adapter to use
 * @param mac_addr the MAC address of the adapter is stored here (if != NULL)
 * @param input a function to call to receive a packet
 * @param arg argument to pass to input
 * @param linkstate the initial link state
 * @return an adapter handle on success, NULL on failure
 */
void*
init_adapter(int adapter_num, char *mac_addr, input_fn input, void *arg, enum link_adapter_event *linkstate)
{
  char *AdapterList[MAX_NUM_ADAPTERS];
#ifndef PACKET_LIB_QUIET
  int i;
#endif /* PACKET_LIB_QUIET */
  char AdapterName[ADAPTER_NAME_LEN]; /* string that contains a list of the network adapters */
  int AdapterNum;
  PPACKET_OID_DATA ppacket_oid_data;
  unsigned char ethaddr[ETHARP_HWADDR_LEN];
  struct packet_adapter *pa;
  NDIS_MEDIA_STATE mediastate;
  
  pa = (struct packet_adapter *)malloc(sizeof(struct packet_adapter));
  if (!pa) {
    printf("Unable to alloc the adapter!\n");
    return NULL;
  }

  memset(pa, 0, sizeof(struct packet_adapter));
  pa->input = input;
  pa->input_fn_arg = arg;

  AdapterNum = get_adapter_list(AdapterList, MAX_NUM_ADAPTERS, AdapterName, ADAPTER_NAME_LEN);

  /* print all adapter names */
  if (AdapterNum <= 0) {
    free(pa);
    return NULL; /* no adapters found */
  }
#ifndef PACKET_LIB_QUIET
  for (i = 0; i < AdapterNum; i++) {
    LPADAPTER lpAdapter;
    printf("%2i: %s\n", i, AdapterList[i]);
    /* set up the selected adapter */
    lpAdapter = PacketOpenAdapter(AdapterList[i]);
    if (lpAdapter && (lpAdapter->hFile != INVALID_HANDLE_VALUE)) {
      ppacket_oid_data = (PPACKET_OID_DATA)malloc(sizeof(PACKET_OID_DATA) + PACKET_OID_DATA_SIZE);
      if (ppacket_oid_data) {
        ppacket_oid_data->Oid = OID_GEN_VENDOR_DESCRIPTION;
        ppacket_oid_data->Length = PACKET_OID_DATA_SIZE;
        if (PacketRequest(lpAdapter, FALSE, ppacket_oid_data)) {
          printf("     Name: \"%s\"\n", ppacket_oid_data->Data);
        }
        free(ppacket_oid_data);
      }
      PacketCloseAdapter(lpAdapter);
      lpAdapter = NULL;
    }
  }
#endif /* PACKET_LIB_QUIET */
  /* invalid adapter index -> check this after printing the adapters */
  if (adapter_num < 0) {
    printf("Invalid adapter_num: %d\n", adapter_num);
    free(pa);
    return NULL;
  }
  /* adapter index out of range */
  if (adapter_num >= AdapterNum) {
    printf("Invalid adapter_num: %d\n", adapter_num);
    free(pa);
    return NULL;
  }
#ifndef PACKET_LIB_QUIET
  printf("Using adapter_num: %d\n", adapter_num);
#endif /* PACKET_LIB_QUIET */
  /* set up the selected adapter */
  pa->lpAdapter = PacketOpenAdapter(AdapterList[adapter_num]);
  if (!pa->lpAdapter || (pa->lpAdapter->hFile == INVALID_HANDLE_VALUE)) {
    free(pa);
    return NULL;
  }
  /* alloc the OID packet  */
  ppacket_oid_data = (PPACKET_OID_DATA)malloc(sizeof(PACKET_OID_DATA) + PACKET_OID_DATA_SIZE);
  if (!ppacket_oid_data) {
    PacketCloseAdapter(pa->lpAdapter);
    free(pa);
    return NULL;
  }
  /* get the description of the selected adapter */
  ppacket_oid_data->Oid = OID_GEN_VENDOR_DESCRIPTION;
  ppacket_oid_data->Length = PACKET_OID_DATA_SIZE;
  if (PacketRequest(pa->lpAdapter, FALSE, ppacket_oid_data)) {
    printf("Using adapter: \"%s\"", ppacket_oid_data->Data);
  }
  /* get the MAC address of the selected adapter */
  ppacket_oid_data->Oid = OID_802_3_PERMANENT_ADDRESS;
  ppacket_oid_data->Length = ETHARP_HWADDR_LEN;
  if (!PacketRequest(pa->lpAdapter, FALSE, ppacket_oid_data)) {
    printf("ERROR getting the adapter's HWADDR, maybe it's not an ethernet adapter?\n");
    PacketCloseAdapter(pa->lpAdapter);
    free(pa);
    return NULL;
  }
  /* copy the MAC address */
  memcpy(&ethaddr, ppacket_oid_data->Data, ETHARP_HWADDR_LEN);
  free(ppacket_oid_data);
  if (mac_addr != NULL) {
    /* copy the MAC address to the user supplied buffer, also */
    memcpy(mac_addr, &ethaddr, ETHARP_HWADDR_LEN);
  }
  printf(" [MAC: %02X:%02X:%02X:%02X:%02X:%02X]\n", ethaddr[0], ethaddr[1], ethaddr[2],
          ethaddr[3], ethaddr[4], ethaddr[5]);
  /* some more adapter settings */
  PacketSetBuff(pa->lpAdapter, PACKET_ADAPTER_BUFSIZE);
  PacketSetReadTimeout(pa->lpAdapter, 1);
  PacketSetHwFilter(pa->lpAdapter, NDIS_PACKET_TYPE_ALL_LOCAL | NDIS_PACKET_TYPE_PROMISCUOUS);
  /* set up packet descriptor (the application input buffer) */
  if ((pa->lpPacket = PacketAllocatePacket()) == NULL) {
    printf("ERROR setting up a packet descriptor\n");
    PacketCloseAdapter(pa->lpAdapter);
    free(pa);
    return NULL;
  }
  PacketInitPacket(pa->lpPacket,(char*)pa->buffer, sizeof(pa->buffer));

  if(get_link_state(pa, &mediastate)) {
    *linkstate = (mediastate == NdisMediaStateConnected ? LINKEVENT_UP : LINKEVENT_DOWN);
  }

  return pa;
}
Ejemplo n.º 28
0
BOOLEAN PacketGetAdapterNames (PTSTR pStr,
				PULONG BufferSize)
{
    ULONG		Result,i;
    LONG		Status;
	char*		pStrInternal;
	
	ULONG		RemainingBytes;

	LPADAPTER	adapter;
    PPACKET_OID_DATA  OidData;
    HKEY		Key;
	char		NdisName[80];
	ULONG		NeededBytes;
	ULONG		NeededBytesForString;
	char		TempBuffer[1024];
	BOOLEAN		retVal;

	OidData=GlobalAllocPtr(GMEM_MOVEABLE | GMEM_ZEROINIT,256);
    if (OidData == NULL) 
	{
        return FALSE;
    }

    Status=RegOpenKeyEx(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\Services\\class\\net",0,KEY_READ,&Key);
    
	if (Status != ERROR_SUCCESS) 
	{
		GlobalFree(OidData);
		return FALSE;
	}

	NeededBytes = 0;

	//first we calculate the needed bytes
	i=0;
	while((Result=RegEnumKey(Key,i,NdisName,sizeof(NdisName) - sizeof("\\NDIS") - 1))==ERROR_SUCCESS)
	{
		HKEY hKeyNdisName;
		strcat(NdisName,"\\NDIS");

		Status=RegOpenKeyEx(Key,NdisName,0,KEY_READ,&hKeyNdisName);
		
		if (Status != ERROR_SUCCESS)
		{
			i++;
			continue;
		}

		//we need to tell RegOpenKeyEx the length of the buffer passed as argument
		NeededBytesForString = sizeof(TempBuffer);

        Status=RegQueryValueEx(hKeyNdisName,"LOGDRIVERNAME",NULL,NULL,(LPBYTE)TempBuffer,&NeededBytesForString);
		
		if (Status != ERROR_SUCCESS)
		{
			RegCloseKey(hKeyNdisName);
			i++;
			continue;
		}

		NeededBytes += NeededBytesForString;

		//we try to open the adapter and retrieve its name
		adapter=PacketOpenAdapter(TempBuffer);
		if(adapter==NULL)
		{
			NeededBytes += sizeof("Unknown") + 1;
		}
		else
		{
			//we retrieve its name by performing a PacketRequest, 
			//the buffer that will contain the name is at the end of the OidData structure
			OidData->Oid = OID_GEN_VENDOR_DESCRIPTION;
			OidData->Length = 256 - sizeof(PACKET_OID_DATA);
			Status = PacketRequest(adapter,FALSE,OidData);
			if(Status==0)
			{
				NeededBytes += sizeof("Unknown") + 1;
			}
			else
			{
				NeededBytes += strlen((char*) OidData->Data) + 1;
			}
			
			PacketCloseAdapter(adapter);
		
		}

		i++;
		RegCloseKey(hKeyNdisName);
	}

	NeededBytes += 1 + 1;  //the two nulls at the end of each block of strings

	if (NeededBytes > *BufferSize || pStr == NULL || Result != ERROR_NO_MORE_ITEMS)
	{
		*BufferSize = NeededBytes;
		GlobalFree(OidData);
		RegCloseKey(Key);

		SetLastError(ERROR_INSUFFICIENT_BUFFER);
		return FALSE;
	}

	//now we copy the strings

	retVal = TRUE;
	NeededBytes = 0;
	i = 0;
	pStrInternal = pStr;
	RemainingBytes = *BufferSize;
	while((Result=RegEnumKey(Key,i,NdisName,sizeof(NdisName) - sizeof("\\NDIS") - 1))==ERROR_SUCCESS)
	{
		HKEY hKeyNdisName;
		strcat(NdisName,"\\NDIS");
		NeededBytesForString = sizeof(TempBuffer);

		Status=RegOpenKeyEx(Key,NdisName,0,KEY_READ,&hKeyNdisName);
		
		if (Status != ERROR_SUCCESS)
		{
			i++;
			continue;
		}

		Status=RegQueryValueEx(hKeyNdisName,"LOGDRIVERNAME",NULL,NULL,(LPBYTE)TempBuffer,&NeededBytesForString);
		
		if (Status == ERROR_SUCCESS && NeededBytesForString <= RemainingBytes)
		{
			//this copy is safe, since we have checked that the available space will fit the string
			strcpy(pStrInternal, TempBuffer);
			pStrInternal += NeededBytesForString;
			RemainingBytes -= NeededBytesForString;
		}

		NeededBytes += NeededBytesForString; //just in case the second scan returns a larger number of adapters!!

		i++;
		RegCloseKey(hKeyNdisName);
	}
	
	RegCloseKey(Key);
		
	//we need to properly terminate the list of adapter names with another \0
	if (RemainingBytes > 0)
	{
		pStrInternal[0] = 0;
		pStrInternal++;
		RemainingBytes--;
	}
	NeededBytes++;

	while (*pStr != 0)  //now we scan again the list of adapters in pStr to retrieve their names
	{
		adapter=PacketOpenAdapter(pStr);
		if(adapter==NULL)
		{
			if ( RemainingBytes < sizeof("Unknown") + 1 )
				retVal = FALSE;		//we do not copy anything, we simply skip this adapter, and return failure
			else
			{	//this copy is safe as we have checked that the remaining bytes will fit the source string
				strcpy(pStrInternal, "Unknown");
				//we move the pointer of the list of adapter names
				pStrInternal += sizeof("Unknown") + 1;
				RemainingBytes -= sizeof("Unknown") + 1;
			}
			
			//we continue to keep track of available bytes. This is used if we fail in this phase
			NeededBytes += sizeof("Unknown") + 1;  
		}
		else
		{	
			OidData->Oid = OID_GEN_VENDOR_DESCRIPTION;
			OidData->Length = 256 - sizeof(PACKET_OID_DATA);
			Status = PacketRequest(adapter,FALSE,OidData);
			if(Status==0)
			{
				if ( RemainingBytes < sizeof("Unknown") + 1 )
					retVal = FALSE;	//we do not copy anything, we simply skip this adapter, and return failure
				else
				{	//this copy is safe as we have checked that the remaining bytes will fit the source string
					strcpy(pStrInternal, "Unknown");
					//we move the pointer of the list of adapter names
					pStrInternal += sizeof("Unknown") + 1;
					RemainingBytes -= sizeof("Unknown") + 1;
				}
				
				//we continue to keep track of available bytes. This is used if we fail in this phase
				NeededBytes += sizeof("Unknown") + 1;
			}
			else
			{
				if ( RemainingBytes < strlen((char*) OidData->Data) + 1 )
					retVal = FALSE; //we do not copy anything, we simply skip this adapter, and return failure
				else
				{
					//this copy is safe as we have checked that the remaining bytes will fit the source string
					strcpy(pStrInternal, (char*)OidData->Data);
					//we move the pointer of the list of adapter names
					pStrInternal += strlen((char*) OidData->Data) + 1;
					RemainingBytes -= strlen((char*) OidData->Data) + 1;
				}
				
				//we continue to keep track of available bytes. This is used if we fail in this phase
				NeededBytes += strlen((char*) OidData->Data) + 1;
			}
			
			PacketCloseAdapter(adapter);
		
		}
		
		//we move to the next adapter in the list. We end when we reach the double \0
		pStr += strlen(pStr) + 1;
	
	}


	//we need to properly terminate the list of adapter descriptions with another \0
	if (RemainingBytes > 0)
	{
		pStrInternal[0] = 0;
		pStrInternal++;
		RemainingBytes--;
	}
	else
		retVal = FALSE;
	
	NeededBytes++;

	*BufferSize = NeededBytes;

	GlobalFree(OidData);

	return retVal;
}
Ejemplo n.º 29
0
int main(int argc, char* argv[])
{

	// Packet.lib variables:
	LPADAPTER  lpAdapter = 0;
	PPACKET_OID_DATA pOidData = malloc( sizeof(PACKET_OID_DATA) + MAX_OID_DATA );
	NetType *type = malloc(sizeof(NetType));
	UINT speed_Mbps = 0;

	BOOL isWinNT = FALSE;
	int        i;

	DWORD dwVersion;
	DWORD dwWindowsMajorVersion;


	//unicode strings (winnt)
	WCHAR		AdapterName[8192]; // string that contains a list of the network adapters
	WCHAR		*temp,*temp1;

	//ascii strings (win95)
	char		AdapterNamea[8192]; // string that contains a list of the network adapters
	char		*tempa,*temp1a;


	int			AdapterNum=0,Open;
	unsigned long		AdapterLength;


	FILE * inifile;

	char		speed_value[10];
	char		*MAC_value = malloc( 13*sizeof(char) );
	char		*temp2 = malloc( 13*sizeof(char) );

	//interfaceArg specifies the interface # passed fron configchange.pl
	//set interfaceArg to argv[1] if arguments are passed
	int interfaceArg = 0;
	if ( argc>1 && argv[1] )
	{
		interfaceArg = atoi(argv[1]);
	}

	// obtain the name of the adapters installed on this machine
	//printf("Adapters installed:\n");
	i=0;

	// the data returned by PacketGetAdapterNames is different in Win95 and in WinNT.
	// We have to check the os on which we are running
	dwVersion=GetVersion();
	dwWindowsMajorVersion =  (DWORD)(LOBYTE(LOWORD(dwVersion)));
	if (!(dwVersion >= 0x80000000 && dwWindowsMajorVersion >= 4))
	{  // Windows NT
		isWinNT = TRUE;
		AdapterLength=sizeof(AdapterName);
		PacketGetAdapterNames((char*)AdapterName,&AdapterLength);
		temp=AdapterName;
		temp1=AdapterName;
		while ((*temp!='\0')||(*(temp-1)!='\0'))
		{
			if (*temp=='\0')
			{
				memcpy(AdapterList[i],temp1,(temp-temp1)*2);
				temp1=temp+1;
				i++;
			}

		temp++;
		}

		AdapterNum=i;
		// we want to automate the adaptor selection process
		// but if there are more than one to choose from, we can't
		// so
		if (AdapterNum>1)
		{
			for (i=0;i<AdapterNum;i++)
			{
				wprintf(L"\n%d- %s\n",i+1,AdapterList[i]);
   			}
			printf("\n");
  		}
	}
	else	//windows 95
	{
		AdapterLength=sizeof(AdapterNamea);
		PacketGetAdapterNames(AdapterNamea,&AdapterLength);
		tempa=AdapterNamea;
		temp1a=AdapterNamea;

		while ((*tempa!='\0')||(*(tempa-1)!='\0'))
		{
			if (*tempa=='\0')
			{
				memcpy(AdapterList[i],temp1a,tempa-temp1a);
				temp1a=tempa+1;
				i++;
			}
			tempa++;
		}

		AdapterNum=i;
		// we want to automate the adaptor selection process
		// but if there are more than one to choose from, we can't
		// so
		if (AdapterNum>1)
		{
			printf("Adapters installed:\n");
			for (i=0;i<AdapterNum;i++)
			{
				printf("\n%d- %s\n",i+1,AdapterList[i]);
   			}
			printf("\n");
  		}
	}

	// we want to automate the adaptor selection process
	// but if there are more than one to choose from, we can't
	// so
	//
	
	if (AdapterNum>1)
	{	
		if ( (interfaceArg>AdapterNum)||(interfaceArg<1) )
		{
			do
			{
				printf("Select the number of the adapter to use : ");scanf("%d",&Open);
				if (Open>AdapterNum) printf("\nThe number must be smaller than %d",AdapterNum);
			} while (Open>AdapterNum);
		}
		else
		{
			Open = interfaceArg;
		}
	}
	else
	{
		Open = AdapterNum;
 	}

	lpAdapter = PacketOpenAdapter(AdapterList[Open-1]);


	MAC_value[0] = '\0';
	temp2[0] = '\0';
	speed_value[0] = '\0';

	if( NULL != lpAdapter)
	{

		if ( TRUE == PacketGetNetType (lpAdapter, type) )
		{
			speed_Mbps = type->LinkSpeed / 1000000; // LinkSpeed is in bits per second
		}
		else
			printf("Could not read Ethernet card's speed\n");

		if ( type->LinkType != NdisMedium802_3)
			printf("NOT Ethernet802.3 card.\nNetwork Interface not supported\n");
		else
		{
			pOidData->Oid = OID_802_3_CURRENT_ADDRESS;

			pOidData->Length = MAX_OID_DATA;


			if ( TRUE == PacketRequest(lpAdapter, FALSE , pOidData) )
			{
				// get info obtained
//				printf("Physical address read: ");
	/*			printf("%x %x %x %x %x %x\n", pOidData->Data[0], pOidData->Data[1],
					pOidData->Data[2],pOidData->Data[3],
					pOidData->Data[4],pOidData->Data[5]
					);*/

				pOidData->Data[0] += 2; // changing address from global to local
				for( i=0; i<6; i++ )
				{
					strcpy( temp2, MAC_value);
					if( pOidData->Data[i] > 15 )
						// has 2 hex digits
						sprintf( MAC_value, "%s%x", temp2, pOidData->Data[i]);
					else
						sprintf( MAC_value, "%s0%x", temp2, pOidData->Data[i]);
				}
			}
			else
				printf("Failed to read physical address of Ethernet card\n");
		}

		free(pOidData);
		free(type);

		PacketCloseAdapter( lpAdapter );
	}
	else
	{
		// lpAdapter NULL
		printf("Problem with opening adapter (packet.lib issue)\n");
		return (1);
	}

	inifile = fopen(EPOC_INI_FILE, "a"); // to create if does exist
	if ( NULL != inifile )
		fclose(inifile);
	else
	{
		printf("Can't create or access %s.\n\n", EPOC_INI_FILE);
		return 0;
	}

	if ( 0 == replace_in_inifile( ETHER_NIF_ENTRY, AdapterList[Open-1], isWinNT ) )
		printf( "Netcards using adapter %d\n", Open );
	else
	{
		return 0;
	}


	if ( 0 != replace_in_inifile( ETHER_MAC_ENTRY, MAC_value, FALSE ) )
	{
		printf("Couldn't write MAC address to %s file\n", EPOC_INI_FILE);
		return (1);
	}


	if( 0 != speed_Mbps )
		sprintf( speed_value, "%dMbps", speed_Mbps);


	if ( 0 != replace_in_inifile( ETHER_SPEED_ENTRY, speed_value, FALSE ) )
	{
		printf("Couldn't write speed value to %s file\n", EPOC_INI_FILE);
		return (1);
	}

	//printf("Netcards has written settings to %s.\n\n", EPOC_INI_FILE);

	free(MAC_value);
	free(temp2);
	return (0);
}
Ejemplo n.º 30
0
int main()
{
	LPADAPTER	lpAdapter = 0;
	int			i;
	DWORD		dwErrorCode;
	char		AdapterName[8192];
	char		*temp,*temp1;
	int			AdapterNum=0,Open;
	ULONG		AdapterLength;
	PPACKET_OID_DATA  OidData;
	BOOLEAN		Status;
	
	//
	// Obtain the name of the adapters installed on this machine
	//

	printf("Packet.dll test application. Library version:%s\n", PacketGetVersion());
	
	printf("Adapters installed:\n");
	i=0;	
	
	AdapterLength = sizeof(AdapterName);
	
	if(PacketGetAdapterNames(AdapterName,&AdapterLength)==FALSE){
		printf("Unable to retrieve the list of the adapters!\n");
		return -1;
	}
	temp=AdapterName;
	temp1=AdapterName;

	while ((*temp!='\0')||(*(temp-1)!='\0'))
	{
		if (*temp=='\0') 
		{
			memcpy(AdapterList[i],temp1,temp-temp1);
			temp1=temp+1;
			i++;
		}
		temp++;
	}
		  
	AdapterNum=i;
	for (i=0;i<AdapterNum;i++)
		printf("\n%d- %s\n",i+1,AdapterList[i]);
	printf("\n");


	do 
	{
		printf("Select the number of the adapter to open : ");
		scanf_s("%d",&Open);
		if (Open>AdapterNum) printf("\nThe number must be smaller than %d",AdapterNum); 
	} while (Open>AdapterNum);
	

	//
	// Open the selected adapter
	//

	lpAdapter =   PacketOpenAdapter(AdapterList[Open-1]);
	
	if (!lpAdapter || (lpAdapter->hFile == INVALID_HANDLE_VALUE))
	{
		dwErrorCode=GetLastError();
		printf("Unable to open the adapter, Error Code : %lx\n",dwErrorCode); 

		return -1;
	}	

	// 
	// Allocate a buffer to get the MAC adress
	//

	OidData = malloc(6 + sizeof(PACKET_OID_DATA));
	if (OidData == NULL) 
	{
		printf("error allocating memory!\n");
		PacketCloseAdapter(lpAdapter);
		return -1;
	}

	// 
	// Retrieve the adapter MAC querying the NIC driver
	//

	OidData->Oid = OID_802_3_CURRENT_ADDRESS;

	OidData->Length = 6;
	ZeroMemory(OidData->Data, 6);
	
	Status = PacketRequest(lpAdapter, FALSE, OidData);
	if(Status)
	{
		printf("The MAC address of the adapter is %.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n",
			(OidData->Data)[0],
			(OidData->Data)[1],
			(OidData->Data)[2],
			(OidData->Data)[3],
			(OidData->Data)[4],
			(OidData->Data)[5]);
	}
	else
	{
		printf("error retrieving the MAC address of the adapter!\n");
	}

	free(OidData);
	PacketCloseAdapter(lpAdapter);
	return (0);
}