Ejemplo n.º 1
0
void checkpackets() // check for and process packets
{

	PacketReceivePacket(lpAdapter,lpPacket,TRUE);	


	char *data;
	data = (char *)lpPacket->Buffer;
	int tbytes;
	tbytes = lpPacket->ulBytesReceived;
	int reader = 0;
	while(reader < tbytes)
	{
		bpf_hdr *header;
		header=(struct bpf_hdr *)(data+reader);
		int datalength = header->bh_datalen;
		int totallength = header->bh_caplen;
		reader = reader + header->bh_hdrlen;
		char *readme;
		readme = data+reader;
		printpacket((unsigned char *)readme, datalength);
		reader = Packet_WORDALIGN(reader+datalength);
	}



}
Ejemplo n.º 2
0
static unsigned int WINAPI ether_thread_get_packets_nt(void *arg)
{
	static uint8 packet[1514];
	int i, packet_sz = 0;

	thread_active_2 = true;

	D(bug("ether_thread_get_packets_nt start\n"));

	// Wait for packets to arrive.
	// Obey the golden rules; keep the reads pending.
	while(thread_active) {

		if(net_if_type == NET_IF_B2ETHER || net_if_type == NET_IF_TAP) {
			D(bug("Pending reads\n"));
			for( i=0; thread_active && i<PACKET_POOL_COUNT; i++ ) {
				if(packets[i]->free) {
					packets[i]->free = FALSE;
					BOOLEAN Result;
					switch (net_if_type) {
					case NET_IF_B2ETHER:
						Result = PacketReceivePacket(fd, packets[i], FALSE);
						break;
					case NET_IF_TAP:
						Result = tap_receive_packet(fd, packets[i], FALSE);
						break;
					}
					if (Result) {
						if(packets[i]->bIoComplete) {
							D(bug("Early io completion...\n"));
							packet_read_completion(
								ERROR_SUCCESS,
								packets[i]->BytesReceived,
								&packets[i]->OverLapped
								);
						}
					} else {
						packets[i]->free = TRUE;
					}
				}
			}
		}

		if(thread_active && has_no_completed_io()) {
			D(bug("Waiting for int_sig2\n"));
			// "problem": awakens twice in a row. Fix if you increase the pool size.
			WaitForSingleObjectEx(int_sig2,INFINITE,TRUE);
		}
	}

	D(bug("ether_thread_get_packets_nt exit\n"));

	thread_active_2 = false;

	return 0;
}
Ejemplo n.º 3
0
void bx_win32_pktmover_c::rx_timer(void)
{
    // Recieve Packet ????
    char           *pBuf;
    unsigned char  *pPacket;
    unsigned int   iOffset = 0;
    struct bpf_hdr *hdr;
    int pktlen;

    PacketInitPacket(pkRecv, (char *)buffer, 256000);
    if (WaitForSingleObject(lpAdapter->ReadEvent,0) == WAIT_OBJECT_0 || IsNT) {
        PacketReceivePacket(lpAdapter, pkRecv, TRUE);
        pBuf = (char *)pkRecv->Buffer;
        iOffset = 0;
        while(iOffset < pkRecv->ulBytesReceived)
        {
            hdr = (struct bpf_hdr *)(pBuf + iOffset);
            pPacket = (unsigned char *)(pBuf + iOffset + hdr->bh_hdrlen);
            if (memcmp(pPacket + 6, cMacAddr, 6) != 0) // src field != ours
            {
                if(memcmp(pPacket, cMacAddr, 6) == 0 || memcmp(pPacket, broadcast_macaddr, 6) == 0)
                {
                    pktlen = hdr->bh_caplen;
                    if (pktlen < 60) pktlen = 60;
#if BX_ETH_WIN32_LOGGING
                    fprintf (pktlog_txt, "a packet from host to guest, length %u\n", pktlen);
                    Bit8u *charbuf = (Bit8u *)pPacket;
                    int n;
                    for (n=0; n<pktlen; n++) {
                        if (((n % 16) == 0) && n>0)
                            fprintf (pktlog_txt, "\n");
                        fprintf (pktlog_txt, "%02x ", (unsigned)charbuf[n]);
                    }
                    fprintf (pktlog_txt, "\n--\n");
                    fflush (pktlog_txt);
#endif
                    (*rx_handler)(rx_Arg, pPacket, pktlen);
                }
            }
            iOffset = Packet_WORDALIGN(iOffset + (hdr->bh_hdrlen + hdr->bh_caplen));
        }
    }
}
Ejemplo n.º 4
0
void SniffPacketThread::Run()
{
	u_int tlen = 0, offset = 0;
	struct bpf_hdr *hdr = NULL;
		
	while(1)
	{
		if(m_stop_flag) break;

		try
		{
			if(PacketReceivePacket(m_lpa, m_lpp, TRUE) == FALSE)
				continue;
		}
		catch(...)
		{
			TRACE0("Exception in packet receive thread");
			return;
		}
		
		// Grab total length
		tlen = m_lpp->ulBytesReceived;

		// Process all the packets we've been handed
		offset = 0;
		while(offset < tlen)
		{
			hdr = (struct bpf_hdr *)(m_pbuf + offset);
			offset += hdr->bh_hdrlen;
			unsigned char *pkt = (unsigned char *)(m_pbuf + offset);
			u_int len = hdr->bh_caplen;
			
			// Adjust offset to next pkt w/ alignment
			offset = Packet_WORDALIGN(offset + hdr->bh_caplen);
						
			// we don't need to free the packet since it's static
			// for this loop
			m_parent->ProcessSniffedPacket( pkt, len );
		}
		Sleep(1);
	}
}
Ejemplo n.º 5
0
Archivo: pktdrv.c Proyecto: 10code/lwip
/**
 * Check for newly received packets. Called in the main loop: 'interrupt' mode is not
 * really supported :(
 *
 * @param adapter adapter handle received by a call to init_adapter
 */
