Exemple #1
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;
}
Exemple #2
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;
}
Exemple #3
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;
}
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;
}
Exemple #5
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;
}
Exemple #6
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);
}
Exemple #7
0
int pkt_release (void)
{
  ADAPTER *adapter;
  DWORD    status = 1;

  if (!_pkt_inf || _watt_fatal_error)
     return (0);

  adapter = (ADAPTER*) _pkt_inf->adapter;

  TCP_CONSOLE_MSG (2, ("pkt_release(): adapter %08lX\n", (DWORD)adapter));

  if (adapter && adapter != INVALID_HANDLE_VALUE)
  {
    /* Don't close the adapter before telling the thread about it.
     */
    if (_pkt_inf->recv_thread)
    {
      FILETIME ctime, etime, ktime, utime;
      DWORD    err = 0;

      _pkt_inf->stop_thread = TRUE;
      SetEvent (adapter->ReadEvent);
      Sleep (50);

      GetExitCodeThread (_pkt_inf->recv_thread, &status);
      if (status == STILL_ACTIVE)
           TCP_CONSOLE_MSG (2, ("pkt_release(): killing thread.\n"));
      else TCP_CONSOLE_MSG (2, ("pkt_release(): thread exit code %lu.\n",
                            status));

      if (!GetThreadTimes (_pkt_inf->recv_thread, &ctime, &etime, &ktime, &utime))
         err = GetLastError();
      TerminateThread (_pkt_inf->recv_thread, 1);
      CloseHandle (_pkt_inf->recv_thread);

      if (err)
         TCP_CONSOLE_MSG (2, ("  GetThreadTime() %s, ", win_strerror(err)));
      TCP_CONSOLE_MSG (2, ("  kernel time %.6fs, user time %.6fs\n",
                       filetime_sec(&ktime), filetime_sec(&utime)));
    }

    PacketCloseAdapter (adapter);

    _pkt_inf->adapter = NULL;
  }

  DO_FREE (_pkt_inf->npf_buf);
  DO_FREE (_pkt_inf);

  PacketInitModule (FALSE, dump_file);
  if (dump_file)
     fclose (dump_file);
  dump_file = NULL;
  return (int) status;
}
//关闭网络网卡
void NetworkInterface::PacketClose(LPADAPTER &lpAdapter, LPPACKET &lpPacket)
{
	//free a PACKET structure
	delete (lpPacket->Buffer);
	lpPacket->Length = 0;
	PacketFreePacket(lpPacket);
	
	//关闭网卡并退出
	PacketCloseAdapter(lpAdapter);
}
Exemple #9
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;
}
void pcapifh_linkstate_close(struct pcapifh_linkstate* state)
{
    if (state != NULL) {
        if (state->lpAdapter != NULL) {
            PacketCloseAdapter(state->lpAdapter);
        }
        if (state->ppacket_oid_data != NULL) {
            free(state->ppacket_oid_data);
        }
        free(state);
    }
}
Exemple #11
0
eth_t *
eth_close(eth_t *eth)
{
	if (eth != NULL) {
		if (eth->pkt != NULL)
			PacketFreePacket(eth->pkt);
		if (eth->lpa != NULL)
			PacketCloseAdapter(eth->lpa);
		free(eth);
	}
	return (NULL);
}
//通过适配器名字获取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;

}
Exemple #13
0
/**
 * Close the adapter (no more packets can be sent or received)
 *
 * @param adapter adapter handle received by a call to init_adapter, invalid on return
 */
