Exemplo n.º 1
0
int main (void)
{
    int fd;

    /* Create PCAP file */
    assert((fd = pcap_create(test_path, LINKTYPE_EN10MB)) > 0);

    /* Write payload */
    assert(test_pcap_write(fd, icmp_dns, sizeof(icmp_dns)) == 0);

    assert(pcap_close(fd) == 0);

    assert((fd = pcap_open(test_path, O_RDONLY)) > 0);

    assert(pcap_has_packets(fd));

    assert(pcap_close(fd) == 0);

    assert((fd = pcap_open(test_path, O_RDWR | O_APPEND)) > 0);

    /* Write payload */
    assert(test_pcap_write(fd, icmp_dns, sizeof(icmp_dns)) == 0);

    assert(pcap_close(fd) == 0);

    pcap_destroy(fd, test_path);

    return (EXIT_SUCCESS);
}
Exemplo n.º 2
0
void test_pcap(void)
{
	rdpPcap* pcap;
	pcap_record record;
	test_packet packets[3];

	packets[0].data = test_packet_1;
	packets[0].length = sizeof(test_packet_1);
	packets[1].data = test_packet_2;
	packets[1].length = sizeof(test_packet_2);
	packets[2].data = test_packet_3;
	packets[2].length = sizeof(test_packet_3);

	pcap = pcap_open("/tmp/test.pcap", true);
	pcap_add_record(pcap, test_packet_1, sizeof(test_packet_1));
	pcap_flush(pcap);
	pcap_add_record(pcap, test_packet_2, sizeof(test_packet_2));
	pcap_flush(pcap);
	pcap_add_record(pcap, test_packet_3, sizeof(test_packet_3));
	pcap_close(pcap);

	pcap = pcap_open("/tmp/test.pcap", false);

	int i = 0;
	while (pcap_has_next_record(pcap))
	{
		pcap_get_next_record(pcap, &record);
		CU_ASSERT(record.length == packets[i].length)
		i++;
	}

	CU_ASSERT(i == 3);

	pcap_close(pcap);
}
Exemplo n.º 3
0
boolean freerdp_connect(freerdp* instance)
{
	rdpRdp* rdp;
	boolean status;

	rdp = instance->context->rdp;

	IFCALL(instance->PreConnect, instance);

	status = rdp_client_connect(rdp);

	if (status)
	{
		if (instance->settings->dump_rfx)
		{
			instance->update->pcap_rfx = pcap_open(instance->settings->dump_rfx_file, True);
			if (instance->update->pcap_rfx)
				instance->update->dump_rfx = True;
		}

		IFCALL(instance->PostConnect, instance);

		if (instance->settings->play_rfx)
		{
			STREAM* s;
			rdpUpdate* update;
			pcap_record record;

			s = stream_new(1024);
			instance->update->pcap_rfx = pcap_open(instance->settings->play_rfx_file, False);
			if (instance->update->pcap_rfx)
				instance->update->play_rfx = True;
			update = instance->update;

			while (instance->update->play_rfx && pcap_has_next_record(update->pcap_rfx))
			{
				pcap_get_next_record_header(update->pcap_rfx, &record);

				s->data = xrealloc(s->data, record.length);
				record.data = s->data;
				s->size = record.length;

				pcap_get_next_record_content(update->pcap_rfx, &record);
				stream_set_pos(s, 0);

				update->BeginPaint(update);
				update_recv_surfcmds(update, s->size, s);
				update->EndPaint(update);
			}

			xfree(s->data);
			return True;
		}
	}

	return status;
}
Exemplo n.º 4
0
void tf_peer_dump_rfx(freerdp_peer* client)
{
	STREAM* s;
	uint32 prev_seconds;
	uint32 prev_useconds;
	rdpUpdate* update;
	rdpPcap* pcap_rfx;
	pcap_record record;

	s = stream_new(512);
	update = client->update;
	client->update->pcap_rfx = pcap_open(test_pcap_file, False);
	pcap_rfx = client->update->pcap_rfx;

	prev_seconds = prev_useconds = 0;

	while (pcap_has_next_record(pcap_rfx))
	{
		pcap_get_next_record_header(pcap_rfx, &record);

		s->data = xrealloc(s->data, record.length);
		record.data = s->data;
		s->size = record.length;

		pcap_get_next_record_content(pcap_rfx, &record);
		s->p = s->data + s->size;

		if (test_dump_rfx_realtime && test_sleep_tsdiff(&prev_seconds, &prev_useconds, record.header.ts_sec, record.header.ts_usec) == False)
			break;

		update->SurfaceCommand(update, s);
	}
}
Exemplo n.º 5
0
int openpcapfile(pcap_t **pcapout, char *filename) {
	pcap_t *pcap;
	char errbuf[PCAP_ERRBUF_SIZE];
	char source[PCAP_BUF_SIZE];

	/* Create the source string according to the new WinPcap syntax */
    if ( pcap_createsrcstr( source,         // variable that will keep the source string
                            PCAP_SRC_FILE,  // we want to open a file
                            NULL,           // remote host
                            NULL,           // port on the remote host
                            filename,        // name of the file we want to open
                            errbuf          // error buffer
                            ) != 0)
    {
        fprintf(stderr,"\nError creating a source string\n");
        return -1;
    }
    
    /* Open the capture file */
    if ( (pcap = pcap_open(source,         // name of the device
                        65536,          // portion of the packet to capture
                                        // 65536 guarantees that the whole packet will be captured on all the link layers
                         PCAP_OPENFLAG_PROMISCUOUS,     // promiscuous mode
                         1000,              // read timeout
                         NULL,              // authentication on the remote machine
                         errbuf         // error buffer
                         ) ) == NULL)
    {
		fprintf(stderr,"\nUnable to open %s: %s\n", filename, errbuf);
        return -1;
    }

	*pcapout = pcap;
	return 0;
}
Exemplo n.º 6
0
static void prvOpenInterface( const char *pucName )
{
static char pucInterfaceName[ 256 ];

	if( pucName != NULL )
	{
		strncpy( pucInterfaceName, pucName, sizeof( pucInterfaceName ) );
	}

	pxOpenedInterfaceHandle = pcap_open(	pucInterfaceName,          	/* The name of the selected interface. */
											ipTOTAL_ETHERNET_FRAME_SIZE, /* The size of the packet to capture. */
											PCAP_OPENFLAG_PROMISCUOUS,	/* Open in promiscuous mode as the MAC and
																		IP address is going to be "simulated", and
																		not be the real MAC and IP address.  This allows
																		traffic to the simulated IP address to be routed
																		to uIP, and traffic to the real IP address to be
																		routed to the Windows TCP/IP stack. */
											100,
											NULL,             			/* No authentication is required as this is
																		not a remote capture session. */
											cErrorBuffer
									   );

	if ( pxOpenedInterfaceHandle == NULL )
	{
		printf( "\n%s is not supported by WinPcap and cannot be opened\n", pucInterfaceName );
	}
	else
	{
		/* Configure the capture filter to allow blocking reads, and to filter
		out packets that are not of interest to this demo. */
		prvConfigureCaptureBehaviour();
	}
}
Exemplo n.º 7
0
/**
    @brief
    This will sniff incoming packets for an ICMP ECHO reply
    libpcap version
*/
bool turbotrace::start_sniffer()
{
	log("Sniffer initialising...\n");

    char errbuf[1000];
	//Open the device
    adapter = pcap_open(adapter_info.name , 65536 , PCAP_OPENFLAG_PROMISCUOUS , 20 , NULL ,errbuf);

    if (adapter == NULL)
	{
		log(_("pcap_open_live failed") + wxString(errbuf , wxConvUTF8));
		return false;
	}

	log(_("pcap_open successful"));

    sniffer_ready = true;

	//Send the syn packets
    send_syn();

    //Put the device in sniff loop
	pcap_loop(adapter , -1 , process_packet2 , (u_char*)this);

	return true;
}
Exemplo n.º 8
0
void main(int argc, char **argv)
{
pcap_t *fp;
char errbuf[PCAP_ERRBUF_SIZE];
struct timeval st_ts;
u_int netmask;
struct bpf_program fcode;
  
	/* Check the validity of the command line */
	if (argc != 2)
	{
		usage();
		return;
	}
		
	/* Open the output adapter */
	if ( (fp= pcap_open(argv[1], 100, PCAP_OPENFLAG_PROMISCUOUS, 1000, NULL, errbuf) ) == NULL)
	{
		fprintf(stderr,"\nUnable to open adapter %s.\n", errbuf);
		return;
	}

    /* Don't care about netmask, it won't be used for this filter */
    netmask=0xffffff; 

    //compile the filter
    if (pcap_compile(fp, &fcode, "tcp", 1, netmask) <0 )
	{
        fprintf(stderr,"\nUnable to compile the packet filter. Check the syntax.\n");
        /* Free the device list */
        return;
    }
    
    //set the filter
    if (pcap_setfilter(fp, &fcode)<0)
	{
        fprintf(stderr,"\nError setting the filter.\n");
		pcap_close(fp);
        /* Free the device list */
        return;
    }

	/* Put the interface in statstics mode */
	if (pcap_setmode(fp, MODE_STAT)<0)
	{
        fprintf(stderr,"\nError setting the mode.\n");
		pcap_close(fp);
        /* Free the device list */
        return;
    }


	printf("TCP traffic summary:\n");

	/* Start the main loop */
	pcap_loop(fp, 0, dispatcher_handler, (PUCHAR)&st_ts);

	pcap_close(fp);
	return;
}
Exemplo n.º 9
0
/*
 * Tries to open the given interface on promiscuous
 * Parameters:
 * 		none
 * Returns: true if the interface is open, false otherwise
*/
bool Interface::open() {
#ifdef _WIN32
	return (handle = pcap_open(dev, BUFSIZ, PCAP_OPENFLAG_PROMISCUOUS | PCAP_OPENFLAG_NOCAPTURE_LOCAL | PCAP_OPENFLAG_MAX_RESPONSIVENESS, 500, NULL, errbuf)) != NULL;
#else
	return (handle = pcap_open_live(dev, BUFSIZ, 1, 500, errbuf)) != NULL;
#endif
}
Exemplo n.º 10
0
int main(int argc, char **argv)
{
    pcap_t *fp;
    char errbuf[PCAP_ERRBUF_SIZE];
    struct timeval st_ts;
    u_int netmask;
    struct bpf_program fcode;

    /* 检查命令行参数的合法性 */
    if (argc != 2)
    {
        usage();
        return -1;
    }

    /* 打开输出适配器 */
    if ( (fp= pcap_open(argv[1], 100, PCAP_OPENFLAG_PROMISCUOUS, 1000, NULL, errbuf) ) == NULL)
    {
        fprintf(stderr,"\nUnable to open adapter %s.\n", errbuf);
        return -1;
    }

    /* 不用关心掩码,在这个过滤器中,它不会被使用 */
    netmask=0xffffff;

    // 编译过滤器
    if (pcap_compile(fp, &fcode, "tcp", 1, netmask) <0 )
    {
        fprintf(stderr,"\nUnable to compile the packet filter. Check the syntax.\n");
        /* 释放设备列表 */
        return -1;
    }

    //设置过滤器
    if (pcap_setfilter(fp, &fcode)<0)
    {
        fprintf(stderr,"\nError setting the filter.\n");
        pcap_close(fp);
        /* 释放设备列表 */
        return -1;
    }

    /* 将接口设置为统计模式 */
    if (pcap_setmode(fp, MODE_STAT)<0)
    {
        fprintf(stderr,"\nError setting the mode.\n");
        pcap_close(fp);
        /* 释放设备列表 */
        return -1;
    }


    printf("TCP traffic summary:\n");

    /* 开始主循环 */
    pcap_loop(fp, 0, dispatcher_handler, (PUCHAR)&st_ts);

    pcap_close(fp);
    return 0;
}
Exemplo n.º 11
0
pcap_t *nr_open_current_device_adapter(int snaplen, pcap_addr_t ** sockaddr) {
    pcap_if_t *devices;
    pcap_if_t *device;
    char errbuf[PCAP_ERRBUF_SIZE];

    if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &devices, errbuf) == -1) {
        fprintf(stderr, "Error in pcap_findalldevs_ex: %s\n", errbuf);
        return 0;
    }

    // Return first interface with an address
    for (device = devices; device; device = device->next) {
        if (device->description) {
            pcap_addr_t *addr;
            for (addr = device->addresses; addr; addr = addr->next) {
                if (addr->addr->sa_family == AF_INET) { // IPv4 addr
                    if (addr->addr) {
                        (*sockaddr) = nr_get_device_ip_interface(device);
                        pcap_t *handle;
                        handle = pcap_open(device->name, snaplen, PCAP_OPENFLAG_PROMISCUOUS, 1000, NULL, errbuf);
                        return handle;
                    }
                }
            }
        }
    }
    return 0;
}
Exemplo n.º 12
0
/* Open an Ethernet interface using PCAP */
static pcap_t *nio_ethernet_open(char *device)
{
   char pcap_errbuf[PCAP_ERRBUF_SIZE];
   pcap_t *p;

#ifndef CYGWIN
   /* Timeout is 10ms */
   if (!(p = pcap_open_live(device, 65535, TRUE, 10, pcap_errbuf)))
      goto pcap_error;

   pcap_setdirection(p, PCAP_D_INOUT);
#ifdef BIOCFEEDBACK
   {
     int on = 1;
     ioctl(pcap_fileno(p), BIOCFEEDBACK, &on);
   }
#endif
#else
   p = pcap_open(device, 65535,
       PCAP_OPENFLAG_PROMISCUOUS |
       PCAP_OPENFLAG_NOCAPTURE_LOCAL |
	   PCAP_OPENFLAG_MAX_RESPONSIVENESS |
	   PCAP_OPENFLAG_NOCAPTURE_RPCAP,
	   10, NULL, pcap_errbuf);

   if (!p)
      goto pcap_error;
#endif

   return p;

 pcap_error:
   fprintf(stderr, "nio_ethernet_open: unable to open device '%s' ""with PCAP (%s)\n", device, pcap_errbuf);
   return NULL;
}
Exemplo n.º 13
0
int add_stream_from_pcap(char *file_path)
{
    pcap_t *fp;
    char errbuf[PCAP_ERRBUF_SIZE];
    char source[PCAP_BUF_SIZE];
    struct pcap_pkthdr *header;
    const u_char *pkt_data;
    t_stream t_stream_tmp;
    
    /* Create the source string according to the new WinPcap syntax */
    if ( pcap_createsrcstr( source,         // variable that will keep the source string
                            PCAP_SRC_FILE,  // we want to open a file
                            NULL,           // remote host
                            NULL,           // port on the remote host
                            file_path,        // name of the file we want to open
                            errbuf          // error buffer
                            ) != 0)
    {
        WinPrintf(hwnd_frame, "Error creating a source string");
        return -1;
    }
    
    /* Open the capture file */
    if ( (fp= pcap_open(source,         // name of the device
                        65536,          // portion of the packet to capture
                                        // 65536 guarantees that the whole packet will be captured on all the link layers
                         PCAP_OPENFLAG_PROMISCUOUS,     // promiscuous mode
                         1000,              // read timeout
                         NULL,              // authentication on the remote machine
                         errbuf         // error buffer
                         ) ) == NULL)
    {
        WinPrintf(hwnd_frame, "打开文件失败:\n%s\n可能是抓包存档文件损坏或格式不支持", source);
        return -1;
    }

    while (pcap_next_ex(fp, &header, &pkt_data)>0)
    {
        if (nr_cur_stream>=MAX_STREAM_NUM)
        {
             err_msg_box("已达最大流数目 %d", MAX_STREAM_NUM);
             break;
        }


        init_stream(&t_stream_tmp);
        t_stream_tmp.len=header->caplen;
        memcpy(t_stream_tmp.data, pkt_data, t_stream_tmp.len);
        t_stream_tmp.err_flags = build_err_flags((void *)(t_stream_tmp.data), t_stream_tmp.len);
        add_stream(&t_stream_tmp);


    }

    pcap_close(fp);	
    re_populate_items();
    return 0;
}
Exemplo n.º 14
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;
}
Exemplo n.º 15
0
/* Opens a port with the given name and uid. */
struct pcap_port * MALLOC_ATTR
pcap_port_open(struct pcap_drv *pcap_drv, size_t id, const char *name) {

    struct linux_port *linux_port;
    HASH_FIND_STR(pcap_drv->linux_ports_map, name, linux_port);
    if(linux_port == NULL) {
        logger_log(pcap_drv->logger, LOG_ERR, "Unable to get interface flags");
        logger_log(pcap_drv->logger, LOG_ERR, "There is no linux port for %s", name);
        return NULL;
    }

    struct linux_port_flags *flags = &linux_port->flags;
    if (flags == NULL) {
        logger_log(pcap_drv->logger, LOG_ERR, "Unable to get interface flags %s", name);
        return NULL;
    }

    struct pcap_port *pcap_port = malloc(sizeof(struct pcap_port));
    pcap_port->drv     = pcap_drv;
    pcap_port->id      = id;
    pcap_port->name    = strdup(name);
    pcap_port->logger  = logger_mgr_get(LOGGER_NAME_PORT_DRV_PCAP_PORT, id);


    pcap_port->dp_uid = 0; // invalidity marked by port_no
    pcap_port->dp_port_no = OF_NO_PORT;
    pcap_port->pkt_mbox = NULL;
    pcap_port->rwlock = malloc(sizeof(pthread_rwlock_t));
    pthread_rwlock_init(pcap_port->rwlock, NULL);

    pcap_port->of_port = malloc(sizeof(struct ofl_port));
    memset(pcap_port->of_port, '\0', sizeof(struct ofl_port));
    pcap_port->of_stats = malloc(sizeof(struct ofl_port_stats));
    memset(pcap_port->of_stats, '\0', sizeof(struct ofl_port_stats));
    pcap_port->of_port->name = strdup(name);

    pcap_port->stats_mutex = malloc(sizeof(pthread_mutex_t));
    pthread_mutex_init(pcap_port->stats_mutex, NULL);

    if(flags->UP && flags->RUNNING) {
        return pcap_open(pcap_port);
    } else {
        pcap_port->pcap = NULL;
        pcap_port->fd   = -1;

        pcap_port->watcher = NULL;
    }

    return pcap_port;
}
Exemplo n.º 16
0
int CapturePacketThread::RunCapture()
{
	Releaseinfo("RunCapture  input");
    pcap_t *adhandle;
    char errbuf[PCAP_ERRBUF_SIZE];
    u_int netmask=0xffffff;
    struct bpf_program fp;
    
    if((adhandle= pcap_open(devname.c_str(),          // name of the device
                              65536,            // portion of the packet to capture
                                                // 65536 guarantees that the whole packet will be captured on all the link layers
                              PCAP_OPENFLAG_PROMISCUOUS,    // promiscuous mode
                              1000,             // read timeout
                              NULL,             // authentication on the remote machine
                              errbuf            // error buffer
                              ) ) == NULL)
    {
		Releaseinfo("pcap_open fails");
        fprintf(stderr,"\nUnable to open the adapter. %s is not supported by WinPcap\n", devname.c_str());
        return -1;
    }
	string filter("");
	string host_str("");
	host_str = AppConfig::SharedInstance()->GetHostIp();
	filter+="host ";
	filter+=ipstr;
	filter+=" and (tcp or udp) and (not host ";
	filter+=host_str;
	filter+=")";
	//char test_filter[100]={0};
	//strcpy(test_filter,filter.c_str());
	//Releaseinfo(test_filter);
    if(pcap_compile(adhandle, &fp, filter.c_str(), 0, netmask) == -1) {
		Releaseinfo("pcap_compile fails");
        fprintf(stderr, "Error calling pcap_compile\n");
        return -1;
    }
 
    if(pcap_setfilter(adhandle, &fp) == -1) {
		Releaseinfo("pcap_setfilter fails");
        fprintf(stderr, "Error setting filter\n");
        return -1;
    }
	char user_ip[20]={0};
	strcpy(user_ip,ipstr.c_str());
    pcap_loop(adhandle, 0, PacketHandler, (u_char*)user_ip);
    return 0;
}
Exemplo n.º 17
0
//打开设备
int Device::OpenDevice(pcap_if_t *d)
{
	if ((adhandle = pcap_open(d->name,          // 设备名
		65536,            // 65535保证能捕获到不同数据链路层上的每个数据包的全部内容
		PCAP_OPENFLAG_PROMISCUOUS,    // 混杂模式,以保证抓到ARP包
		1,             /*读取超时时间,单位为毫秒,捕捉数据包的时候,延迟一定的时间,然后再调用内核中的程序,
					   这样效率较高。0表示没有延迟,没有包到达的时候永不返回。-1表示立即返回。*/
					   NULL,             // 远程机器验证
					   errbuf            // 错误缓冲池
					   )) == NULL)
	{
		pcap_freealldevs(alldevs);//释放设备列表
		return -1;
	}
	else return 0;
}
Exemplo n.º 18
0
BOOL tf_peer_dump_rfx(freerdp_peer* client)
{
	wStream* s;
	UINT32 prev_seconds;
	UINT32 prev_useconds;
	rdpUpdate* update;
	rdpPcap* pcap_rfx;
	pcap_record record;
	s = Stream_New(NULL, 512);

	if (!s)
		return FALSE;

	update = client->update;

	if (!(pcap_rfx = pcap_open(test_pcap_file, FALSE)))
		return FALSE;

	prev_seconds = prev_useconds = 0;

	while (pcap_has_next_record(pcap_rfx))
	{
		if (!pcap_get_next_record_header(pcap_rfx, &record))
			break;

		if (!Stream_EnsureCapacity(s, record.length))
			break;

		record.data = Stream_Buffer(s);
		pcap_get_next_record_content(pcap_rfx, &record);
		Stream_SetPointer(s, Stream_Buffer(s) + Stream_Capacity(s));

		if (test_dump_rfx_realtime
		    && test_sleep_tsdiff(&prev_seconds, &prev_useconds, record.header.ts_sec,
		                         record.header.ts_usec) == FALSE)
			break;

		update->SurfaceCommand(update->context, s);

		if (client->CheckFileDescriptor(client) != TRUE)
			break;
	}

	Stream_Free(s, TRUE);
	pcap_close(pcap_rfx);
	return TRUE;
}
Exemplo n.º 19
0
///////////////////////////////////////////////////////////////////////////////////////
//
//	Body
//
///////////////////////////////////////////////////////////////////////////////////////
//=====================================================================================
//
//	* Function : openDevice()
//	* Description
//		 해당 모듈은 사용자가 선택한 디바이스를 열고 해당 핸들을 datas.cpp에 선언된
//		adhandle에 저장한다.
//
//=====================================================================================
int openDevice(int index){

	char errbuf[PCAP_ERRBUF_SIZE];
	int counter;
	char logmsg[LOG_MSG_SIZE];
	unsigned int lNetMask = 0;
	struct bpf_program lFCode;

	for(d=alldevs, counter=0; d; d=d->next, counter++){
		if(counter==index){
			strncpy(deviceName,d->name,1024);
			break;
		}
	}

	/* 디바이스 열기 */
	if((adhandle = pcap_open(deviceName, 65536, PCAP_OPENFLAG_PROMISCUOUS, 1000, NULL, errbuf)) == NULL){
		sprintf(logmsg,"[Error] Unable to open the adapter. not supported by WinPcap\n");
		log(logmsg);
		SendMessage(hC1, WM_SPOOF, SM_NODEVICE, NULL);
		pcap_freealldevs(alldevs);
		return -1;
	}

	if (d->addresses != NULL)
		lNetMask = ((struct sockaddr_in *)(d->addresses->netmask))->sin_addr.S_un.S_addr;
	else
		lNetMask = 0xffffff;

	ZeroMemory(&lFCode, sizeof(lFCode));
	if(pcap_compile(adhandle, &lFCode, "", 1, lNetMask) < 0 ) {
		log("[Error] Unable to compile the packet filter. \n");
		exit(1);
	}

	if(pcap_setfilter(adhandle, &lFCode) < 0 ) {
		log("[Error] Error setting the filter.\n");
	}

	/* 로그기록 */
	sprintf(logmsg, "[Info] %s Device Opened\n\r", d->description);
	log(logmsg);
	/* 네트워크 디바이스 목록 해제 */
	pcap_freealldevs(alldevs);
	return 0;
}
Exemplo n.º 20
0
Arquivo: readfile.c Projeto: 52M/npcap
int main(int argc, char **argv)
{
pcap_t *fp;
char errbuf[PCAP_ERRBUF_SIZE];
char source[PCAP_BUF_SIZE];

	if(argc != 2){

		printf("usage: %s filename", argv[0]);
		return -1;

	}

	/* Create the source string according to the new WinPcap syntax */
	if ( pcap_createsrcstr(	source,			// variable that will keep the source string
							PCAP_SRC_FILE,	// we want to open a file
							NULL,			// remote host
							NULL,			// port on the remote host
							argv[1],		// name of the file we want to open
							errbuf			// error buffer
							) != 0)
	{
		fprintf(stderr,"\nError creating a source string\n");
		return -1;
	}
	
	/* Open the capture file */
	if ( (fp= pcap_open(source,			// name of the device
						65536,			// portion of the packet to capture
										// 65536 guarantees that the whole packet will be captured on all the link layers
						 PCAP_OPENFLAG_PROMISCUOUS, 	// promiscuous mode
						 1000,				// read timeout
						 NULL,				// authentication on the remote machine
						 errbuf			// error buffer
						 ) ) == NULL)
	{
		fprintf(stderr,"\nUnable to open the file %s.\n", source);
		return -1;
	}

	// read and dispatch packets until EOF is reached
	pcap_loop(fp, 0, dispatcher_handler, NULL);

	return 0;
}
int nbNetVmPortLocalAdapter::OpenAsDataSrc()
{
	int IsPromiscuous;
	char errbuf[PCAP_ERRBUF_SIZE];

	if (nbFLAG_ISSET(Flags, nbNETDEVICE_PROMISCUOUS))
		IsPromiscuous = PCAP_OPENFLAG_PROMISCUOUS;
	else
		IsPromiscuous = 0;

	m_WinPcapDevice = pcap_open(Name,65535,IsPromiscuous,1000,NULL,errbuf);
 
	if (m_WinPcapDevice == NULL)
		
			return nbFAILURE;
		
	return nbSUCCESS;
}
Exemplo n.º 22
0
static void prvOpenSelectedNetworkInterface( pcap_if_t *pxAllNetworkInterfaces )
{
pcap_if_t *xInterface;
long x;

    /* Walk the list of devices until the selected device is located. */
	xInterface = pxAllNetworkInterfaces;
    for( x = 0L; x < ( configNETWORK_INTERFACE_TO_USE - 1L ); x++ )
	{
		xInterface = xInterface->next;
	}

    /* Open the selected interface. */
	pxOpenedInterfaceHandle = pcap_open(	xInterface->name,          	/* The name of the selected interface. */
											UIP_CONF_BUFFER_SIZE, 		/* The size of the packet to capture. */
											PCAP_OPENFLAG_PROMISCUOUS,	/* Open in promiscious mode as the MAC and 
																		IP address is going to be "simulated", and 
																		not be the real MAC and IP address.  This allows
																		trafic to the simulated IP address to be routed
																		to uIP, and trafic to the real IP address to be
																		routed to the Windows TCP/IP stack. */
											0xfffffffL,             	/* The read time out.  This is going to block
																		until data is available. */
											NULL,             			/* No authentication is required as this is
																		not a remote capture session. */
											cErrorBuffer            
									   );
									   
    if ( pxOpenedInterfaceHandle == NULL )
    {
        printf( "\r\n%s is not supported by WinPcap and cannot be opened\r\n", xInterface->name );
    }
	else
	{
		/* Configure the capture filter to allow blocking reads, and to filter 
		out packets that are not of interest to this demo. */
		prvConfigureCaptureBehaviour();
	}

	/* The device list is no longer required. */
	pcap_freealldevs( pxAllNetworkInterfaces );
}
Exemplo n.º 23
0
static pcap_t *select_interface_by_id(int id) 
{
	pcap_if_t *alldevs;
	pcap_if_t *dev;
	pcap_t *res = NULL;
	char errbuf[PCAP_ERRBUF_SIZE + 1];
	int i;

	if(pcap_findalldevs_ex("rpcap://", NULL, &alldevs, errbuf) == -1) { /* TODO: "rpcap://" -> PCAP_SRC_IF_STRING */
		fprintf(stderr,"Error in pcap_findalldevs_ex: %s\n", errbuf);
		return NULL;
	}

	for(dev=alldevs, i=0; dev != NULL; dev=dev->next, i++ ) {
		if(i == id) {
			res = pcap_open(dev->name,
					2048,	/* TODO: ? */
					1 | 16,	/* TODO: 1 | 16 -> PCAP_OPENFLAG_PROMISCUOUS | PCAP_OPENFLAG_MAX_RESPONSIVENESS */
					1000,
					NULL,
					errbuf);

			if(!res) {
				fprintf(stderr,"Unable to open the adapter.\n");
				return NULL;
			}

			pcap_setmintocopy(res, 0);

			break;
		}
	}

	if(dev == 0) {
		printf("No interfaces found!\n");
		return NULL;
	}

	pcap_freealldevs(alldevs);

	return res;
}
Exemplo n.º 24
0
/** Basic setup to connect NIC to socket.
* @param[in] port        = port context struct
* @param[in] ifname       = Name of NIC device, f.e. "eth0"
* @param[in] secondary      = if >0 then use secondary stack instead of primary
* @return >0 if succeeded
*/
int ecx_portt::setupnic(const char *ifname, pcap_t **psock)
{
	/* we use pcap socket to send RAW packets in windows user mode*/
	*psock = pcap_open(ifname, 65536, PCAP_OPENFLAG_PROMISCUOUS |
		PCAP_OPENFLAG_MAX_RESPONSIVENESS |
		PCAP_OPENFLAG_NOCAPTURE_LOCAL, -1, NULL, errbuf);
	if (NULL == *psock)
	{
		printf("interface %s could not open with pcap\n", ifname);
		return 0;
	}

	for (int i = 0; i < EC_MAXBUF; i++)
	{
		ec::setupheader(&(this->txbuf[i]));
		this->rxbufstat[i] = EC_BUF_EMPTY;
	}
	ec::setupheader(&(this->txbuf2));

	return 1;
}
Exemplo n.º 25
0
int uaenet_open (void *vsd, struct netdriverdata *tc, void *user, uaenet_gotfunc *gotfunc, uaenet_getfunc *getfunc, int promiscuous)
{
	struct uaenetdatawin32 *sd = (struct uaenetdatawin32*)vsd;
	char *s;

	s = ua (tc->name);
	sd->fp = pcap_open (s, 65536, (promiscuous ? PCAP_OPENFLAG_PROMISCUOUS : 0) | PCAP_OPENFLAG_MAX_RESPONSIVENESS, 100, NULL, sd->errbuf);
	xfree (s);
	if (sd->fp == NULL) {
		TCHAR *ss = au (sd->errbuf);
		write_log (L"'%s' failed to open: %s\n", tc->name, ss);
		xfree (ss);
		return 0;
	}
	sd->tc = tc;
	sd->user = user;
	sd->evttw = CreateEvent (NULL, FALSE, FALSE, NULL);

	if (!sd->evttw)
		goto end;
	sd->mtu = tc->mtu;
	sd->readbuffer = xmalloc (uae_u8, sd->mtu);
	sd->writebuffer = xmalloc (uae_u8, sd->mtu);
	sd->gotfunc = gotfunc;
	sd->getfunc = getfunc;

	uae_sem_init (&sd->change_sem, 0, 1);
	uae_sem_init (&sd->sync_semr, 0, 0);
	uae_start_thread (L"uaenet_win32r", uaenet_trap_threadr, sd, &sd->tidr);
	uae_sem_wait (&sd->sync_semr);
	uae_sem_init (&sd->sync_semw, 0, 0);
	uae_start_thread (L"uaenet_win32w", uaenet_trap_threadw, sd, &sd->tidw);
	uae_sem_wait (&sd->sync_semw);
	write_log (L"uaenet_win32 initialized\n");
	return 1;

end:
	uaenet_close (sd);
	return 0;
}
Exemplo n.º 26
0
void tf_peer_dump_rfx(freerdp_peer* client)
{
	wStream* s;
	UINT32 prev_seconds;
	UINT32 prev_useconds;
	rdpUpdate* update;
	rdpPcap* pcap_rfx;
	pcap_record record;

	s = Stream_New(NULL, 512);
	update = client->update;
	client->update->pcap_rfx = pcap_open(test_pcap_file, FALSE);
	pcap_rfx = client->update->pcap_rfx;

	if (pcap_rfx == NULL)
		return;

	prev_seconds = prev_useconds = 0;

	while (pcap_has_next_record(pcap_rfx))
	{
		pcap_get_next_record_header(pcap_rfx, &record);

		Stream_Buffer(s) = realloc(Stream_Buffer(s), record.length);
		record.data = Stream_Buffer(s);
		Stream_Capacity(s) = record.length;

		pcap_get_next_record_content(pcap_rfx, &record);
		Stream_Pointer(s) = Stream_Buffer(s) + Stream_Capacity(s);

		if (test_dump_rfx_realtime && test_sleep_tsdiff(&prev_seconds, &prev_useconds, record.header.ts_sec, record.header.ts_usec) == FALSE)
			break;

		update->SurfaceCommand(update->context, s);

		if (client->CheckFileDescriptor(client) != TRUE)
			break;
	}
}
Exemplo n.º 27
0
int 
main(int argc, const char** argv)
{
    if (2 > argc) {
        print_help();
        return 0;
    }
    
    pcap cap;
    
    if (QP_ERROR == pcap_open(argv[1], &cap)) {
        return QP_ERROR;
    }
    
    cap.pkt_process = pcap_process;

    pcap_read(&cap);
    
    pcap_close(&cap);
    
    return 0;
}
Exemplo n.º 28
0
/** Creates a new connection based on the settings found in the "instance" parameter
 *  It will use the callbacks registered on the structure to process the pre/post connect operations
 *  that the caller requires.
 *  @see struct rdp_freerdp in freerdp.h
 *
 *  @param instance - pointer to a rdp_freerdp structure that contains base information to establish the connection.
 *  				  On return, this function will be initialized with the new connection's settings.
 *
 *  @return TRUE if successful. FALSE otherwise.
 *
 */