void
update_adapter(void *adapter)
{
  struct packet_adapter *pa = (struct packet_adapter*)adapter;
  struct bpf_stat stat;

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

  if ((pa != NULL) && (PacketReceivePacket(pa->lpAdapter, pa->lpPacket, TRUE))) {
    ProcessPackets(adapter, pa->lpPacket);
  }
}
Ejemplo n.º 6
0
long sockRecvData(void *pData, int Size) {
	int ret;

	ret = _recvPacket(pData);
	if (ret > 0) return ret;

	PacketInitPacket(lpRecvPacket, buffer, BUFFER_SIZE);
	if(PacketReceivePacket(lpAdapter,lpRecvPacket,TRUE)==FALSE){
		printf("Error: PacketReceivePacket failed");
		return (-1);
	}
	lbytes = lpRecvPacket->ulBytesReceived;
	tbytes+= lbytes;
//	DEV9_LOG("PacketReceivePacket %d:\n", lbytes);
	if (lbytes == 0) return 0;
	memcpy(buffer, lpRecvPacket->Buffer, lbytes);
	buf = buffer;
	PacketFreePacket(lpRecvPacket);

	return _recvPacket(pData);
}
//抓包
int NetworkInterface::CapturePacket()
{
	while(1)
	{
		if(!RunStatus)
			break;
		WaitForSingleObject(hEventForRun, INFINITE);
		if (PacketReceivePacket(adapter.lpAdapter, adapter.lpPacket, TRUE) == FALSE)
		{
			LastErrCode = GetLastError();
			strcpy_s(LastErrStr, "Error: PacketReceivePacket failed");
			return (-1);
		}

        if(!RunStatus)
			break;
		/*在此处调用数据包处理函数*/
		SplitPackets(adapter.lpPacket);
	}
	SetEvent(hEventForQuit);
	return 0;
}
Ejemplo n.º 8
0
static int
pcap_read_win32_dag(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
{
	struct pcap_win *pw = p->priv;
	PACKET Packet;
	u_char *dp = NULL;
	int	packet_len = 0, caplen = 0;
	struct pcap_pkthdr	pcap_header;
	u_char *endofbuf;
	int n = 0;
	dag_record_t *header;
	unsigned erf_record_len;
	ULONGLONG ts;
	int cc;
	unsigned swt;
	unsigned dfp = pw->adapter->DagFastProcess;

	cc = p->cc;
	if (cc == 0) /* Get new packets only if we have processed all the ones of the previous read */
	{
		/*
		 * Get new packets from the network.
		 *
		 * The PACKET structure had a bunch of extra stuff for
		 * Windows 9x/Me, but the only interesting data in it
		 * in the versions of Windows that we support is just
		 * a copy of p->buffer, a copy of p->buflen, and the
		 * actual number of bytes read returned from
		 * PacketReceivePacket(), none of which has to be
		 * retained from call to call, so we just keep one on
		 * the stack.
		 */
		PacketInitPacket(&Packet, (BYTE *)p->buffer, p->bufsize);
		if (!PacketReceivePacket(pw->adapter, &Packet, TRUE)) {
			pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "read error: PacketReceivePacket failed");
			return (-1);
		}

		cc = Packet.ulBytesReceived;
		if(cc == 0)
			/* The timeout has expired but we no packets arrived */
			return (0);
		header = (dag_record_t*)pw->adapter->DagBuffer;
	}
	else
		header = (dag_record_t*)p->bp;

	endofbuf = (char*)header + cc;

	/*
	 * Cycle through the packets
	 */
	do
	{
		erf_record_len = SWAPS(header->rlen);
		if((char*)header + erf_record_len > endofbuf)
			break;

		/* Increase the number of captured packets */
		p->stat.ps_recv++;

		/* Find the beginning of the packet */
		dp = ((u_char *)header) + dag_record_size;

		/* Determine actual packet len */
		switch(header->type)
		{
		case TYPE_ATM:
			packet_len = ATM_SNAPLEN;
			caplen = ATM_SNAPLEN;
			dp += 4;

			break;

		case TYPE_ETH:
			swt = SWAPS(header->wlen);
			packet_len = swt - (pw->dag_fcs_bits);
			caplen = erf_record_len - dag_record_size - 2;
			if (caplen > packet_len)
			{
				caplen = packet_len;
			}
			dp += 2;

			break;

		case TYPE_HDLC_POS:
			swt = SWAPS(header->wlen);
			packet_len = swt - (pw->dag_fcs_bits);
			caplen = erf_record_len - dag_record_size;
			if (caplen > packet_len)
			{
				caplen = packet_len;
			}

			break;
		}

		if(caplen > p->snapshot)
			caplen = p->snapshot;

		/*
		 * Has "pcap_breakloop()" been called?
		 * If so, return immediately - if we haven't read any
		 * packets, clear the flag and return -2 to indicate
		 * that we were told to break out of the loop, otherwise
		 * leave the flag set, so that the *next* call will break
		 * out of the loop without having read any packets, and
		 * return the number of packets we've processed so far.
		 */
		if (p->break_loop)
		{
			if (n == 0)
			{
				p->break_loop = 0;
				return (-2);
			}
			else
			{
				p->bp = (char*)header;
				p->cc = endofbuf - (char*)header;
				return (n);
			}
		}

		if(!dfp)
		{
			/* convert between timestamp formats */
			ts = header->ts;
			pcap_header.ts.tv_sec = (int)(ts >> 32);
			ts = (ts & 0xffffffffi64) * 1000000;
			ts += 0x80000000; /* rounding */
			pcap_header.ts.tv_usec = (int)(ts >> 32);
			if (pcap_header.ts.tv_usec >= 1000000) {
				pcap_header.ts.tv_usec -= 1000000;
				pcap_header.ts.tv_sec++;
			}
		}

		/* No underlaying filtering system. We need to filter on our own */
		if (p->fcode.bf_insns)
		{
			if (bpf_filter(p->fcode.bf_insns, dp, packet_len, caplen) == 0)
			{
				/* Move to next packet */
				header = (dag_record_t*)((char*)header + erf_record_len);
				continue;
			}
		}

		/* Fill the header for the user suppplied callback function */
		pcap_header.caplen = caplen;
		pcap_header.len = packet_len;

		/* Call the callback function */
		(*callback)(user, &pcap_header, dp);

		/* Move to next packet */
		header = (dag_record_t*)((char*)header + erf_record_len);

		/* Stop if the number of packets requested by user has been reached*/
		if (++n >= cnt && !PACKET_COUNT_IS_UNLIMITED(cnt))
		{
			p->bp = (char*)header;
			p->cc = endofbuf - (char*)header;
			return (n);
		}
	}
Ejemplo n.º 9
0
static int
pcap_read_win32_npf(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
{
	PACKET Packet;
	int cc;
	int n = 0;
	register u_char *bp, *ep;
	u_char *datap;
	struct pcap_win *pw = p->priv;

	cc = p->cc;
	if (p->cc == 0) {
		/*
		 * Has "pcap_breakloop()" been called?
		 */
		if (p->break_loop) {
			/*
			 * Yes - clear the flag that indicates that it
			 * has, and return PCAP_ERROR_BREAK to indicate
			 * that we were told to break out of the loop.
			 */
			p->break_loop = 0;
			return (PCAP_ERROR_BREAK);
		}

		/*
		 * Capture the packets.
		 *
		 * The PACKET structure had a bunch of extra stuff for
		 * Windows 9x/Me, but the only interesting data in it
		 * in the versions of Windows that we support is just
		 * a copy of p->buffer, a copy of p->buflen, and the
		 * actual number of bytes read returned from
		 * PacketReceivePacket(), none of which has to be
		 * retained from call to call, so we just keep one on
		 * the stack.
		 */
		PacketInitPacket(&Packet, (BYTE *)p->buffer, p->bufsize);
		if (!PacketReceivePacket(pw->adapter, &Packet, TRUE)) {
			pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "read error: PacketReceivePacket failed");
			return (PCAP_ERROR);
		}

		cc = Packet.ulBytesReceived;

		bp = p->buffer;
	}
	else
		bp = p->bp;

	/*
	 * Loop through each packet.
	 */
#define bhp ((struct bpf_hdr *)bp)
	ep = bp + cc;
	for (;;) {
		register int caplen, hdrlen;

		/*
		 * Has "pcap_breakloop()" been called?
		 * If so, return immediately - if we haven't read any
		 * packets, clear the flag and return PCAP_ERROR_BREAK
		 * to indicate that we were told to break out of the loop,
		 * otherwise leave the flag set, so that the *next* call
		 * will break out of the loop without having read any
		 * packets, and return the number of packets we've
		 * processed so far.
		 */
		if (p->break_loop) {
			if (n == 0) {
				p->break_loop = 0;
				return (PCAP_ERROR_BREAK);
			} else {
				p->bp = bp;
				p->cc = (int) (ep - bp);
				return (n);
			}
		}
		if (bp >= ep)
			break;

		caplen = bhp->bh_caplen;
		hdrlen = bhp->bh_hdrlen;
		datap = bp + hdrlen;

		/*
		 * Short-circuit evaluation: if using BPF filter
		 * in kernel, no need to do it now - we already know
		 * the packet passed the filter.
		 *
		 * XXX - bpf_filter() should always return TRUE if
		 * handed a null pointer for the program, but it might
		 * just try to "run" the filter, so we check here.
		 */
		if (pw->filtering_in_kernel ||
		    p->fcode.bf_insns == NULL ||
		    bpf_filter(p->fcode.bf_insns, datap, bhp->bh_datalen, caplen)) {
#ifdef ENABLE_REMOTE
			switch (p->rmt_samp.method) {

			case PCAP_SAMP_1_EVERY_N:
				pw->samp_npkt = (pw->samp_npkt + 1) % p->rmt_samp.value;

				/* Discard all packets that are not '1 out of N' */
				if (pw->samp_npkt != 0) {
					bp += Packet_WORDALIGN(caplen + hdrlen);
					continue;
				}
				break;

			case PCAP_SAMP_FIRST_AFTER_N_MS:
			    {
				struct pcap_pkthdr *pkt_header = (struct pcap_pkthdr*) bp;

				/*
				 * Check if the timestamp of the arrived
				 * packet is smaller than our target time.
				 */
				if (pkt_header->ts.tv_sec < pw->samp_time.tv_sec ||
				   (pkt_header->ts.tv_sec == pw->samp_time.tv_sec && pkt_header->ts.tv_usec < pw->samp_time.tv_usec)) {
					bp += Packet_WORDALIGN(caplen + hdrlen);
					continue;
				}

				/*
				 * The arrived packet is suitable for being
				 * delivered to our caller, so let's update
				 * the target time.
				 */
				pw->samp_time.tv_usec = pkt_header->ts.tv_usec + p->rmt_samp.value * 1000;
				if (pw->samp_time.tv_usec > 1000000) {
					pw->samp_time.tv_sec = pkt_header->ts.tv_sec + pw->samp_time.tv_usec / 1000000;
					pw->samp_time.tv_usec = pw->samp_time.tv_usec % 1000000;
				}
			    }
			}
#endif	/* ENABLE_REMOTE */

			/*
			 * XXX A bpf_hdr matches a pcap_pkthdr.
			 */
			(*callback)(user, (struct pcap_pkthdr*)bp, datap);
			bp += Packet_WORDALIGN(caplen + hdrlen);
			if (++n >= cnt && !PACKET_COUNT_IS_UNLIMITED(cnt)) {
				p->bp = bp;
				p->cc = (int) (ep - bp);
				return (n);
			}
		} else {
			/*
			 * Skip this packet.
			 */
			bp += Packet_WORDALIGN(caplen + hdrlen);
		}
	}
#undef bhp
	p->cc = 0;
	return (n);
}
Ejemplo n.º 10
0
static int
pcap_read_win32_npf(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
{
	int cc;
	int n = 0;
	register u_char *bp, *ep;

	cc = p->cc;
	if (p->cc == 0) {
		/*
		 * Has "pcap_breakloop()" been called?
		 */
		if (p->break_loop) {
			/*
			 * Yes - clear the flag that indicates that it
			 * has, and return -2 to indicate that we were
			 * told to break out of the loop.
			 */
			p->break_loop = 0;
			return (-2);
		}

	    /* capture the packets */
		if(PacketReceivePacket(p->adapter,p->Packet,TRUE)==FALSE){
			snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "read error: PacketReceivePacket failed");
			return (-1);
		}
			
		cc = p->Packet->ulBytesReceived;

		bp = p->Packet->Buffer;
	} 
	else
		bp = p->bp;

	/*
	 * Loop through each packet.
	 */
#define bhp ((struct bpf_hdr *)bp)
	ep = bp + cc;
	while (1) {
		register int caplen, hdrlen;

		/*
		 * Has "pcap_breakloop()" been called?
		 * If so, return immediately - if we haven't read any
		 * packets, clear the flag and return -2 to indicate
		 * that we were told to break out of the loop, otherwise
		 * leave the flag set, so that the *next* call will break
		 * out of the loop without having read any packets, and
		 * return the number of packets we've processed so far.
		 */
		if (p->break_loop) {
			if (n == 0) {
				p->break_loop = 0;
				return (-2);
			} else {
				p->bp = bp;
				p->cc = ep - bp;
				return (n);
			}
		}
		if (bp >= ep)
			break;

		caplen = bhp->bh_caplen;
		hdrlen = bhp->bh_hdrlen;

		/*
		 * XXX A bpf_hdr matches a pcap_pkthdr.
		 */
		(*callback)(user, (struct pcap_pkthdr*)bp, bp + hdrlen);
		bp += BPF_WORDALIGN(caplen + hdrlen);
		if (++n >= cnt && cnt > 0) {
			p->bp = bp;
			p->cc = ep - bp;
			return (n);
		}
	}
#undef bhp
	p->cc = 0;
	return (n);
}
Ejemplo n.º 11
0
int 
pcap_next_ex(pcap_t *p, struct pcap_pkthdr **pkt_header, u_char **pkt_data)
{
	/* Check the capture type */

#ifdef HAVE_REMOTE
	if (p->rmt_clientside)
	{
		/* We are on an remote capture */
		if (!p->rmt_capstarted)
		{
			// if the capture has not started yet, please start it
			if (pcap_startcapture_remote(p) )
				return -1;
			p->rmt_capstarted= 1;
		}
		return pcap_next_ex_remote(p, pkt_header, pkt_data);
	}
#endif

	if (p->adapter!=NULL)
	{
		/* We are on a live capture */
		int cc;
		int n = 0;
		register u_char *bp, *ep;
		
		cc = p->cc;
		if (p->cc == 0) 
		{
			/* capture the packets */
			if(PacketReceivePacket(p->adapter, p->Packet, TRUE) == FALSE)
			{
				sprintf(p->errbuf, "read error: PacketReceivePacket failed");
				return (-1);
			}
			
			cc = p->Packet->ulBytesReceived;
			
			bp = p->Packet->Buffer;
		} 
		else
			bp = p->bp;
		
		/*
		 * Loop through each packet.
		 */
		ep = bp + cc;
		if (bp < ep) 
		{
			register int caplen, hdrlen;
			caplen = ((struct bpf_hdr *)bp)->bh_caplen;
			hdrlen = ((struct bpf_hdr *)bp)->bh_hdrlen;
			
			/*
			 * XXX A bpf_hdr matches a pcap_pkthdr.
			 */
			*pkt_header = (struct pcap_pkthdr*)bp;
			*pkt_data = bp + hdrlen;
			bp += BPF_WORDALIGN(caplen + hdrlen);
			
			p->bp = bp;
			p->cc = ep - bp;
			return (1);
		}
		else{
			p->cc = 0;
			return (0);
		}
	}	
	else
	{
		/* We are on an offline capture */
		struct bpf_insn *fcode = p->fcode.bf_insns;
		int status;
		int n = 0;
		
		struct pcap_pkthdr *h=(struct pcap_pkthdr*)(p->buffer+p->bufsize-sizeof(struct pcap_pkthdr));
		
		while (1)
		{
			status = sf_next_packet(p, h, p->buffer, p->bufsize);
			if (status==1)
				/* EOF */
				return (-2);
			if (status==-1)
				/* Error */
				return (-1);
			
			if (fcode == NULL ||
				bpf_filter(fcode, p->buffer, h->len, h->caplen)) 
			{
				*pkt_header = h;
				*pkt_data = p->buffer;
				return (1);
			}			
			
		}
	}
}
Ejemplo n.º 12
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.º 13
0
/**
 * Our low-level capture thread.
 *
 * Loop waiting for packet(s) in PacketReceivePacket(). In
 * _pkt_release() the receive event-handle (adapter->Readvent) is
 * set. This causes WaitForSingleObject() in PacketReceivePacket()
 * to return. It is vital that the ADAPTER object isn't deallocated
 * before PacketReceivePacket() returns.
 *
 * The return-value is > 0 if thread exited on it's own. Otherwise
 * it is 0  (from  GetExitCodeThread).
 */
DWORD __stdcall pkt_recv_thread (void *arg)
{
  int rc = 0;

  while (1)
  {
    const  ADAPTER *adapter;
    const  BYTE *pkt, *pkt_end;
    size_t cap_len, hdr_len;
    int    total_len, chunk;
    PACKET npf_pkt;

    if (!_pkt_inf || _pkt_inf->stop_thread)  /* signals closure */
    {
      rc = 1;
      break;
    }

    adapter  = (const ADAPTER*) _pkt_inf->adapter;
    npf_pkt.Length = _pkt_inf->npf_buf_size;
    npf_pkt.Buffer = _pkt_inf->npf_buf;

    if (!PacketReceivePacket(adapter, &npf_pkt, TRUE))
    {
      rc = 2;
      break;
    }
    total_len = npf_pkt.ulBytesReceived;

    ENTER_CRIT();

    for (pkt = npf_pkt.Buffer, pkt_end = (BYTE*)npf_pkt.Buffer + total_len, chunk = 1;
         pkt < pkt_end;
         pkt += Packet_WORDALIGN(cap_len+hdr_len), chunk++)
    {
      struct pkt_ringbuf    *q;
      struct pkt_rx_element *head;
      struct bpf_hdr        *bp;

      q  = &_pkt_inf->pkt_queue;
      bp = (struct bpf_hdr*) pkt;

      cap_len = bp->bh_caplen;
      hdr_len = bp->bh_hdrlen;

      num_rx_bytes += bp->bh_datalen;

      TCP_CONSOLE_MSG (2, ("pkt_recv_thread(): total_len %d, "
                           "chunk %d, cap_len %d, in-idx %d\n",
                       total_len, chunk, cap_len, q->in_index));

      if (cap_len > ETH_MAX)
      {
        _pkt_inf->error = "Large size";
        STAT (macstats.num_too_large++);
      }
      else
      if (pktq_in_index(q) == q->out_index)  /* queue is full, drop it */
         q->num_drop++;
      else
      {
        int pad_len, buf_max;

        head = (struct pkt_rx_element*) pktq_in_buf (q);
        memcpy (head->rx_buf, pkt + hdr_len, cap_len);
        head->tstamp_put = bp->bh_tstamp;
        head->rx_length  = cap_len;

        /* zero-pad up to ETH_MAX (don't destroy marker at end)
         */
        buf_max = q->buf_size - RX_ELEMENT_HEAD_SIZE - 4;
        pad_len = min (ETH_MAX, buf_max - cap_len);
        if (pad_len > 0)
           memset (&head->rx_buf[cap_len], 0, pad_len);
        pktq_inc_in (q);
      }
    }
    LEAVE_CRIT();
  }

  TCP_CONSOLE_MSG (2, ("pkt_recv_thread(): rc %d\n", rc));
  fflush (stdout);
  ARGSUSED (arg);
  thr_stopped = TRUE;
  return (rc);
}
Ejemplo n.º 14
0
static int
pcap_read_win32_npf(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
{
	int cc;
	int n = 0;
	register u_char *bp, *ep;
	u_char *datap;
	struct pcap_win *pw = p->priv;

	cc = p->cc;
	if (p->cc == 0) {
		/*
		 * Has "pcap_breakloop()" been called?
		 */
		if (p->break_loop) {
			/*
			 * Yes - clear the flag that indicates that it
			 * has, and return PCAP_ERROR_BREAK to indicate
			 * that we were told to break out of the loop.
			 */
			p->break_loop = 0;
			return (PCAP_ERROR_BREAK);
		}

	    /* capture the packets */
		if(PacketReceivePacket(p->adapter,p->Packet,TRUE)==FALSE){
			snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "read error: PacketReceivePacket failed");
			return (PCAP_ERROR);
		}

		cc = p->Packet->ulBytesReceived;

		bp = p->Packet->Buffer;
	}
	else
		bp = p->bp;

	/*
	 * Loop through each packet.
	 */
#define bhp ((struct bpf_hdr *)bp)
	ep = bp + cc;
	while (1) {
		register int caplen, hdrlen;

		/*
		 * Has "pcap_breakloop()" been called?
		 * If so, return immediately - if we haven't read any
		 * packets, clear the flag and return PCAP_ERROR_BREAK
		 * to indicate that we were told to break out of the loop,
		 * otherwise leave the flag set, so that the *next* call
		 * will break out of the loop without having read any
		 * packets, and return the number of packets we've
		 * processed so far.
		 */
		if (p->break_loop) {
			if (n == 0) {
				p->break_loop = 0;
				return (PCAP_ERROR_BREAK);
			} else {
				p->bp = bp;
				p->cc = ep - bp;
				return (n);
			}
		}
		if (bp >= ep)
			break;

		caplen = bhp->bh_caplen;
		hdrlen = bhp->bh_hdrlen;
		datap = bp + hdrlen;

		/*
		 * Short-circuit evaluation: if using BPF filter
		 * in kernel, no need to do it now - we already know
		 * the packet passed the filter.
		 *
		 * XXX - bpf_filter() should always return TRUE if
		 * handed a null pointer for the program, but it might
		 * just try to "run" the filter, so we check here.
		 */
		if (pw->filtering_in_kernel ||
		    p->fcode.bf_insns == NULL ||
		    bpf_filter(p->fcode.bf_insns, datap, bhp->bh_datalen, caplen)) {
			/*
			 * XXX A bpf_hdr matches a pcap_pkthdr.
			 */
			(*callback)(user, (struct pcap_pkthdr*)bp, datap);
			bp += Packet_WORDALIGN(caplen + hdrlen);
			if (++n >= cnt && !PACKET_COUNT_IS_UNLIMITED(cnt)) {
				p->bp = bp;
				p->cc = ep - bp;
				return (n);
			}
		} else {
			/*
			 * Skip this packet.
			 */
			bp += Packet_WORDALIGN(caplen + hdrlen);
		}
	}
#undef bhp
	p->cc = 0;
	return (n);
}
Ejemplo n.º 15
0
int
pcap_read(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
{
	int cc;
	int n = 0;
	register u_char *bp, *ep;

#ifdef REMOTE
	if (p->rmt_clientside)
	{
		/* We are on an remote capture */
		if (!p->rmt_capstarted)
		{
			// if the capture has not started yet, please start it
			if (pcap_startcapture_remote(p) )
				return -1;
			p->rmt_capstarted= 1;
		}
		return pcap_read_remote(p, cnt, callback, user);
	}
#endif

	cc = p->cc;
	if (p->cc == 0) {

	    /* capture the packets */
		if(PacketReceivePacket(p->adapter,p->Packet,TRUE)==FALSE){
			snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "read error: PacketReceivePacket failed");
			return (-1);
		}
			
		cc = p->Packet->ulBytesReceived;

		bp = p->Packet->Buffer;
	} 
	else
		bp = p->bp;

	/*
	 * Loop through each packet.
	 */
#define bhp ((struct bpf_hdr *)bp)
	ep = bp + cc;
	while (bp < ep) {
		register int caplen, hdrlen;
		caplen = bhp->bh_caplen;
		hdrlen = bhp->bh_hdrlen;

		/*
		 * XXX A bpf_hdr matches a pcap_pkthdr.
		 */
		(*callback)(user, (struct pcap_pkthdr*)bp, bp + hdrlen);
		bp += BPF_WORDALIGN(caplen + hdrlen);
		if (++n >= cnt && cnt > 0) {
			p->bp = bp;
			p->cc = ep - bp;
			return (n);
		}
	}
#undef bhp
	p->cc = 0;
	return (n);
}