Start a packet capture in uBridge.

        :param adapter_number: adapter number
        :param output_file: PCAP destination file for the capture
175265
def _start_ubridge_capture(self, adapter_number, output_file):
        

        vnet = "ethernet{}.vnet".format(adapter_number)
        if vnet not in self._vmx_pairs:
            raise VMwareError("vnet {} not in VMX file".format(vnet))
        if not self._ubridge_hypervisor:
            raise VMwareError("Cannot start the packet capture: uBridge is not running")
        yield from self._ubridge_send('bridge start_capture {name} "{output_file}"'.format(name=vnet,
                                                                                           output_file=output_file))
20356
def _delete_ubridge_connection(self, adapter_number):
        

        vnet = "ethernet{}.vnet".format(adapter_number)
        if vnet not in self._vmx_pairs:
            raise VMwareError("vnet {} not in VMX file".format(vnet))
        yield from self._ubridge_send("bridge delete {name}".format(name=vnet))
978444
def start_capture(self, port_number, output_file, data_link_type="DLT_EN10MB"):
        

        if port_number not in self._mappings:
            raise DynamipsError("Port {} is not allocated".format(port_number))

        nio = self._mappings[port_number]

        data_link_type = data_link_type.lower()
        if data_link_type.startswith("dlt_"):
            data_link_type = data_link_type[4:]

        if nio.input_filter[0] is not None and nio.output_filter[0] is not None:
            raise DynamipsError("Port {} has already a filter applied".format(port_number))

        yield from nio.bind_filter("both", "capture")
        yield from nio.setup_filter("both", '{} "{}"'.format(data_link_type, output_file))

        log.info('Ethernet hub "{name}" [{id}]: starting packet capture on port {port}'.format(name=self._name,
                                                                                               id=self._id,
                                                                                               port=port_number))
363482
def stop_capture(self, port_number):
        

        if not self._ethernet_adapter.port_exists(port_number):
            raise VPCSError("Port {port_number} doesn't exist in adapter {adapter}".format(adapter=self._ethernet_adapter,
                                                                                           port_number=port_number))

        nio = self._ethernet_adapter.get_nio(0)

        if not nio:
            raise VPCSError("Port {} is not connected".format(port_number))

        nio.stopPacketCapture()

        if self.ubridge:
            yield from self._ubridge_send('bridge stop_capture {name}'.format(name="VPCS-{}".format(self._id)))

        log.info("VPCS '{name}' [{id}]: stopping packet capture on port {port_number}".format(name=self.name,
                                                                                              id=self.id,
                                                                                              port_number=port_number))
997408
def _low_level_dispatch(pcapdev, devname, pktqueue):
        '''
        
        '''
        while LLNetReal.running:
            # a non-zero timeout value is ok here; this is an
            # independent thread that handles input for this
            # one pcap device.  it throws any packets received
            # into the shared queue (which is read by the actual
            # user code)
            pktinfo = pcapdev.recv_packet(timeout=0.2)
            if pktinfo is None:
                continue
            pktqueue.put( (devname,pcapdev.dlt,pktinfo) )

        log_debug("Receiver thread for {} exiting".format(devname))
        stats = pcapdev.stats()
        log_debug("Final device statistics {}: {} received, {} dropped, {} dropped/if".format(devname, stats.ps_recv, stats.ps_drop, stats.ps_ifdrop))
1038291
def get_transport_target(cls, instance, timeout, retries):
        '''
        
        '''
        if "ip_address" not in instance:
            raise Exception("An IP address needs to be specified")
        ip_address = instance["ip_address"]
        port = int(instance.get("port", 161))  # Default SNMP port
        return hlapi.UdpTransportTarget((ip_address, port), timeout=timeout, retries=retries)
711994
def application(handler, adapter_cls=WerkzeugAdapter):
    
    adapter = adapter_cls()

    def wrapper(environ, start_response):
        request = adapter.to_request(environ)
        response = handler(request)
        response_func = adapter.from_response(response)
        return response_func(environ, start_response)

    return wrapper