BOOL freerdp_connect(freerdp* instance)
{
	rdpRdp* rdp;
	rdpSettings* settings;
	BOOL status = FALSE;
	ConnectionResultEventArgs e;

	/* We always set the return code to 0 before we start the connect sequence*/
	connectErrorCode = 0;

	rdp = instance->context->rdp;
	settings = instance->settings;

	IFCALLRET(instance->PreConnect, status, instance);

	if (settings->KeyboardLayout == KBD_JAPANESE_INPUT_SYSTEM_MS_IME2002)
	{
		settings->KeyboardType = 7;
		settings->KeyboardSubType = 2;
		settings->KeyboardFunctionKey = 12;
	}

	extension_load_and_init_plugins(rdp->extension);
	extension_pre_connect(rdp->extension);

	if (!status)
	{
		if (!connectErrorCode)
		{
			connectErrorCode = PREECONNECTERROR;
		}
		fprintf(stderr, "%s:%d: freerdp_pre_connect failed\n", __FILE__, __LINE__);

		goto freerdp_connect_finally;
	}

	status = rdp_client_connect(rdp);

	/* --authonly tests the connection without a UI */
	if (instance->settings->AuthenticationOnly)
	{
		fprintf(stderr, "%s:%d: Authentication only, exit status %d\n", __FILE__, __LINE__, !status);
		goto freerdp_connect_finally;
	}

	if (status)
	{
		if (instance->settings->DumpRemoteFx)
		{
			instance->update->pcap_rfx = pcap_open(instance->settings->DumpRemoteFxFile, TRUE);
			if (instance->update->pcap_rfx)
				instance->update->dump_rfx = TRUE;
		}

		extension_post_connect(rdp->extension);

		IFCALLRET(instance->PostConnect, status, instance);
		update_post_connect(instance->update);

		if (!status)
		{
			fprintf(stderr, "freerdp_post_connect failed\n");

			if (!connectErrorCode)
			{
				connectErrorCode = POSTCONNECTERROR;
			}

			goto freerdp_connect_finally;
		}

		if (instance->settings->PlayRemoteFx)
		{
			wStream* s;
			rdpUpdate* update;
			pcap_record record;

			update = instance->update;

			update->pcap_rfx = pcap_open(settings->PlayRemoteFxFile, FALSE);

			if (!update->pcap_rfx)
			{
				status = FALSE;
				goto freerdp_connect_finally;
			}
			else
			{
				update->play_rfx = TRUE;
			}

			while (pcap_has_next_record(update->pcap_rfx))
			{

				pcap_get_next_record_header(update->pcap_rfx, &record);

				s = StreamPool_Take(rdp->transport->ReceivePool, record.length);
				record.data = Stream_Buffer(s);

				pcap_get_next_record_content(update->pcap_rfx, &record);
				Stream_SetLength(s,record.length);
				Stream_SetPosition(s, 0);

				update->BeginPaint(update->context);
				update_recv_surfcmds(update, Stream_Length(s) , s);
				update->EndPaint(update->context);
				Stream_Release(s);
			
				StreamPool_Return(rdp->transport->ReceivePool, s);
			}

			pcap_close(update->pcap_rfx);
			update->pcap_rfx = NULL;
			status = TRUE;
			goto freerdp_connect_finally;
		}
	}

	if (rdp->errorInfo == ERRINFO_SERVER_INSUFFICIENT_PRIVILEGES)
	{
		connectErrorCode = INSUFFICIENTPRIVILEGESERROR;
	}

	if (!connectErrorCode)
	{
		connectErrorCode = UNDEFINEDCONNECTERROR;
	}

	SetEvent(rdp->transport->connectedEvent);

	freerdp_connect_finally:

	EventArgsInit(&e, "freerdp");
	e.result = status ? 0 : -1;
	PubSub_OnConnectionResult(instance->context->pubSub, instance->context, &e);

	return status;
}
Exemplo n.º 29
0
main()
{
pcap_if_t *alldevs;
pcap_if_t *d;
int inum;
int i=0;
pcap_t *adhandle;
int res;
char errbuf[PCAP_ERRBUF_SIZE];
struct tm *ltime;
char timestr[16];
struct pcap_pkthdr *header;
u_char *pkt_data;
	
    
	/* Retrieve the device list on the local machine */
	if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1)
	{
		fprintf(stderr,"Error in pcap_findalldevs: %s\n", errbuf);
		exit(1);
	}
    
    /* Print the list */
    for(d=alldevs; d; d=d->next)
    {
        printf("%d. %s", ++i, d->name);
        if (d->description)
            printf(" (%s)\n", d->description);
        else
            printf(" (No description available)\n");
    }
	
    if(i==0)
    {
        printf("\nNo interfaces found! Make sure WinPcap is installed.\n");
        return -1;
    }
    
    printf("Enter the interface number (1-%d):",i);
    scanf("%d", &inum);
    
    if(inum < 1 || inum > i)
    {
        printf("\nInterface number out of range.\n");
        /* Free the device list */
        pcap_freealldevs(alldevs);
        return -1;
    }
	
    /* Jump to the selected adapter */
    for(d=alldevs, i=0; i< inum-1 ;d=d->next, i++);
    
	/* Open the device */
	if ( (adhandle= pcap_open(d->name,			// name of the device
							  65536,			// portion of the packet to capture. 
												// 65536 guarantees that the whole packet will be captured on all the link layers
							  PCAP_OPENFLAG_PROMISCUOUS, 	// promiscuous mode
							  1000,				// read timeout
							  NULL,				// authentication on the remote machine
							  errbuf			// error buffer
							  ) ) == NULL)
	{
		fprintf(stderr,"\nUnable to open the adapter. %s is not supported by WinPcap\n", d->name);
		/* Free the device list */
		pcap_freealldevs(alldevs);
		return -1;
	}
    
    printf("\nlistening on %s...\n", d->description);
	
    /* At this point, we don't need any more the device list. Free it */
    pcap_freealldevs(alldevs);
	
	/* Retrieve the packets */
	while((res = pcap_next_ex( adhandle, &header, &pkt_data)) >= 0){
		
		if(res == 0)
			/* Timeout elapsed */
			continue;
		
		/* convert the timestamp to readable format */
		ltime=localtime(&header->ts.tv_sec);
		strftime( timestr, sizeof timestr, "%H:%M:%S", ltime);
		
		printf("%s,%.6d len:%d\n", timestr, header->ts.tv_usec, header->len);
	}
	
	if(res == -1){
		printf("Error reading the packets: %s\n", pcap_geterr(adhandle));
		return -1;
	}
	
    return 0;
}
Exemplo n.º 30
0
int main(){
	pcap_if_t *alldevs;
	pcap_if_t *d;
	int inum;
	int i = 0;
	pcap_t *adhandle;
	int res;
	char errbuf[PCAP_ERRBUF_SIZE];
	struct tm *ltime;
	char timestr[16];
	struct pcap_pkthdr *header;
	const u_char *pkt_data;
	time_t local_tv_sec;


	/* 获取本机设备列表 */
	if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1)
	{
		fprintf(stderr, "Error in pcap_findalldevs: %s\n", errbuf);
		exit(1);
	}

	/* 打印列表 */
	for (d = alldevs; d; d = d->next)
	{
		printf("%d. %s", ++i, d->name);
		if (d->description)
			printf(" (%s)\n", d->description);
		else
			printf(" (No description available)\n");
	}

	if (i == 0)
	{
		printf("\nNo interfaces found! Make sure WinPcap is installed.\n");
		return -1;
	}

	printf("Enter the interface number (1-%d):", i);
	scanf("%d", &inum);

	if (inum < 1 || inum > i)
	{
		printf("\nInterface number out of range.\n");
		/* 释放设备列表 */
		pcap_freealldevs(alldevs);
		return -1;
	}

	/* 跳转到已选中的适配器 */
	for (d = alldevs, i = 0; i< inum - 1; d = d->next, i++);

	/* 打开设备 */
	if ((adhandle = pcap_open(d->name,          // 设备名
		65536,            // 要捕捉的数据包的部分 
		// 65535保证能捕获到不同数据链路层上的每个数据包的全部内容
		PCAP_OPENFLAG_PROMISCUOUS,    // 混杂模式
		1000,             // 读取超时时间
		NULL,             // 远程机器验证
		errbuf            // 错误缓冲池
		)) == NULL)
	{
		fprintf(stderr, "\nUnable to open the adapter. %s is not supported by WinPcap\n", d->name);
		/* 释放设列表 */
		pcap_freealldevs(alldevs);
		return -1;
	}

	printf("\nlistening on %s...\n", d->description);

	/* 释放设备列表 */
	pcap_freealldevs(alldevs);

	/* 获取数据包 */
	while ((res = pcap_next_ex(adhandle, &header, &pkt_data)) >= 0){

		if (res == 0)
			/* 超时时间到 */
			continue;

		/* 将时间戳转换成可识别的格式 */
		local_tv_sec = header->ts.tv_sec;
		ltime = localtime(&local_tv_sec);
		strftime(timestr, sizeof timestr, "%H:%M:%S", ltime);

		printf("%s,%.6d len:%d\n", timestr, header->ts.tv_usec, header->len);
	}

	if (res == -1){
		printf("Error reading the packets: %s\n", pcap_geterr(adhandle));
		return -1;
	}

	return 0;
}