// Read data from the connection, returning plaintext data if all
// cryptographic checks passed. Obeys the `net.Conn` interface.
// Returns the number of bytes read into the output buffer.
761085
func (c *Conn) Read(out []byte) (n int, err error) {

	c.readMutex.Lock()
	defer c.readMutex.Unlock()

	// The first error kills the whole stream
	if err = c.getErrorForRead(); err != nil {
		return 0, err
	}
	// First see if there's anything buffered, and read that
	// out now.
	if n, err = c.readBufferedMsgsIntoBytes(out); err != nil {
		return 0, c.setReadError(err)
	}
	if n > 0 {
		return n, nil
	}

	var poll time.Duration
	if !c.readDeadline.IsZero() {
		poll = c.readDeadline.Sub(time.Now())
		if poll.Nanoseconds() < 0 {
			return 0, c.setReadError(ErrTimedOut)
		}
	} else {
		poll = c.readTimeout
	}

	var msgs [][]byte
	msgs, err = c.pollLoop(poll)

	if err != nil {
		return 0, c.setReadError(err)
	}
	if _, err = c.decryptIncomingMessages(msgs); err != nil {
		return 0, c.setReadError(err)
	}
	if n, err = c.readBufferedMsgsIntoBytes(out); err != nil {
		return 0, c.setReadError(err)
	}

	if n == 0 {
		switch {
		case c.getClosed():
			c.lctx.Debug("conn#Read: EOF since connection was closed")
			err = io.EOF
		case poll > 0:
			err = ErrTimedOut
		default:
			err = ErrAgain
		}
	}

	return n, err
}
1274839
func read(conn *net.TCPConn, size int, data *bytes.Buffer) error {
	conn.SetReadDeadline(time.Now().Add(time.Second * 15))

	n, err := io.CopyN(data, conn, int64(size))
	if err != nil || n != int64(size) {
		return errors.New("read error")
	}
	return nil
}
1186852
func (r *Reader) Read(buffer []byte) (n int, err error) {
	if r.reader == nil {
		n = len(buffer)
	} else {
		n, err = r.reader.Read(buffer)
	}

	r.count += int64(n)
	if r.onRead != nil {
		r.onRead(r.count)
	}
	return
}
1081321
func (c *Conn) Read(b []byte) (int, error) {
	n, err := c.pipe.Read(b)
	if err != nil {
		if e, ok := err.(*net.OpError); ok {
			e.Addr = c.raddr
			e.Source = c.laddr
			return n, e
		}
		return n, &net.OpError{
			Op:     "read",
			Addr:   c.raddr,
			Source: c.laddr,
			Net:    c.raddr.Network(),
			Err:    err,
		}
	}
	return n, nil
}
512542
func (p *ProxiedConnection) Read(b []byte) (n int, err error) {
	return p.originalTCPConnection.Read(b)
}
361941
func (c *connection) read(timeout time.Duration) ([]byte, error) {
	if !c.available() {
		return nil, ErrCannotRead
	}

	var err error
	var count int
	var messageLength uint32
	var rt time.Duration = timeout // rt = 'read timeout'
	b := &backoff.Backoff{
		Min:    rt,
		Jitter: true,
	}
	try := uint16(0)

	for {
		c.setReadDeadline(rt)
		if count, err = io.ReadFull(c.conn, c.sizeBuf); err == nil && count == 4 {
			messageLength = binary.BigEndian.Uint32(c.sizeBuf)
			if messageLength > uint32(cap(c.dataBuf)) {
				logDebug("[Connection]", "allocating larger dataBuf of size %d", messageLength)
				c.dataBuf = make([]byte, messageLength)
			} else {
				c.dataBuf = c.dataBuf[0:messageLength]
			}
			// FUTURE: large object warning / error
			// TODO: FUTURE this deadline should subtract the duration taken by the first
			// ReadFull call. Currently it's could wait up to 2X the read timout value
			c.setReadDeadline(rt)
			count, err = io.ReadFull(c.conn, c.dataBuf)
		} else {
			if err == nil && count != 4 {
				err = newClientError(fmt.Sprintf("[Connection] expected to read 4 bytes, only read: %d", count), nil)
			}
		}

		if err == nil && count != int(messageLength) {
			err = newClientError(fmt.Sprintf("[Connection] message length: %d, only read: %d", messageLength, count), nil)
		}

		if err == nil {
			return c.dataBuf, nil
		}

		if try < c.tempNetErrorRetries && isTemporaryNetError(err) {
			rt = b.Duration()
			try++
			logDebug("[Connection]", "temporary error, re-try %v, new read timeout: %v", try, rt)
		} else {
			c.setState(connInactive)
			return nil, err
		}
	}
}
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
}
830242
func (c *Conn) Read(b []byte) (int, error) {
	n, err := c.fd.Read(b)
	if err != nil {
		return n, c.opError(opRead, err)
	}

	return n, nil
}
767826
func (t *TerminalHandler) read(out []byte, ws *websocket.Conn) (n int, err error) {
	if len(t.buffer) > 0 {
		n := copy(out, t.buffer)
		if n == len(t.buffer) {
			t.buffer = []byte{}
		} else {
			t.buffer = t.buffer[n:]
		}
		return n, nil
	}

	var bytes []byte
	err = websocket.Message.Receive(ws, &bytes)
	if err != nil {
		if err == io.EOF {
			return 0, io.EOF
		}
		return 0, trace.Wrap(err)
	}

	var envelope Envelope
	err = proto.Unmarshal(bytes, &envelope)
	if err != nil {
		return 0, trace.Wrap(err)
	}

	var data []byte
	data, err = t.decoder.Bytes([]byte(envelope.GetPayload()))
	if err != nil {
		return 0, trace.Wrap(err)
	}

	switch string(envelope.GetType()) {
	case defaults.WebsocketRaw:
		n := copy(out, data)
		// if payload size is greater than [out], store the remaining
		// part in the buffer to be processed on the next Read call
		if len(data) > n {
			t.buffer = data[n:]
		}
		return n, nil
	case defaults.WebsocketResize:
		var e events.EventFields
		err := json.Unmarshal(data, &e)
		if err != nil {
			return 0, trace.Wrap(err)
		}

		params, err := session.UnmarshalTerminalParams(e.GetString("size"))
		if err != nil {
			return 0, trace.Wrap(err)
		}

		// Send the window change request in a goroutine so reads are not blocked
		// by network connectivity issues.
		go t.windowChange(params)

		return 0, nil
	default:
		return 0, trace.BadParameter("unknown prefix type: %v", envelope.GetType())
	}
}
1199772
func (d *decompressor) ReadByte() (byte, error) {
	if d.buf.hasData() {
		return d.buf.ReadByte()
	}
	return d.cr.ReadByte()
}
568043
func (d *Decoder) Read() uint64 {
	v := d.buf[d.i]
	return v
}
917249
func (f *Conn) Read(b []byte) (n int, err error) {
	total := 0

	if f.bytesLeft <= 0 {
		frameSize, err := f.readSize()
		if err != nil {
			return total, err
		}
		f.bytesLeft = frameSize
	}
	n, err = io.ReadFull(f.Conn, b[:min(f.bytesLeft, len(b))])
	f.bytesLeft -= n
	return
}
1270881
func (c *Connector) Read(ctx context.Context, ei *dosa.EntityInfo, keys map[string]dosa.FieldValue, minimumFields []string) (map[string]dosa.FieldValue, error) {
	// Convert the fields from the client's map to a set of fields to read
	var rpcMinimumFields map[string]struct{}
	if minimumFields != nil {
		rpcMinimumFields = map[string]struct{}{}
		for _, field := range minimumFields {
			rpcMinimumFields[field] = struct{}{}
		}
	}

	// convert the key values from interface{} to RPC's Value
	rpcFields := make(dosarpc.FieldValueMap)
	for key, value := range keys {
		rv, err := RawValueFromInterface(value)
		if err != nil {
			return nil, errors.Wrapf(err, "Key field %q", key)
		}
		if rv == nil {
			continue
		}
		rpcValue := &dosarpc.Value{ElemValue: rv}
		rpcFields[key] = rpcValue
	}

	// perform the read request
	readRequest := &dosarpc.ReadRequest{
		Ref:          entityInfoToSchemaRef(ei),
		KeyValues:    rpcFields,
		FieldsToRead: rpcMinimumFields,
	}

	response, err := c.client.Read(ctx, readRequest, getHeaders(c.headers)...)
	if err != nil {
		if be, ok := err.(*dosarpc.BadRequestError); ok {
			if be.ErrorCode != nil && *be.ErrorCode == errCodeNotFound {
				return nil, errors.Wrap(&dosa.ErrNotFound{}, "Read failed: not found")
			}
		}

		if !dosarpc.Dosa_Read_Helper.IsException(err) {
			return nil, errors.Wrap(err, "failed to Read due to network issue")
		}

		return nil, errors.Wrap(err, "failed to Read")
	}

	// no error, so for each column, transform it into the map of (col->value) items

	return decodeResults(ei, response.EntityValues), nil
}
1188992
func (c *Conn) Read(p []byte) (int, error) {
	c.conn.SetReadDeadline(time.Now().Add(c.config.ReadTimeout))
	return c.r.Read(p)
}
312692
func (conn *WebsocketConnection) Read(b []byte) (n int, err error) {
	if conn.reader == nil {
		err = conn.waitForReader()
		if err != nil {
			return
		}
	}

	rn, rerr := conn.reader.Read(b)
	switch rerr {
	case io.EOF:
		conn.reader = nil
	default:
		n, err = rn, rerr
	}
	return
}
1276938
func (s *Server) readData(c *Connection) {
	c.write("354 Ok Send data ending with <CRLF>.<CRLF>")

	for {
		text := c.read()
		bytes := []byte(text)
		s.addMessageLine(text)
		// 46 13 10
		if bytes[0] == 46 && bytes[1] == 13 && bytes[2] == 10 {
			break
		}
	}
	c.write("250 server has transmitted the message")
}
819266
func (con *Connection) DecryptedRead(b []byte) (int, error) {
	if con.readBuffer == nil {
		buffered := bufio.NewReader(con.connection)
		decrypted, err := con.getDecrypter().Decrypt(buffered)
		if err != nil {
			if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
				// Ignore timeout error #77
			} else {
				log.Debug.Println("Decryption failed:", err)
				err = con.connection.Close()
			}
			return 0, err
		}

		con.readBuffer = decrypted
	}

	n, err := con.readBuffer.Read(b)

	if n < len(b) || err == io.EOF {
		con.readBuffer = nil
	}

	return n, err
}