1244895
def read_interface(self):
        """"""

        # Spin up the packet capture
        if self._iface_is_file():
            self.pcap = pcapy.open_offline(self.iface_name)
        else:
            try:
                # self.pcap = pcap.pcap(name=self.iface_name, promisc=True, immediate=True)
                #   snaplen (maximum number of bytes to capture _per_packet_)
                #   promiscious mode (1 for true)
                #   timeout (in milliseconds)
                self.pcap = pcapy.open_live(self.iface_name, 65536 , 1 , 0)
            except OSError:
                try:
                    logger.warning('Could not get promisc mode, turning flag off')
                    self.pcap = pcapy.open_live(self.iface_name, 65536 , 0 , 0)
                except OSError:
                    log_utils.panic('Could no open interface with any options (may need to be sudo)')

        # Add the BPF if it's specified
        if self.bpf:
            self.pcap.setfilter(self.bpf)
        print('listening on %s: %s' % (self.iface_name, self.bpf))

        # For each packet in the pcap process the contents
        _packets = 0
        while True:
            # Grab the next header and packet buffer
            header, raw_buf = self.pcap.next()

            # If we don't get a packet header break out of the loop
            if not header:
                break;

            # Extract the timestamp from the header and yield the packet
            seconds, micro_sec = header.getts()
            timestamp = seconds + micro_sec * 10**-6
            yield {'timestamp': timestamp, 'raw_buf': raw_buf, 'packet_num': _packets}
            _packets += 1

            # Is there a max packets set if so break on it
            if self.max_packets and _packets >= self.max_packets:
                break

        # All done so report and raise a StopIteration
        try:
            print('Packet stats: %d  received, %d dropped,  %d dropped by interface' % self.pcap.stats())
        except pcapy.PcapError:
            print('No stats available...')
        raise StopIteration
1235214
def start_capture(self, *ports):
        

        IxeCapture.current_object = None
        IxeCaptureBuffer.current_object = None
        if not ports:
            ports = self.ports.values()
        for port in ports:
            port.captureBuffer = None
        port_list = self.set_ports_list(*ports)
        self.api.call_rc('ixStartCapture {}'.format(port_list))
800281
def make_witness_input(outpoint, sequence):
    '''
    
    '''
    if 'decred' in riemann.get_current_network_name():
        return tx.DecredTxIn(
            outpoint=outpoint,
            sequence=utils.i2le_padded(sequence, 4))
    return tx.TxIn(outpoint=outpoint,
                   stack_script=b'',
                   redeem_script=b'',
                   sequence=utils.i2le_padded(sequence, 4))
302348
function createDebugFileRouter(adapterPool) {
    var router = express.Router();

    router.get('/:connectionId/:referenceId/*', function(req, res) {
        if (!adapterPool.has(req.params.connectionId)) {
            res.sendStatus(404);
            return;
        }
        var adapter = adapterPool.get(req.params.connectionId);
        adapter.sendRequest('source', { sourceReference: parseInt(req.params.referenceId, 10) }, TIMEOUT, function(response) {
            if (!response.success) {
                res.sendStatus(404);
                return;
            } else {
                if (response.body.mimeType) {
                    res.setHeader('Content-Type', response.body.mimeType);
                }
                res.write(response.body.content);
                res.end();
            }
        });
    });

    return router;
}
1082163
def start_capture(self, adapter_number, output_file):
        

        try:
            adapter = self._ethernet_adapters[adapter_number]
        except KeyError:
            raise DockerError("Adapter {adapter_number} doesn't exist on Docker VM '{name}'".format(name=self.name,
                                                                                                    adapter_number=adapter_number))

        nio = adapter.get_nio(0)

        if not nio:
            raise DockerError("Adapter {} is not connected".format(adapter_number))

        if nio.capturing:
            raise DockerError("Packet capture is already activated on adapter {adapter_number}".format(adapter_number=adapter_number))

        nio.startPacketCapture(output_file)

        if self.status == "started" and self.ubridge:
            yield from self._start_ubridge_capture(adapter_number, output_file)

        log.info("Docker VM '{name}' [{id}]: starting packet capture on adapter {adapter_number}".format(name=self.name,
                                                                                                         id=self.id,
                                                                                                         adapter_number=adapter_number))
1370350
def send_packet(self, dataOut):
        
        try:
            if (pyusb1 is False):
                self.handle.bulkWrite(1, dataOut, 20)
            else:
                self.handle.write(endpoint=1, data=dataOut, timeout=20)
        except usb.USBError:
            pass
