Remove byte stuffing from a TSIP packet.

    :param packet: TSIP packet with byte stuffing. The packet must already
        have been stripped or `ValueError` will be raised.
    :type packet: Binary string.
    :return: Packet without byte stuffing.
168829
def unstuff(packet):
    

    if is_framed(packet):
        raise ValueError('packet contains leading DLE and trailing DLE/ETX')
    else:
        return packet.replace(CHR_DLE + CHR_DLE, CHR_DLE)
247824
def unpack_bitstring(length, is_float, is_signed, bits):
    # type: (int, bool, bool, typing.Any) -> typing.Union[float, int]
    

    if is_float:
        types = {
            32: '>f',
            64: '>d'
        }

        float_type = types[length]
        value, = struct.unpack(float_type, bytearray(int(''.join(b), 2)  for b in grouper(bits, 8)))
    else:
        value = int(bits, 2)

        if is_signed and bits[0] == '1':
            value -= (1 << len(bits))

    return value
318036
def _pack(self, msg_type, payload):
        
        pb = payload.encode('utf-8')
        s = struct.pack('=II', len(pb), msg_type.value)
        return self.MAGIC.encode('utf-8') + s + pb
757801
def decap(self, orig_pkt):
        """"""
        if orig_pkt.name != Ether().name or orig_pkt.payload.name != MACsec().name:  # noqa: E501
            raise TypeError('cannot decapsulate MACsec packet, must be Ethernet/MACsec')  # noqa: E501
        packet = copy.deepcopy(orig_pkt)
        prev_layer = packet[MACsec].underlayer
        prev_layer.type = packet[MACsec].type
        next_layer = packet[MACsec].payload
        del prev_layer.payload
        if prev_layer.name == Ether().name:
            return Ether(raw(prev_layer / next_layer))
        return prev_layer / next_layer
25089
private void handleIncomingPacket(DatagramPacket packet) {
    SsdpResponse response = new ResponseParser().parse(packet);
    if (response == null) {
      // Unknown to protocol
      return;
    }
    if (response.getType().equals(SsdpResponse.Type.DISCOVERY_RESPONSE)) {
      handleDiscoveryResponse(response);
    } else if (response.getType().equals(SsdpResponse.Type.PRESENCE_ANNOUNCEMENT)) {
      handlePresenceAnnouncement(response);
    }
  }
1167091
def serialise_packet(self):
        
        if not hasattr(self, '_Meta'):
            raise ReferenceError("Can't serialise a packet that doesn't have an endpoint ID.")
        serialised = self.serialise()
        return struct.pack('!HH', len(serialised), self._Meta['endpoint']) + serialised
279096
def pack(self, value=None):
        """"""
        if isinstance(value, Match):
            return value.pack()
        elif value is None:
            self._update_match_length()
            packet = super().pack()
            return self._complete_last_byte(packet)
        raise PackException(f'Match can\'t unpack "{value}".')
1300848
def pack(self, value=None):
        """"""
        self._update_length()
        packet = super().pack()
        return self._complete_last_byte(packet)
936254
def from_bytes(cls, bitstream, decode_payload=True):
        '''
        
        '''
        packet = cls()

        # Convert to ConstBitStream (if not already provided)
        if not isinstance(bitstream, ConstBitStream):
            if isinstance(bitstream, Bits):
                bitstream = ConstBitStream(auto=bitstream)
            else:
                bitstream = ConstBitStream(bytes=bitstream)

        # Read the version
        version = bitstream.read('uint:4')
        if version != packet.version:
            raise ValueError('Provided bytes do not contain an IPv6 packet')

        # Read the traffic class
        packet.traffic_class = bitstream.read('uint:8')

        # Read the flow label
        packet.flow_label = bitstream.read('uint:20')

        # Read the payload length
        payload_length = bitstream.read('uint:16')

        # Read the next header type
        packet.next_header = bitstream.read('uint:8')

        # Read the hop limit
        packet.hop_limit = bitstream.read('uint:8')

        # Read the source and destination addresses
        packet.source = IPv6Address(bitstream.read('uint:128'))
        packet.destination = IPv6Address(bitstream.read('uint:128'))

        # And the rest is payload
        packet.payload = bitstream.read('bytes:%d' % payload_length)

        if decode_payload:
            payload_class = protocol_registry.get_type_class(packet.next_header)
            if payload_class:
                packet.payload = payload_class.from_bytes(packet.payload)

        # There should be no remaining bits
        if bitstream.pos != bitstream.len:
            raise ValueError('Bits remaining after processing packet')

        # Verify that the properties make sense
        packet.sanitize()

        return packet
875020
def terminate_bits(self, payload):
        
        data_capacity = tables.data_capacity[self.version][self.error][0]

        if len(payload) > data_capacity:
            raise ValueError('The supplied data will not fit '
                             'within this version of a QR code.')

        #We must add up to 4 zeros to make up for any shortfall in the
        #length of the data field.
        if len(payload) == data_capacity:
            return None
        elif len(payload) <= data_capacity-4:
            bits = self.binary_string(0,4)
        else:
            #Make up any shortfall need with less than 4 zeros
            bits = self.binary_string(0, data_capacity - len(payload))

        return bits
