capture_udp_packets

    Capture ``UDP`` packets and call the ``handle_packets`` method

    Change the network interface by ``export CAP_DEVICE=eth0``
17076
def capture_udp_packets():
    
    dev = ev(
        "CAP_DEVICE",
        "lo")

    """
    Ignore ports for forwarding to consolidators:

    Redis VM: 6379, 16379
    RabbitMQ VM: 5672, 15672, 25672

    """

    # http://biot.com/capstats/bpf.html
    default_filter = "udp"
    custom_filter = ev(
        "NETWORK_FILTER",
        default_filter)

    log.info(("starting device={} filter={}")
             .format(
                dev,
                custom_filter))

    kamene.sniff(
        filter=custom_filter,
        prn=handle_packets)

    log.info("done")
2658
def emit(self, batch):
        
        udp_socket = None
        try:
            self.client._seqid = 0
            #  truncate and reset the position of BytesIO object
            self.buffer._buffer.truncate(0)
            self.buffer._buffer.seek(0)
            self.client.emitBatch(batch)
            buff = self.buffer.getvalue()
            if len(buff) > self.max_packet_size:
                logging.warn('Data exceeds the max UDP packet size; size {},\
                        max {}'.format(len(buff), self.max_packet_size))
            else:
                udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                udp_socket.sendto(buff, self.address)

        except Exception as e:  # pragma: NO COVER
            logging.error(getattr(e, 'message', e))

        finally:
            if udp_socket is not None:
                udp_socket.close()
25703
def _vpn_signal_handler(self, args):
        """"""
        # Args is a dictionary of changed properties
        # We only care about changes in ActiveConnections
        active = "ActiveConnections"
        # Compare current ActiveConnections to last seen ActiveConnections
        if active in args.keys() and sorted(self.active) != sorted(args[active]):
            self.active = args[active]
            self.py3.update()
1301232
def send(self, out, addr=_MDNS_ADDR, port=_MDNS_PORT):
        """"""
        # This is a quick test to see if we can parse the packets we generate
        #temp = DNSIncoming(out.packet())
        for i in self.intf.values():
            try:
                return i.sendto(out.packet(), 0, (addr, port))
            except:
                traceback.print_exc()
                # Ignore this, it may be a temporary loss of network connection
                return -1
373208
def _process(self, data_buffer):
        
        packet = json.loads(data_buffer)

        if packet['cmd'] == 'out':
            # Call os.write manually. In Python2.6, sys.stdout.write doesn't use UTF-8.
            original_mode = DWORD(0)
            windll.kernel32.GetConsoleMode(self._hconsole, byref(original_mode))

            windll.kernel32.SetConsoleMode(self._hconsole, DWORD(
                ENABLE_PROCESSED_INPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING))

            try:
                os.write(sys.stdout.fileno(), packet['data'].encode('utf-8'))
            finally:
                windll.kernel32.SetConsoleMode(self._hconsole, original_mode)

        elif packet['cmd'] == 'suspend':
            # Suspend client process to background.
            pass

        elif packet['cmd'] == 'mode':
            pass
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
177991
def send(self, packet, interfaces=None):
        """"""
        interfaces = interfaces or self.interfaces  # default to all interfaces
        interfaces = interfaces if hasattr(interfaces, '__iter__') else [interfaces]

        for interface in interfaces:
            for f in self.filters:
                packet = f.tx(packet, interface)  # run outgoing packet through the filters
            if packet:
                # if not dropped, log the transmit and pass it to the interface's send method
                # self.log("OUT     ", ("<"+",".join(i.name for i in interfaces)+">").ljust(30), packet.decode())
                interface.send(packet)
1276605
def stop_capture(self, port_number):
        

        if not [port["port_number"] for port in self._ports_mapping if port_number == port["port_number"]]:
            raise NodeError("Port {port_number} doesn't exist on cloud '{name}'".format(name=self.name,
                                                                                        port_number=port_number))

        if port_number not in self._nios:
            raise NodeError("Port {} is not connected".format(port_number))

        nio = self._nios[port_number]
        nio.stopPacketCapture()
        bridge_name = "{}-{}".format(self._id, port_number)
        yield from self._ubridge_send("bridge stop_capture {name}".format(name=bridge_name))

        log.info("Cloud'{name}' [{id}]: stopping packet capture on port {port_number}".format(name=self.name,
                                                                                              id=self.id,
                                                                                              port_number=port_number))