void
shutdown_adapter(void *adapter)
{
  struct packet_adapter *pa = (struct packet_adapter*)adapter;
  if (pa != NULL) {
    if (pa->lpPacket) {
      PacketFreePacket(pa->lpPacket);
    }
    if (pa->lpAdapter) {
      PacketCloseAdapter(pa->lpAdapter);
    }
    free(pa);
  }
}
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);
}
Exemple #15
0
eth_t *
eth_close(eth_t *eth)
{
  HANDLE pcapMutex;
  DWORD wait;
	if (eth != NULL) {
		if (eth->pkt != NULL)
			PacketFreePacket(eth->pkt);
		if (eth->lpa != NULL)
    {
      pcapMutex = CreateMutex(NULL, 0, "Global\\DnetPcapHangAvoidanceMutex");
      wait = WaitForSingleObject(pcapMutex, INFINITE);
			PacketCloseAdapter(eth->lpa);
      if (wait == WAIT_ABANDONED || wait == WAIT_OBJECT_0) {
        ReleaseMutex(pcapMutex);
      }
      CloseHandle(pcapMutex);
    }
		free(eth);
	}
	return (NULL);
}
Exemple #16
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 */
}
Exemple #17
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);
}
Exemple #18
0
void sockClose() {
	PacketCloseAdapter(lpAdapter);
}
Exemple #19
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);
}
Exemple #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();
}
Exemple #21
0
void ether_exit(void)
{
	D(bug("EtherExit\n"));

	// Stop reception thread
	thread_active = false;

	if(int_ack) ReleaseSemaphore(int_ack,1,NULL);
	if(int_sig) ReleaseSemaphore(int_sig,1,NULL);
	if(int_sig2) ReleaseSemaphore(int_sig2,1,NULL);
	if(int_send_now) ReleaseSemaphore(int_send_now,1,NULL);

	D(bug("CancelIO if needed\n"));
	if (fd && fd->hFile && pfnCancelIo)
		pfnCancelIo(fd->hFile);

	// Wait max 2 secs to shut down pending io. After that, kill them.
	D(bug("Wait delay\n"));
	for( int i=0; i<10; i++ ) {
		if(!thread_active_1 && !thread_active_2 && !thread_active_3) break;
		Sleep(200);
	}

	if(thread_active_1) {
		D(bug("Ether killing ether_th1\n"));
		if(ether_th1) TerminateThread(ether_th1,0);
		thread_active_1 = false;
	}
	if(thread_active_2) {
		D(bug("Ether killing ether_th2\n"));
		if(ether_th2) TerminateThread(ether_th2,0);
		thread_active_2 = false;
	}
	if(thread_active_3) {
		D(bug("Ether killing thread\n"));
		if(ether_th) TerminateThread(ether_th,0);
		thread_active_3 = false;
	}

	ether_th1 = 0;
	ether_th2 = 0;
	ether_th = 0;

	D(bug("Closing semaphores\n"));
	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;
	}

	// Close ethernet device
	if (fd) {
		switch (net_if_type) {
		case NET_IF_B2ETHER:
			PacketCloseAdapter(fd);
			break;
		case NET_IF_TAP:
			tap_close_adapter(fd);
			break;
		}
		fd = 0;
	}

	// Remove all protocols
	D(bug("Removing protocols\n"));
	NetProtocol *p = prot_list;
	while (p) {
		NetProtocol *next = p->next;
		delete p;
		p = next;
	}
	prot_list = 0;

	D(bug("Deleting sections\n"));
	DeleteCriticalSection( &fetch_csection );
	DeleteCriticalSection( &queue_csection );
	DeleteCriticalSection( &send_csection );
	DeleteCriticalSection( &wpool_csection );

	D(bug("Freeing read packets\n"));
	free_read_packets();

	D(bug("Freeing write packets\n"));
	free_write_packets();

	D(bug("Finalizing queue\n"));
	final_queue();

	if (net_if_type == NET_IF_ROUTER) {
		D(bug("Stopping router\n"));
		router_final();
	}

	D(bug("EtherExit done\n"));
}
Exemple #22
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;
}
Exemple #23
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;
}
Exemple #24
0
pcap_t *
pcap_open_live(const char *device, int snaplen, int promisc, int to_ms,
    char *ebuf)
{
	register pcap_t *p;
	NetType type;

#ifdef REMOTE
	/*
		Retrofit; we have to make older applications compatible with the remote capture
		So, we're calling the pcap_open_remote() from here, that is a very dirty thing.
		Obviously, we cannot exploit all the new features; for instance, we cannot
		send authentication, we cannot use a UDP data connection, and so on.
	*/

	char host[PCAP_BUF_SIZE + 1];
	char port[PCAP_BUF_SIZE + 1];
	char name[PCAP_BUF_SIZE + 1];
	int srctype;

	if (pcap_parsesrcstr(device, &srctype, host, port, name, ebuf) )
		return NULL;

	if (srctype == PCAP_SRC_IFREMOTE)
	{
		p= pcap_opensource_remote(device, NULL, ebuf);

		if (p == NULL) 
			return NULL;

		p->snapshot= snaplen;
		p->timeout= to_ms;
		p->rmt_flags= (promisc) ? PCAP_OPENFLAG_PROMISCUOUS : 0;

		return p;
	}
#endif

	/* Init WinSock */
	wsockinit();

	p = (pcap_t *)malloc(sizeof(*p));
	if (p == NULL) {
		snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s", pcap_strerror(errno));
		return (NULL);
	}
	memset(p, 0, sizeof(*p));
	p->adapter=NULL;

	p->adapter=PacketOpenAdapter(device);
	if (p->adapter==NULL) {
		snprintf(ebuf, PCAP_ERRBUF_SIZE, "Error opening adapter: %s", pcap_win32strerror());
		return NULL;
	}

	/*get network type*/
	if(PacketGetNetType (p->adapter,&type)==FALSE)
	{
		snprintf(ebuf, PCAP_ERRBUF_SIZE, "Cannot determine the network type: %s", pcap_win32strerror());
		goto bad;
	}
	
	/*Set the linktype*/
	switch (type.LinkType) {

	case NdisMediumWan:
		p->linktype = DLT_EN10MB;
	break;

	case NdisMedium802_3:
		p->linktype = DLT_EN10MB;
	break;

	case NdisMediumFddi:
		p->linktype = DLT_FDDI;
	break;

	case NdisMedium802_5:			
		p->linktype = DLT_IEEE802;	
	break;

	case NdisMediumArcnetRaw:
		p->linktype = DLT_ARCNET;
	break;

	case NdisMediumArcnet878_2:
		p->linktype = DLT_ARCNET;
	break;

	case NdisMediumAtm:
		p->linktype = DLT_ATM_RFC1483;
	break;

	default:
		p->linktype = DLT_EN10MB;			/*an unknown adapter is assumed to be ethernet*/
	break;
	}

	/* Set promisquous mode */
	if (promisc) PacketSetHwFilter(p->adapter,NDIS_PACKET_TYPE_PROMISCUOUS);
	 else PacketSetHwFilter(p->adapter,NDIS_PACKET_TYPE_ALL_LOCAL);

	/* Set the buffer size */
	p->bufsize = PcapBufSize;

	p->buffer = (u_char *)malloc(PcapBufSize);
	if (p->buffer == NULL) {
		snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s", pcap_strerror(errno));
		goto bad;
	}

	p->snapshot = snaplen;

	/* allocate Packet structure used during the capture */
	if((p->Packet = PacketAllocatePacket())==NULL){
		snprintf(ebuf, PCAP_ERRBUF_SIZE, "failed to allocate the PACKET structure");
		goto bad;
	}

	PacketInitPacket(p->Packet,(BYTE*)p->buffer,p->bufsize);

	/* allocate the standard buffer in the driver */
	if(PacketSetBuff( p->adapter, SIZE_BUF)==FALSE)
	{
		snprintf(ebuf, PCAP_ERRBUF_SIZE,"driver error: not enough memory to allocate the kernel buffer\n");
		goto bad;
	}

	/* tell the driver to copy the buffer only if it contains at least 16K */
	if(PacketSetMinToCopy(p->adapter,16000)==FALSE)
	{
		snprintf(ebuf, PCAP_ERRBUF_SIZE,"Error calling PacketSetMinToCopy: %s\n", pcap_win32strerror());
		goto bad;
	}

	PacketSetReadTimeout(p->adapter, to_ms);

	return (p);
bad:
	if (p->adapter)
	    PacketCloseAdapter(p->adapter);
	if (p->buffer != NULL)
		free(p->buffer);
	free(p);
	return (NULL);
}
Exemple #25
0
/**
 * 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;
}
Exemple #26
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);
}
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);
}
Exemple #28
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);
}