526872
def _add_ubridge_connection(self, nio, port_number):
        

        port_info = None
        for port in self._ports_mapping:
            if port["port_number"] == port_number:
                port_info = port
                break

        if not port_info:
            raise NodeError("Port {port_number} doesn't exist on cloud '{name}'".format(name=self.name,
                                                                                        port_number=port_number))

        bridge_name = "{}-{}".format(self._id, port_number)
        yield from self._ubridge_send("bridge create {name}".format(name=bridge_name))
        if not isinstance(nio, NIOUDP):
            raise NodeError("Source NIO is not UDP")
        yield from self._ubridge_send('bridge add_nio_udp {name} {lport} {rhost} {rport}'.format(name=bridge_name,
                                                                                                 lport=nio.lport,
                                                                                                 rhost=nio.rhost,
                                                                                                 rport=nio.rport))

        yield from self._ubridge_apply_filters(bridge_name, nio.filters)
        if port_info["type"] in ("ethernet", "tap"):

            if sys.platform.startswith("win"):
                yield from self._add_ubridge_ethernet_connection(bridge_name, port_info["interface"])

            else:

                if port_info["type"] == "ethernet":
                    network_interfaces = [interface["name"] for interface in self._interfaces()]
                    if not port_info["interface"] in network_interfaces:
                        raise NodeError("Interface '{}' could not be found on this system".format(port_info["interface"]))

                    if sys.platform.startswith("linux"):
                        yield from self._add_linux_ethernet(port_info, bridge_name)
                    elif sys.platform.startswith("darwin"):
                        yield from self._add_osx_ethernet(port_info, bridge_name)
                    else:
                        yield from self._add_windows_ethernet(port_info, bridge_name)

                elif port_info["type"] == "tap":
                    yield from self._ubridge_send('bridge add_nio_tap {name} "{interface}"'.format(name=bridge_name, interface=port_info["interface"]))

        elif port_info["type"] == "udp":
            yield from self._ubridge_send('bridge add_nio_udp {name} {lport} {rhost} {rport}'.format(name=bridge_name,
                                                                                                     lport=port_info["lport"],
                                                                                                     rhost=port_info["rhost"],
                                                                                                     rport=port_info["rport"]))

        if nio.capturing:
            yield from self._ubridge_send('bridge start_capture {name} "{pcap_file}"'.format(name=bridge_name,
                                                                                             pcap_file=nio.pcap_output_file))

        yield from self._ubridge_send('bridge start {name}'.format(name=bridge_name))
1058093
def start_capture(self, adapter_number, output_file):
        

        try:
            adapter = self._ethernet_adapters[adapter_number]
        except KeyError:
            raise VirtualBoxError("Adapter {adapter_number} doesn't exist on VirtualBox VM '{name}'".format(name=self.name,
                                                                                                            adapter_number=adapter_number))

        nio = adapter.get_nio(0)

        if not nio:
            raise VirtualBoxError("Adapter {} is not connected".format(adapter_number))

        if nio.capturing:
            raise VirtualBoxError("Packet capture is already activated on adapter {adapter_number}".format(adapter_number=adapter_number))

        nio.startPacketCapture(output_file)

        if self.ubridge:
            yield from self._ubridge_send('bridge start_capture {name} "{output_file}"'.format(name="VBOX-{}-{}".format(self._id, adapter_number),
                                                                                               output_file=output_file))

        log.info("VirtualBox VM '{name}' [{id}]: starting packet capture on adapter {adapter_number}".format(name=self.name,
                                                                                                             id=self.id,
                                                                                                             adapter_number=adapter_number))
1361853
def wrpcap(filename, pkt, *args, **kargs):
    """"""
    with PcapWriter(filename, *args, **kargs) as pcap:
        pcap.write(pkt)
465063
def adapter_add_nio_binding(self, adapter_number, nio):
        

        try:
            adapter = self._ethernet_adapters[adapter_number]
        except IndexError:
            raise VMwareError("Adapter {adapter_number} doesn't exist on VMware VM '{name}'".format(name=self.name,
                                                                                                    adapter_number=adapter_number))

        self._read_vmx_file()
        # check if trying to connect to a nat, bridged or host-only adapter
        if self._get_vmx_setting("ethernet{}.present".format(adapter_number), "TRUE"):
            # check for the connection type
            connection_type = "ethernet{}.connectiontype".format(adapter_number)
            if connection_type in self._vmx_pairs and self._vmx_pairs[connection_type] in ("nat", "bridged", "hostonly"):
                if not self._use_any_adapter:
                    raise VMwareError("Attachment '{attachment}' is already configured on network adapter {adapter_number}. "
                                      "Please remove it or allow VMware VM '{name}' to use any adapter.".format(attachment=self._vmx_pairs[connection_type],
                                                                                                                adapter_number=adapter_number,
                                                                                                                name=self.name))
                elif (yield from self.is_running()):
                    raise VMwareError("Attachment '{attachment}' is configured on network adapter {adapter_number}. "
                                      "Please stop VMware VM '{name}' to link to this adapter and allow GNS3 to change the attachment type.".format(attachment=self._vmx_pairs[connection_type],
                                                                                                                                                    adapter_number=adapter_number,
                                                                                                                                                    name=self.name))

        adapter.add_nio(0, nio)
        if self._started and self._ubridge_hypervisor:
            yield from self._add_ubridge_connection(nio, adapter_number)

        log.info("VMware VM '{name}' [{id}]: {nio} added to adapter {adapter_number}".format(name=self.name,
                                                                                             id=self.id,
                                                                                             nio=nio,
                                                                                             adapter_number=adapter_number))