// readPacket reads and decrypt a single packet from the reader argument.
165330
func (s *streamPacketCipher) readPacket(seqNum uint32, r io.Reader) ([]byte, error) {
	if _, err := io.ReadFull(r, s.prefix[:]); err != nil {
		return nil, err
	}

	s.cipher.XORKeyStream(s.prefix[:], s.prefix[:])
	length := binary.BigEndian.Uint32(s.prefix[0:4])
	paddingLength := uint32(s.prefix[4])

	var macSize uint32
	if s.mac != nil {
		s.mac.Reset()
		binary.BigEndian.PutUint32(s.seqNumBytes[:], seqNum)
		s.mac.Write(s.seqNumBytes[:])
		s.mac.Write(s.prefix[:])
		macSize = uint32(s.mac.Size())
	}

	if length <= paddingLength+1 {
		return nil, errors.New("ssh: invalid packet length, packet too small")
	}

	if length > maxPacket {
		return nil, errors.New("ssh: invalid packet length, packet too large")
	}

	// the maxPacket check above ensures that length-1+macSize
	// does not overflow.
	if uint32(cap(s.packetData)) < length-1+macSize {
		s.packetData = make([]byte, length-1+macSize)
	} else {
		s.packetData = s.packetData[:length-1+macSize]
	}

	if _, err := io.ReadFull(r, s.packetData); err != nil {
		return nil, err
	}
	mac := s.packetData[length-1:]
	data := s.packetData[:length-1]
	s.cipher.XORKeyStream(data, data)

	if s.mac != nil {
		s.mac.Write(data)
		s.macResult = s.mac.Sum(s.macResult[:0])
		if subtle.ConstantTimeCompare(s.macResult, mac) != 1 {
			return nil, errors.New("ssh: MAC failure")
		}
	}

	return s.packetData[:length-paddingLength-1], nil
}
968527
func Read(r io.Reader) (p Packet, err error) {
	tag, _, contents, err := readHeader(r)
	if err != nil {
		return
	}

	switch tag {
	case packetTypeEncryptedKey:
		p = new(EncryptedKey)
	case packetTypeSignature:
		var version byte
		// Detect signature version
		if contents, version, err = peekVersion(contents); err != nil {
			return
		}
		if version < 4 {
			p = new(SignatureV3)
		} else {
			p = new(Signature)
		}
	case packetTypeSymmetricKeyEncrypted:
		p = new(SymmetricKeyEncrypted)
	case packetTypeOnePassSignature:
		p = new(OnePassSignature)
	case packetTypePrivateKey, packetTypePrivateSubkey:
		pk := new(PrivateKey)
		if tag == packetTypePrivateSubkey {
			pk.IsSubkey = true
		}
		p = pk
	case packetTypePublicKey, packetTypePublicSubkey:
		var version byte
		if contents, version, err = peekVersion(contents); err != nil {
			return
		}
		isSubkey := tag == packetTypePublicSubkey
		if version < 4 {
			p = &PublicKeyV3{IsSubkey: isSubkey}
		} else {
			p = &PublicKey{IsSubkey: isSubkey}
		}
	case packetTypeCompressed:
		p = new(Compressed)
	case packetTypeSymmetricallyEncrypted:
		p = new(SymmetricallyEncrypted)
	case packetTypeLiteralData:
		p = new(LiteralData)
	case packetTypeUserId:
		p = new(UserId)
	case packetTypeUserAttribute:
		p = new(UserAttribute)
	case packetTypeSymmetricallyEncryptedMDC:
		se := new(SymmetricallyEncrypted)
		se.MDC = true
		p = se
	default:
		err = errors.UnknownPacketTypeError(tag)
	}
	if p != nil {
		err = p.parse(contents)
	}
	if err != nil {
		consumeAll(contents)
	}
	return
}
176022
func (s *Slice) ReadByte() (c byte, err error) {
	if len(*s) < 1 {
		return 0, io.EOF
	}

	c = (*s)[0]
	if len(*s) > 1 {
		*s = (*s)[1:]
	} else {
		*s = nil
	}
	return c, nil
}
321502
func (c *Conn) receivePacket(h header, payload []byte) {
	c.packetReadTimeoutTimer.Reset(packetReadTimeout)
	c.processDelivery(h, payload)
}
49974
func (p *Packet) ReadTCPData() []byte {
	return p.ipHdr.Buffer[uint16(p.ipHdr.ipHeaderLen)+p.TCPDataStartBytes():]
}
1306815
func AuthServerReadPacketString(c *Conn) (string, error) {
	// Read a packet, the password is the payload, as a
	// zero terminated string.
	data, err := c.ReadPacket()
	if err != nil {
		return "", err
	}
	if len(data) == 0 || data[len(data)-1] != 0 {
		return "", vterrors.Errorf(vtrpc.Code_INTERNAL, "received invalid response packet, datalen=%v", len(data))
	}
	return string(data[:len(data)-1]), nil
}
285993
func (p *pktline) readPacketText() (string, error) {
	data, err := p.readPacket()
	return strings.TrimSuffix(string(data), "\n"), err
}
956688
func Decrypt(password string, encrypted []byte) (plaintext []byte, err error) {
	// Pull apart packet.
	pkt := encrypted
	if len(pkt) < 1+8+4+2*aes.BlockSize+sha1.Size {
		return nil, fmt.Errorf("encrypted packet too short")
	}
	vers, pkt := pkt[:1], pkt[1:]
	salt, pkt := pkt[:8], pkt[8:]
	hash, pkt := pkt[:4], pkt[4:]
	iv, pkt := pkt[:aes.BlockSize], pkt[aes.BlockSize:]
	enc, sig := pkt[:len(pkt)-sha1.Size], pkt[len(pkt)-sha1.Size:]

	if vers[0] != version || len(enc)%aes.BlockSize != 0 {
		return nil, fmt.Errorf("malformed encrypted packet")
	}

	// Derive key and check against hash.
	aesKey, hmacKey, keyHash := deriveKey(password, salt)
	if !bytes.Equal(hash, keyHash) {
		return nil, fmt.Errorf("incorrect password - %x vs %x", hash, keyHash)
	}

	// Verify signature.
	h := hmac.New(sha1.New, hmacKey)
	h.Write(encrypted[:len(encrypted)-len(sig)])
	if !bytes.Equal(sig, h.Sum(nil)) {
		return nil, fmt.Errorf("cannot authenticate encrypted packet")
	}

	// Decrypt.
	aesBlock, err := aes.NewCipher(aesKey)
	if err != nil {
		// Cannot happen - key is right size.
		panic("aes: " + err.Error())
	}
	m := cipher.NewCBCDecrypter(aesBlock, iv)
	dec := make([]byte, len(enc))
	m.CryptBlocks(dec, enc)

	// Unpad.
	pad := dec[len(dec)-1]
	if pad <= 0 || pad > aes.BlockSize {
		return nil, fmt.Errorf("malformed packet padding")
	}
	for _, b := range dec[len(dec)-int(pad):] {
		if b != pad {
			return nil, fmt.Errorf("malformed packet padding")
		}
	}
	dec = dec[:len(dec)-int(pad)]

	// Success!
	return dec, nil
}
763285
func Unpack(r io.Reader) ([]byte, error) {
	var bl [2]byte

	_, err := io.ReadFull(r, bl[:])
	if err != nil {
		return nil, err
	}

	n := binary.LittleEndian.Uint16(bl[:])
	buf := make([]byte, int(n))
	_, err = io.ReadFull(r, buf)
	return buf, err
}
78684
func (c *Client) processPacket(pkt packet.Generic) error {
	// prepare error
	var err error

	// handle individual packets
	switch typedPkt := pkt.(type) {
	case *packet.Subscribe:
		err = c.processSubscribe(typedPkt)
	case *packet.Unsubscribe:
		err = c.processUnsubscribe(typedPkt)
	case *packet.Publish:
		err = c.processPublish(typedPkt)
	case *packet.Puback:
		err = c.processPubackAndPubcomp(typedPkt.ID)
	case *packet.Pubcomp:
		err = c.processPubackAndPubcomp(typedPkt.ID)
	case *packet.Pubrec:
		err = c.processPubrec(typedPkt.ID)
	case *packet.Pubrel:
		err = c.processPubrel(typedPkt.ID)
	case *packet.Pingreq:
		err = c.processPingreq()
	case *packet.Disconnect:
		err = c.processDisconnect()
	default:
		err = c.die(ClientError, ErrUnexpectedPacket)
	}

	// return eventual error
	if err != nil {
		return err // error has already been handled
	}

	return nil
}
767040
func (pr *PacketResponse) ReadPacket() (*ber.Packet, error) {
	if (pr == nil) || (pr.Packet == nil && pr.Error == nil) {
		return nil, NewError(ErrorNetwork, errors.New("ldap: could not retrieve response"))
	}
	return pr.Packet, pr.Error
}
608669
func (s *Server) ReadSSFPacketSocket(serverConn net.PacketConn, packetPool *sync.Pool) {
	// TODO This is duplicated from ReadMetricSocket and feels like it could be it's
	// own function?
	p := packetPool.Get().([]byte)
	if len(p) == 0 {
		log.WithField("len", len(p)).Fatal(
			"packetPool making empty slices: trace_max_length_bytes must be >= 0")
	}
	packetPool.Put(p)

	for {
		buf := packetPool.Get().([]byte)
		n, _, err := serverConn.ReadFrom(buf)
		if err != nil {
			// In tests, the probably-best way to
			// terminate this reader is to issue a shutdown and close the listening
			// socket, which returns an error, so let's handle it here:
			select {
			case <-s.shutdown:
				log.WithError(err).Info("Ignoring ReadFrom error while shutting down")
				return
			default:
				log.WithError(err).Error("Error reading from UDP trace socket")
				continue
			}
		}

		s.HandleTracePacket(buf[:n])
		packetPool.Put(buf)
	}
}
74694
func (r *importReader) readByte() byte {
	c, err := r.b.ReadByte()
	if err == nil {
		r.buf = append(r.buf, c)
		if c == 0 {
			err = errNUL
		}
	}
	if err != nil {
		if err == io.EOF {
			r.eof = true
		} else if r.err == nil {
			r.err = err
		}
		c = 0
	}
	return c
}
1191426
func (m *Multi) UnpackFromReader(r io.Reader, keyRing keychain.KeyRing) error {
	// We'll attempt to read the entire packed backup, and also decrypt it
	// using the passed key ring which is expected to be able to derive the
	// encryption keys.
	plaintextBackup, err := decryptPayloadFromReader(r, keyRing)
	if err != nil {
		return err
	}
	backupReader := bytes.NewReader(plaintextBackup)

	// Now that we've decrypted the payload successfully, we can parse out
	// each of the individual static channel backups.

	// First, we'll need to read the version of this multi-back up so we
	// can know how to unpack each of the individual SCB's.
	var multiVersion byte
	err = lnwire.ReadElements(backupReader, &multiVersion)
	if err != nil {
		return err
	}

	m.Version = MultiBackupVersion(multiVersion)
	switch m.Version {

	// The default version is simply a set of serialized SCB's with the
	// number of total SCB's prepended to the front of the byte slice.
	case DefaultMultiVersion:
		// First, we'll need to read out the total number of backups
		// that've been serialized into this multi-chan backup. Each
		// backup is the same size, so we can continue until we've
		// parsed out everything.
		var numBackups uint32
		err = lnwire.ReadElements(backupReader, &numBackups)
		if err != nil {
			return err
		}

		// We'll continue to parse out each backup until we've read all
		// that was indicated from the length prefix.
		for ; numBackups != 0; numBackups-- {
			// Attempt to parse out the net static channel backup,
			// if it's been malformed, then we'll return with an
			// error
			var chanBackup Single
			err := chanBackup.Deserialize(backupReader)
			if err != nil {
				return err
			}

			// Collect the next valid chan backup into the main
			// multi backup slice.
			m.StaticBackups = append(m.StaticBackups, chanBackup)
		}

	default:
		return fmt.Errorf("unable to unpack unknown multi-version "+
			"of %v", multiVersion)
	}

	return nil
}
627567
func (ua *UnsubackPacket) Unpack(b io.Reader) {
	ua.MessageID = decodeUint16(b)
}
739337
func (c *CipherReader) Read(p []byte) (n int, err error) {
	n, err = c.r.Read(p)
	ws.Cipher(p[:n], c.mask, c.pos)
	c.pos += n
	return
}
1073205
func (p *pktline) readPacketList() ([]string, error) {
	var list []string
	for {
		data, err := p.readPacketText()
		if err != nil {
			return nil, err
		}

		if len(data) == 0 {
			break
		}

		list = append(list, data)
	}

	return list, nil
}