// readMessageHeader reads a bitcoin message header from r.
190501
func readMessageHeader(r io.Reader) (int, *messageHeader, error) {
	// Since readElements doesn't return the amount of bytes read, attempt
	// to read the entire header into a buffer first in case there is a
	// short read so the proper amount of read bytes are known.  This works
	// since the header is a fixed size.
	var headerBytes [MessageHeaderSize]byte
	n, err := io.ReadFull(r, headerBytes[:])
	if err != nil {
		return n, nil, err
	}
	hr := bytes.NewReader(headerBytes[:])

	// Create and populate a messageHeader struct from the raw header bytes.
	hdr := messageHeader{}
	var command [CommandSize]byte
	readElements(hr, &hdr.magic, &command, &hdr.length, &hdr.checksum)

	// Strip trailing zeros from command string.
	hdr.command = string(bytes.TrimRight(command[:], string(0)))

	return n, &hdr, nil
}
789409
func (m *Memberlist) readUserMsg(bufConn io.Reader, dec *codec.Decoder) error {
	// Read the user message header
	var header userMsgHeader
	if err := dec.Decode(&header); err != nil {
		return err
	}

	// Read the user message into a buffer
	var userBuf []byte
	if header.UserMsgLen > 0 {
		userBuf = make([]byte, header.UserMsgLen)
		bytes, err := io.ReadAtLeast(bufConn, userBuf, header.UserMsgLen)
		if err == nil && bytes != header.UserMsgLen {
			err = fmt.Errorf(
				"Failed to read full user message (%d / %d)",
				bytes, header.UserMsgLen)
		}
		if err != nil {
			return err
		}

		d := m.config.Delegate
		if d != nil {
			d.NotifyMsg(userBuf)
		}
	}

	return nil
}
650607
func NewMessage(hdr *Header, msg []byte) *Message {
	var h Header
	if hdr != nil {
		h = *hdr
	}

	if h.Timestamp.IsZero() {
		h.Timestamp = time.Now().UTC()
	}

	if h.Version == 0 {
		h.Version = 1
	}

	if msg != nil {
		m := make([]byte, len(msg))
		copy(m, msg)
		msg = m
	}

	return &Message{Header: h, Msg: msg}
}
203319
func (c *Connection) readMessage() (m *buffer.InMessage, err error) {
	// Allocate a message.
	m = c.getInMessage()

	// Loop past transient errors.
	for {
		// Attempt a reaed.
		err = m.Init(c.dev)

		// Special cases:
		//
		//  *  ENODEV means fuse has hung up.
		//
		//  *  EINTR means we should try again. (This seems to happen often on
		//     OS X, cf. http://golang.org/issue/11180)
		//
		if pe, ok := err.(*os.PathError); ok {
			switch pe.Err {
			case syscall.ENODEV:
				err = io.EOF

			case syscall.EINTR:
				err = nil
				continue
			}
		}

		if err != nil {
			c.putInMessage(m)
			m = nil
			return
		}

		return
	}
}
1237932
func readChunkVST1_1(r io.Reader) (chunk, error) {
	hdr := [maxChunkHeaderSize]byte{}
	if err := readBytes(hdr[:maxChunkHeaderSize], r); err != nil {
		return chunk{}, driver.WithStack(err)
	}
	le := binary.LittleEndian
	length := le.Uint32(hdr[0:])
	chunkX := le.Uint32(hdr[4:])
	messageID := le.Uint64(hdr[8:])
	messageLength := le.Uint64(hdr[16:])
	contentLength := length - maxChunkHeaderSize

	data := make([]byte, contentLength)
	if err := readBytes(data, r); err != nil {
		return chunk{}, driver.WithStack(err)
	}
	//fmt.Printf("data: " + hex.EncodeToString(data) + "\n")
	return chunk{
		chunkX:        chunkX,
		MessageID:     messageID,
		MessageLength: messageLength,
		Data:          data,
	}, nil
}
112551
func (a *AuthServerCodec) ReadRequestHeader(r *rpc.Request) error {

	// There is no need for synchronization here, since go's RPC server
	//  ensures that requests are read one-at-a-time

	// Reset state
	a.lastError = nil
	a.buff.ReadBuff.Reset()

	ident, body, err := a.parser.ReadHeader(a.conn)
	if err != nil {
		log.WithError(err).WithField("ServiceMethod", r.ServiceMethod).Debug("Could not authenticate RPC request")
		if e, ok := err.(*auth.AuthHeaderError); ok {
			body = e.Payload
			a.lastError = e.Err
		} else {
			return err
		}
	}

	// Now write the actual request to the buffer
	if _, err = a.buff.ReadBuff.Write(body); err != nil {
		return err
	}

	// Let the underlying codec read the request from the buffer and parse it
	if err := a.wrappedcodec.ReadRequestHeader(r); err != nil {
		return err
	}

	log.WithField("ServiceMethod", r.ServiceMethod).Debug("Received RPC request")

	// Now we can get the method name from r and authenticate if required
	//  If this fails, save the error to return later
	//  If we return an error now, the server will simply close the connection
	//  This is safe because go's rpc server always calls ReadRequestHeader and ReadRequestBody back-to-back
	//   (unless ReadRequestHeader returns an error)
	if requiresAuthentication(r.ServiceMethod) {
		if a.lastError == nil {
			if requiresAdmin(r.ServiceMethod) && (ident == nil || !ident.HasAdminAccess()) {
				log.WithField("ServiceMethod", r.ServiceMethod).Debug("Received unauthorized RPC request")
				a.lastError = ErrNoAdmin
			}
		}
		//TODO: save the identity so we can inject it into the request body later
	}
	return nil
}
1027739
func (m *Message) AddHeader(header, value string) {
	if m.headers == nil {
		m.headers = make(map[string]string)
	}
	m.headers[header] = value
}
334689
func (e *ExchangeMessage) SetHeader(k, v string) {
	e.head.Add(k, v)
}
743694
func (r *Reader) ReadMessage() (*Message, error) {
	line, err := r.reader.ReadString('\n')
	if err != nil {
		return nil, err
	}

	if r.DebugCallback != nil {
		r.DebugCallback(line)
	}

	// Parse the message from our line
	return ParseMessage(line)
}
255988
func ReadServerMessage(r io.Reader, m []Message) ([]Message, error) {
	return ReadMessage(r, ws.StateClientSide, m)
}
1330541
func readSignedMessage(packets *packet.Reader, mdin *MessageDetails, keyring KeyRing) (md *MessageDetails, err error) {
	if mdin == nil {
		mdin = new(MessageDetails)
	}
	md = mdin

	var p packet.Packet
	var h hash.Hash
	var wrappedHash hash.Hash
FindLiteralData:
	for {
		p, err = packets.Next()
		if err != nil {
			return nil, err
		}
		switch p := p.(type) {
		case *packet.Compressed:
			if err := packets.Push(p.Body); err != nil {
				return nil, err
			}
		case *packet.OnePassSignature:
			if !p.IsLast {
				return nil, errors.UnsupportedError("nested signatures")
			}

			h, wrappedHash, err = hashForSignature(p.Hash, p.SigType)
			if err != nil {
				md = nil
				return
			}

			md.IsSigned = true
			md.SignedByKeyId = p.KeyId
			keys := keyring.KeysByIdUsage(p.KeyId, packet.KeyFlagSign)
			if len(keys) > 0 {
				md.SignedBy = &keys[0]
			}
		case *packet.LiteralData:
			md.LiteralData = p
			break FindLiteralData
		}
	}

	if md.SignedBy != nil {
		md.UnverifiedBody = &signatureCheckReader{packets, h, wrappedHash, md}
	} else if md.decrypted != nil {
		md.UnverifiedBody = checkReader{md}
	} else {
		md.UnverifiedBody = md.LiteralData.Body
	}

	return md, nil
}
124850
func ReadHeader(db ethdb.Reader, hash common.Hash, number uint64) *types.Header {
	data := ReadHeaderRLP(db, hash, number)
	if len(data) == 0 {
		return nil
	}
	header := new(types.Header)
	if err := rlp.Decode(bytes.NewReader(data), header); err != nil {
		log.Error("Invalid block header RLP", "hash", hash, "err", err)
		return nil
	}
	return header
}
779083
func (z *Reader) readHeader() (hdr Header, err error) {
	if _, err = io.ReadFull(z.r, z.buf[:10]); err != nil {
		// RFC 1952, section 2.2, says the following:
		//	A gzip file consists of a series of "members" (compressed data sets).
		//
		// Other than this, the specification does not clarify whether a
		// "series" is defined as "one or more" or "zero or more". To err on the
		// side of caution, Go interprets this to mean "zero or more".
		// Thus, it is okay to return io.EOF here.
		return hdr, err
	}
	if z.buf[0] != gzipID1 || z.buf[1] != gzipID2 || z.buf[2] != gzipDeflate {
		return hdr, ErrHeader
	}
	flg := z.buf[3]
	hdr.ModTime = time.Unix(int64(le.Uint32(z.buf[4:8])), 0)
	// z.buf[8] is XFL and is currently ignored.
	hdr.OS = z.buf[9]
	z.digest = crc32.ChecksumIEEE(z.buf[:10])

	if flg&flagExtra != 0 {
		if _, err = io.ReadFull(z.r, z.buf[:2]); err != nil {
			return hdr, noEOF(err)
		}
		z.digest = crc32.Update(z.digest, crc32.IEEETable, z.buf[:2])
		data := make([]byte, le.Uint16(z.buf[:2]))
		if _, err = io.ReadFull(z.r, data); err != nil {
			return hdr, noEOF(err)
		}
		z.digest = crc32.Update(z.digest, crc32.IEEETable, data)
		hdr.Extra = data
	}

	var s string
	if flg&flagName != 0 {
		if s, err = z.readString(); err != nil {
			return hdr, err
		}
		hdr.Name = s
	}

	if flg&flagComment != 0 {
		if s, err = z.readString(); err != nil {
			return hdr, err
		}
		hdr.Comment = s
	}

	if flg&flagHdrCrc != 0 {
		if _, err = io.ReadFull(z.r, z.buf[:2]); err != nil {
			return hdr, noEOF(err)
		}
		digest := le.Uint16(z.buf[:2])
		if digest != uint16(z.digest) {
			return hdr, ErrHeader
		}
	}

	z.digest = 0
	if z.decompressor == nil {
		z.decompressor = flate.NewReader(z.r)
	} else {
		z.decompressor.(flate.Resetter).Reset(z.r, nil)
	}
	return hdr, nil
}
719508
func (self *FSock) readEvent() (header string, body string, err error) {
	var cl int

	if header, err = self.readHeaders(); err != nil {
		return "", "", err
	}
	if !strings.Contains(header, "Content-Length") { //No body
		return header, "", nil
	}
	if cl, err = strconv.Atoi(headerVal(header, "Content-Length")); err != nil {
		return "", "", errors.New("Cannot extract content length")
	}
	if body, err = self.readBody(cl); err != nil {
		return "", "", err
	}
	return
}
566572
func readGroupHeaderTOC(fpr io.Reader) ([]byte, uint32, error) {
	return _readGroupHeader(fpr, true)
}
463077
func (c *Chunk) ParseChunkHeader(reader io.ReadSeeker) {
	err := encoding.Unmarshal(reader, &c.Header, Endianness)
	if err != nil {
		panic(err)
	}
}
1006001
func (s *Server) readMessage(peer Peer) (wtwire.Message, error) {
	// Set a read timeout to ensure we drop the client if not sent in a
	// timely manner.
	err := peer.SetReadDeadline(time.Now().Add(s.cfg.ReadTimeout))
	if err != nil {
		err = fmt.Errorf("unable to set read deadline: %v", err)
		return nil, err
	}

	// Pull the next message off the wire, and parse it according to the
	// watchtower wire specification.
	rawMsg, err := peer.ReadNextMessage()
	if err != nil {
		err = fmt.Errorf("unable to read message: %v", err)
		return nil, err
	}

	msgReader := bytes.NewReader(rawMsg)
	msg, err := wtwire.ReadMessage(msgReader, 0)
	if err != nil {
		err = fmt.Errorf("unable to parse message: %v", err)
		return nil, err
	}

	logMessage(peer, msg, true)

	return msg, nil
}