856101
public IoBuffer encodePacket(Packet packet) {
        IoBuffer out = null;
        Header header = packet.getHeader();
        int channelId = header.getChannelId();
        //log.trace("Channel id: {}", channelId);
        IRTMPEvent message = packet.getMessage();
        if (message instanceof ChunkSize) {
            ChunkSize chunkSizeMsg = (ChunkSize) message;
            ((RTMPConnection) Red5.getConnectionLocal()).getState().setWriteChunkSize(chunkSizeMsg.getSize());
        }
        // normally the message is expected not to be dropped
        if (!dropMessage(channelId, message)) {
            //log.trace("Header time: {} message timestamp: {}", header.getTimer(), message.getTimestamp());
            IoBuffer data = encodeMessage(header, message);
            if (data != null) {
                RTMP rtmp = ((RTMPConnection) Red5.getConnectionLocal()).getState();
                // set last write packet
                rtmp.setLastWritePacket(channelId, packet);
                // ensure we're at the beginning
                if (data.position() != 0) {
                    data.flip();
                } else {
                    data.rewind();
                }
                // length of the data to be chunked
                int dataLen = data.limit();
                header.setSize(dataLen);
                //if (log.isTraceEnabled()) {
                    //log.trace("Message: {}", data);
                //}
                // chunk size for writing
                int chunkSize = rtmp.getWriteChunkSize();
                // number of chunks to write
                int numChunks = (int) Math.ceil(dataLen / (float) chunkSize);
                // get last header
                Header lastHeader = rtmp.getLastWriteHeader(channelId);
                if (log.isTraceEnabled()) {
                    log.trace("Channel id: {} chunkSize: {}", channelId, chunkSize);
                }
                // attempt to properly guess the size of the buffer we'll need
                int bufSize = dataLen + 18 + (numChunks * 2);
                //log.trace("Allocated buffer size: {}", bufSize);
                out = IoBuffer.allocate(bufSize, false);
                out.setAutoExpand(true);
                do {
                    // encode the header
                    encodeHeader(header, lastHeader, out);
                    // write a chunk
                    byte[] buf = new byte[Math.min(chunkSize, data.remaining())];
                    data.get(buf);
                    //log.trace("Buffer: {}", Hex.encodeHexString(buf));
                    out.put(buf);
                    // move header over to last header
                    lastHeader = header.clone();
                } while (data.hasRemaining());
                // collapse the time stamps on the last header after decode is complete
                lastHeader.setTimerBase(lastHeader.getTimer());
                // clear the delta
                lastHeader.setTimerDelta(0);
                // set last write header
                rtmp.setLastWriteHeader(channelId, lastHeader);
                data.free();
                out.flip();
                data = null;
            }
        }
        message.release();
        return out;
    }
941737
def stream_to_packet(data):
    
    if len(data) < 6:
        return None

    # unpack the length
    pktlen = struct.unpack(">H", data[4:6])[0] + 6
    if (len(data) < pktlen):
        return None

    return (data[:pktlen], data[pktlen:])
1282086
def tcp_reassembly(packet, *, count=NotImplemented):
    """"""
    if getattr(packet, 'ip', None):
        ip = packet['ip']
    elif getattr(packet, 'ip6', None):
        ip = packet['ip6']
    else:
        return False, None
    tcp = getattr(ip, 'tcp', None)
    if tcp is not None:
        flags = bin(tcp.flags)[2:].zfill(8)
        data = dict(
            bufid=(
                ipaddress.ip_address(ip.src),                   # source IP address
                ipaddress.ip_address(ip.dst),                   # destination IP address
                tcp.sport,                                      # source port
                tcp.dport,                                      # destination port
            ),
            num=count,                                          # original packet range number
            ack=tcp.ack,                                        # acknowledgement
            dsn=tcp.seq,                                        # data sequence number
            rst=bool(int(flags[5])),                            # reset connection flag
            syn=bool(int(flags[6])),                            # synchronise flag
            fin=bool(int(flags[7])),                            # finish flag
            payload=bytearray(tcp.pack()[tcp.__hdr_len__:]),    # raw bytearray type payload
        )
        raw_len = len(tcp.data)                                 # payload length, header excludes
        data['first'] = tcp.seq                                 # this sequence number
        data['last'] = tcp.seq + raw_len                        # next (wanted) sequence number
        data['len'] = raw_len                                   # payload length, header excludes
        return True, data
    return False, None
1253186
def read_packet(self, size=MTU):
        
        hdr = self.f.read(16)
        if len(hdr) < 16:
            return None
        sec,usec,caplen,wirelen = struct.unpack(self.endian+"IIII", hdr)
        s = self.f.read(caplen)[:MTU]
        return s, 0, (sec,usec,wirelen)
17479
def clear_cache(self):
        """"""
        self.raw_packet_cache = None
        for _, fval in six.iteritems(self.fields):
            if isinstance(fval, Packet):
                fval.clear_cache()
        self.payload.clear_cache()
1329806
def extract_packet(self):
        
        packet_size = velbus.MINIMUM_MESSAGE_SIZE + \
            (self.buffer[3] & 0x0F)
        packet = self.buffer[0:packet_size]
        return packet
767459
def decode(self, encoded_packet):
        
        ep = encoded_packet
        try:
            self.packet_type = int(ep[0:1])
        except TypeError:
            self.packet_type = ep
            ep = ''
        self.namespace = None
        self.data = None
        ep = ep[1:]
        dash = ep.find('-')
        attachment_count = 0
        if dash > 0 and ep[0:dash].isdigit():
            attachment_count = int(ep[0:dash])
            ep = ep[dash + 1:]
        if ep and ep[0:1] == '/':
            sep = ep.find(',')
            if sep == -1:
                self.namespace = ep
                ep = ''
            else:
                self.namespace = ep[0:sep]
                ep = ep[sep + 1:]
            q = self.namespace.find('?')
            if q != -1:
                self.namespace = self.namespace[0:q]
        if ep and ep[0].isdigit():
            self.id = 0
            while ep and ep[0].isdigit():
                self.id = self.id * 10 + int(ep[0])
                ep = ep[1:]
        if ep:
            self.data = self.json.loads(ep)
        return attachment_count