472083
def packet_in_handler(self, evt):
        """"""
        msg = evt.msg
        dpid = msg.datapath.id

        req_pkt = packet.Packet(msg.data)
        req_igmp = req_pkt.get_protocol(igmp.igmp)
        if req_igmp:
            if self._querier.dpid == dpid:
                self._querier.packet_in_handler(req_igmp, msg)
            else:
                self._snooper.packet_in_handler(req_pkt, req_igmp, msg)
        else:
            self.send_event_to_observers(EventPacketIn(msg))
1069610
def _choose_capture_side(self):
        

        ALWAYS_RUNNING_NODES_TYPE = ("cloud", "nat", "ethernet_switch", "ethernet_hub")

        for node in self._nodes:
            if node["node"].compute.id == "local" and node["node"].node_type in ALWAYS_RUNNING_NODES_TYPE and node["node"].status == "started":
                return node

        for node in self._nodes:
            if node["node"].node_type in ALWAYS_RUNNING_NODES_TYPE and node["node"].status == "started":
                return node

        for node in self._nodes:
            if node["node"].compute.id == "local" and node["node"].status == "started":
                return node

        for node in self._nodes:
            if node["node"].node_type and node["node"].status == "started":
                return node

        raise aiohttp.web.HTTPConflict(text="Cannot capture because there is no running device on this link")
863278
def _port_op(op_name, port, protocol="TCP"):
    """"""
    _args = [op_name]
    icmp = protocol.upper() == "ICMP"
    if icmp:
        _args.append(protocol)
    else:
        _args.append('{}/{}'.format(port, protocol))
    try:
        subprocess.check_call(_args)
    except subprocess.CalledProcessError:
        # Older Juju pre 2.3 doesn't support ICMP
        # so treat it as a no-op if it fails.
        if not icmp:
            raise
95813
def release_udp_port(self, port, project):
        

        if port in self._used_udp_ports:
            self._used_udp_ports.remove(port)
            project.remove_udp_port(port)
            log.debug("UDP port {} has been released".format(port))
549362
def start_capture(self, data_link_type="DLT_EN10MB", capture_file_name=None):
        

        self._capturing = True
        self._capture_file_name = capture_file_name
        self._streaming_pcap = asyncio.async(self._start_streaming_pcap())
        self._project.controller.notification.emit("link.updated", self.__json__())
582949
def save_bt_addr(self, packet, bt_addr):
        """"""
        if isinstance(packet, EddystoneUIDFrame):
            # remove out old mapping
            new_mappings = [m for m in self.eddystone_mappings if m[0] != bt_addr]
            new_mappings.append((bt_addr, packet.properties))
            self.eddystone_mappings = new_mappings
1269849
def stop_capture(self, adapter_number):
        

        try:
            adapter = self._ethernet_adapters[adapter_number]
        except IndexError:
            raise QemuError('Adapter {adapter_number} does not exist on QEMU VM "{name}"'.format(name=self._name,
                                                                                                 adapter_number=adapter_number))
        nio = adapter.get_nio(0)

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

        nio.stopPacketCapture()

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

        log.info("QEMU VM '{name}' [{id}]: stopping packet capture on adapter {adapter_number}".format(name=self.name,
                                                                                                       id=self.id,
                                                                                                       adapter_number=adapter_number))
687682
def pack_ip_addr(addr):
    """"""
    addr, port = addr
    return socket.inet_aton(addr) + struct.pack('!H', port & _short_mask)
1037163
def stop_capture(self, adapter_number):
        

        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))

        nio.stopPacketCapture()

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

        log.info("VirtualBox VM '{name}' [{id}]: stopping packet capture on adapter {adapter_number}".format(name=self.name,
                                                                                                             id=self.id,
                                                                                                             adapter_number=adapter_number))