// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package websocket

import (
	
	
	
	
	
	
	
	
	
	
	
	
)

const (
	// Frame header byte 0 bits from Section 5.2 of RFC 6455
	finalBit = 1 << 7
	rsv1Bit  = 1 << 6
	rsv2Bit  = 1 << 5
	rsv3Bit  = 1 << 4

	// Frame header byte 1 bits from Section 5.2 of RFC 6455
	maskBit = 1 << 7

	maxFrameHeaderSize         = 2 + 8 + 4 // Fixed header + length + mask
	maxControlFramePayloadSize = 125

	writeWait = time.Second

	defaultReadBufferSize  = 4096
	defaultWriteBufferSize = 4096

	continuationFrame = 0
	noFrame           = -1
)

// Close codes defined in RFC 6455, section 11.7.
const (
	CloseNormalClosure           = 1000
	CloseGoingAway               = 1001
	CloseProtocolError           = 1002
	CloseUnsupportedData         = 1003
	CloseNoStatusReceived        = 1005
	CloseAbnormalClosure         = 1006
	CloseInvalidFramePayloadData = 1007
	ClosePolicyViolation         = 1008
	CloseMessageTooBig           = 1009
	CloseMandatoryExtension      = 1010
	CloseInternalServerErr       = 1011
	CloseServiceRestart          = 1012
	CloseTryAgainLater           = 1013
	CloseTLSHandshake            = 1015
)

// The message types are defined in RFC 6455, section 11.8.
const (
	// TextMessage denotes a text data message. The text message payload is
	// interpreted as UTF-8 encoded text data.
	TextMessage = 1

	// BinaryMessage denotes a binary data message.
	BinaryMessage = 2

	// CloseMessage denotes a close control message. The optional message
	// payload contains a numeric code and text. Use the FormatCloseMessage
	// function to format a close message payload.
	CloseMessage = 8

	// PingMessage denotes a ping control message. The optional message payload
	// is UTF-8 encoded text.
	PingMessage = 9

	// PongMessage denotes a pong control message. The optional message payload
	// is UTF-8 encoded text.
	PongMessage = 10
)

// ErrCloseSent is returned when the application writes a message to the
// connection after sending a close message.
var ErrCloseSent = errors.New("websocket: close sent")

// ErrReadLimit is returned when reading a message that is larger than the
// read limit set for the connection.
var ErrReadLimit = errors.New("websocket: read limit exceeded")

// netError satisfies the net Error interface.
type netError struct {
	msg       string
	temporary bool
	timeout   bool
}

func ( *netError) () string   { return .msg }
func ( *netError) () bool { return .temporary }
func ( *netError) () bool   { return .timeout }

// CloseError represents a close message.
type CloseError struct {
	// Code is defined in RFC 6455, section 11.7.
	Code int

	// Text is the optional text payload.
	Text string
}

func ( *CloseError) () string {
	 := []byte("websocket: close ")
	 = strconv.AppendInt(, int64(.Code), 10)
	switch .Code {
	case CloseNormalClosure:
		 = append(, " (normal)"...)
	case CloseGoingAway:
		 = append(, " (going away)"...)
	case CloseProtocolError:
		 = append(, " (protocol error)"...)
	case CloseUnsupportedData:
		 = append(, " (unsupported data)"...)
	case CloseNoStatusReceived:
		 = append(, " (no status)"...)
	case CloseAbnormalClosure:
		 = append(, " (abnormal closure)"...)
	case CloseInvalidFramePayloadData:
		 = append(, " (invalid payload data)"...)
	case ClosePolicyViolation:
		 = append(, " (policy violation)"...)
	case CloseMessageTooBig:
		 = append(, " (message too big)"...)
	case CloseMandatoryExtension:
		 = append(, " (mandatory extension missing)"...)
	case CloseInternalServerErr:
		 = append(, " (internal server error)"...)
	case CloseTLSHandshake:
		 = append(, " (TLS handshake error)"...)
	}
	if .Text != "" {
		 = append(, ": "...)
		 = append(, .Text...)
	}
	return string()
}

// IsCloseError returns boolean indicating whether the error is a *CloseError
// with one of the specified codes.
func ( error,  ...int) bool {
	if ,  := .(*CloseError);  {
		for ,  := range  {
			if .Code ==  {
				return true
			}
		}
	}
	return false
}

// IsUnexpectedCloseError returns boolean indicating whether the error is a
// *CloseError with a code not in the list of expected codes.
func ( error,  ...int) bool {
	if ,  := .(*CloseError);  {
		for ,  := range  {
			if .Code ==  {
				return false
			}
		}
		return true
	}
	return false
}

var (
	errWriteTimeout        = &netError{msg: "websocket: write timeout", timeout: true, temporary: true}
	errUnexpectedEOF       = &CloseError{Code: CloseAbnormalClosure, Text: io.ErrUnexpectedEOF.Error()}
	errBadWriteOpCode      = errors.New("websocket: bad write message type")
	errWriteClosed         = errors.New("websocket: write closed")
	errInvalidControlFrame = errors.New("websocket: invalid control frame")
)

func newMaskKey() [4]byte {
	 := rand.Uint32()
	return [4]byte{byte(), byte( >> 8), byte( >> 16), byte( >> 24)}
}

func hideTempErr( error) error {
	if ,  := .(net.Error);  && .Temporary() {
		 = &netError{msg: .Error(), timeout: .Timeout()}
	}
	return 
}

func isControl( int) bool {
	return  == CloseMessage ||  == PingMessage ||  == PongMessage
}

func isData( int) bool {
	return  == TextMessage ||  == BinaryMessage
}

var validReceivedCloseCodes = map[int]bool{
	// see http://www.iana.org/assignments/websocket/websocket.xhtml#close-code-number

	CloseNormalClosure:           true,
	CloseGoingAway:               true,
	CloseProtocolError:           true,
	CloseUnsupportedData:         true,
	CloseNoStatusReceived:        false,
	CloseAbnormalClosure:         false,
	CloseInvalidFramePayloadData: true,
	ClosePolicyViolation:         true,
	CloseMessageTooBig:           true,
	CloseMandatoryExtension:      true,
	CloseInternalServerErr:       true,
	CloseServiceRestart:          true,
	CloseTryAgainLater:           true,
	CloseTLSHandshake:            false,
}

func isValidReceivedCloseCode( int) bool {
	return validReceivedCloseCodes[] || ( >= 3000 &&  <= 4999)
}

// BufferPool represents a pool of buffers. The *sync.Pool type satisfies this
// interface.  The type of the value stored in a pool is not specified.
type BufferPool interface {
	// Get gets a value from the pool or returns nil if the pool is empty.
	Get() interface{}
	// Put adds a value to the pool.
	Put(interface{})
}

// writePoolData is the type added to the write buffer pool. This wrapper is
// used to prevent applications from peeking at and depending on the values
// added to the pool.
type writePoolData struct{ buf []byte }

// The Conn type represents a WebSocket connection.
type Conn struct {
	conn        net.Conn
	isServer    bool
	subprotocol string

	// Write fields
	mu            chan struct{} // used as mutex to protect write to conn
	writeBuf      []byte        // frame is constructed in this buffer.
	writePool     BufferPool
	writeBufSize  int
	writeDeadline time.Time
	writer        io.WriteCloser // the current writer returned to the application
	isWriting     bool           // for best-effort concurrent write detection

	writeErrMu sync.Mutex
	writeErr   error

	enableWriteCompression bool
	compressionLevel       int
	newCompressionWriter   func(io.WriteCloser, int) io.WriteCloser

	// Read fields
	reader  io.ReadCloser // the current reader returned to the application
	readErr error
	br      *bufio.Reader
	// bytes remaining in current frame.
	// set setReadRemaining to safely update this value and prevent overflow
	readRemaining int64
	readFinal     bool  // true the current message has more frames.
	readLength    int64 // Message size.
	readLimit     int64 // Maximum message size.
	readMaskPos   int
	readMaskKey   [4]byte
	handlePong    func(string) error
	handlePing    func(string) error
	handleClose   func(int, string) error
	readErrCount  int
	messageReader *messageReader // the current low-level reader

	readDecompress         bool // whether last read frame had RSV1 set
	newDecompressionReader func(io.Reader) io.ReadCloser
}

func newConn( net.Conn,  bool, ,  int,  BufferPool,  *bufio.Reader,  []byte) *Conn {

	if  == nil {
		if  == 0 {
			 = defaultReadBufferSize
		} else if  < maxControlFramePayloadSize {
			// must be large enough for control frame
			 = maxControlFramePayloadSize
		}
		 = bufio.NewReaderSize(, )
	}

	if  <= 0 {
		 = defaultWriteBufferSize
	}
	 += maxFrameHeaderSize

	if  == nil &&  == nil {
		 = make([]byte, )
	}

	 := make(chan struct{}, 1)
	 <- struct{}{}
	 := &Conn{
		isServer:               ,
		br:                     ,
		conn:                   ,
		mu:                     ,
		readFinal:              true,
		writeBuf:               ,
		writePool:              ,
		writeBufSize:           ,
		enableWriteCompression: true,
		compressionLevel:       defaultCompressionLevel,
	}
	.SetCloseHandler(nil)
	.SetPingHandler(nil)
	.SetPongHandler(nil)
	return 
}

// setReadRemaining tracks the number of bytes remaining on the connection. If n
// overflows, an ErrReadLimit is returned.
func ( *Conn) ( int64) error {
	if  < 0 {
		return ErrReadLimit
	}

	.readRemaining = 
	return nil
}

// Subprotocol returns the negotiated protocol for the connection.
func ( *Conn) () string {
	return .subprotocol
}

// Close closes the underlying network connection without sending or waiting
// for a close message.
func ( *Conn) () error {
	return .conn.Close()
}

// LocalAddr returns the local network address.
func ( *Conn) () net.Addr {
	return .conn.LocalAddr()
}

// RemoteAddr returns the remote network address.
func ( *Conn) () net.Addr {
	return .conn.RemoteAddr()
}

// Write methods

func ( *Conn) ( error) error {
	 = hideTempErr()
	.writeErrMu.Lock()
	if .writeErr == nil {
		.writeErr = 
	}
	.writeErrMu.Unlock()
	return 
}

func ( *Conn) ( int) ([]byte, error) {
	,  := .br.Peek()
	if  == io.EOF {
		 = errUnexpectedEOF
	}
	.br.Discard(len())
	return , 
}

func ( *Conn) ( int,  time.Time, ,  []byte) error {
	<-.mu
	defer func() { .mu <- struct{}{} }()

	.writeErrMu.Lock()
	 := .writeErr
	.writeErrMu.Unlock()
	if  != nil {
		return 
	}

	.conn.SetWriteDeadline()
	if len() == 0 {
		_,  = .conn.Write()
	} else {
		 = .writeBufs(, )
	}
	if  != nil {
		return .writeFatal()
	}
	if  == CloseMessage {
		.writeFatal(ErrCloseSent)
	}
	return nil
}

func ( *Conn) ( ...[]byte) error {
	 := net.Buffers()
	,  := .WriteTo(.conn)
	return 
}

// WriteControl writes a control message with the given deadline. The allowed
// message types are CloseMessage, PingMessage and PongMessage.
func ( *Conn) ( int,  []byte,  time.Time) error {
	if !isControl() {
		return errBadWriteOpCode
	}
	if len() > maxControlFramePayloadSize {
		return errInvalidControlFrame
	}

	 := byte() | finalBit
	 := byte(len())
	if !.isServer {
		 |= maskBit
	}

	 := make([]byte, 0, maxFrameHeaderSize+maxControlFramePayloadSize)
	 = append(, , )

	if .isServer {
		 = append(, ...)
	} else {
		 := newMaskKey()
		 = append(, [:]...)
		 = append(, ...)
		maskBytes(, 0, [6:])
	}

	 := 1000 * time.Hour
	if !.IsZero() {
		 = .Sub(time.Now())
		if  < 0 {
			return errWriteTimeout
		}
	}

	 := time.NewTimer()
	select {
	case <-.mu:
		.Stop()
	case <-.C:
		return errWriteTimeout
	}
	defer func() { .mu <- struct{}{} }()

	.writeErrMu.Lock()
	 := .writeErr
	.writeErrMu.Unlock()
	if  != nil {
		return 
	}

	.conn.SetWriteDeadline()
	_,  = .conn.Write()
	if  != nil {
		return .writeFatal()
	}
	if  == CloseMessage {
		.writeFatal(ErrCloseSent)
	}
	return 
}

// beginMessage prepares a connection and message writer for a new message.
func ( *Conn) ( *messageWriter,  int) error {
	// Close previous writer if not already closed by the application. It's
	// probably better to return an error in this situation, but we cannot
	// change this without breaking existing applications.
	if .writer != nil {
		.writer.Close()
		.writer = nil
	}

	if !isControl() && !isData() {
		return errBadWriteOpCode
	}

	.writeErrMu.Lock()
	 := .writeErr
	.writeErrMu.Unlock()
	if  != nil {
		return 
	}

	.c = 
	.frameType = 
	.pos = maxFrameHeaderSize

	if .writeBuf == nil {
		,  := .writePool.Get().(writePoolData)
		if  {
			.writeBuf = .buf
		} else {
			.writeBuf = make([]byte, .writeBufSize)
		}
	}
	return nil
}

// NextWriter returns a writer for the next message to send. The writer's Close
// method flushes the complete message to the network.
//
// There can be at most one open writer on a connection. NextWriter closes the
// previous writer if the application has not already done so.
//
// All message types (TextMessage, BinaryMessage, CloseMessage, PingMessage and
// PongMessage) are supported.
func ( *Conn) ( int) (io.WriteCloser, error) {
	var  messageWriter
	if  := .beginMessage(&, );  != nil {
		return nil, 
	}
	.writer = &
	if .newCompressionWriter != nil && .enableWriteCompression && isData() {
		 := .newCompressionWriter(.writer, .compressionLevel)
		.compress = true
		.writer = 
	}
	return .writer, nil
}

type messageWriter struct {
	c         *Conn
	compress  bool // whether next call to flushFrame should set RSV1
	pos       int  // end of data in writeBuf.
	frameType int  // type of the current frame.
	err       error
}

func ( *messageWriter) ( error) error {
	if .err != nil {
		return 
	}
	 := .c
	.err = 
	.writer = nil
	if .writePool != nil {
		.writePool.Put(writePoolData{buf: .writeBuf})
		.writeBuf = nil
	}
	return 
}

// flushFrame writes buffered data and extra as a frame to the network. The
// final argument indicates that this is the last frame in the message.
func ( *messageWriter) ( bool,  []byte) error {
	 := .c
	 := .pos - maxFrameHeaderSize + len()

	// Check for invalid control frames.
	if isControl(.frameType) &&
		(! ||  > maxControlFramePayloadSize) {
		return .endMessage(errInvalidControlFrame)
	}

	 := byte(.frameType)
	if  {
		 |= finalBit
	}
	if .compress {
		 |= rsv1Bit
	}
	.compress = false

	 := byte(0)
	if !.isServer {
		 |= maskBit
	}

	// Assume that the frame starts at beginning of c.writeBuf.
	 := 0
	if .isServer {
		// Adjust up if mask not included in the header.
		 = 4
	}

	switch {
	case  >= 65536:
		.writeBuf[] = 
		.writeBuf[+1] =  | 127
		binary.BigEndian.PutUint64(.writeBuf[+2:], uint64())
	case  > 125:
		 += 6
		.writeBuf[] = 
		.writeBuf[+1] =  | 126
		binary.BigEndian.PutUint16(.writeBuf[+2:], uint16())
	default:
		 += 8
		.writeBuf[] = 
		.writeBuf[+1] =  | byte()
	}

	if !.isServer {
		 := newMaskKey()
		copy(.writeBuf[maxFrameHeaderSize-4:], [:])
		maskBytes(, 0, .writeBuf[maxFrameHeaderSize:.pos])
		if len() > 0 {
			return .endMessage(.writeFatal(errors.New("websocket: internal error, extra used in client mode")))
		}
	}

	// Write the buffers to the connection with best-effort detection of
	// concurrent writes. See the concurrency section in the package
	// documentation for more info.

	if .isWriting {
		panic("concurrent write to websocket connection")
	}
	.isWriting = true

	 := .write(.frameType, .writeDeadline, .writeBuf[:.pos], )

	if !.isWriting {
		panic("concurrent write to websocket connection")
	}
	.isWriting = false

	if  != nil {
		return .endMessage()
	}

	if  {
		.endMessage(errWriteClosed)
		return nil
	}

	// Setup for next frame.
	.pos = maxFrameHeaderSize
	.frameType = continuationFrame
	return nil
}

func ( *messageWriter) ( int) (int, error) {
	 := len(.c.writeBuf) - .pos
	if  <= 0 {
		if  := .flushFrame(false, nil);  != nil {
			return 0, 
		}
		 = len(.c.writeBuf) - .pos
	}
	if  >  {
		 = 
	}
	return , nil
}

func ( *messageWriter) ( []byte) (int, error) {
	if .err != nil {
		return 0, .err
	}

	if len() > 2*len(.c.writeBuf) && .c.isServer {
		// Don't buffer large messages.
		 := .flushFrame(false, )
		if  != nil {
			return 0, 
		}
		return len(), nil
	}

	 := len()
	for len() > 0 {
		,  := .ncopy(len())
		if  != nil {
			return 0, 
		}
		copy(.c.writeBuf[.pos:], [:])
		.pos += 
		 = [:]
	}
	return , nil
}

func ( *messageWriter) ( string) (int, error) {
	if .err != nil {
		return 0, .err
	}

	 := len()
	for len() > 0 {
		,  := .ncopy(len())
		if  != nil {
			return 0, 
		}
		copy(.c.writeBuf[.pos:], [:])
		.pos += 
		 = [:]
	}
	return , nil
}

func ( *messageWriter) ( io.Reader) ( int64,  error) {
	if .err != nil {
		return 0, .err
	}
	for {
		if .pos == len(.c.writeBuf) {
			 = .flushFrame(false, nil)
			if  != nil {
				break
			}
		}
		var  int
		,  = .Read(.c.writeBuf[.pos:])
		.pos += 
		 += int64()
		if  != nil {
			if  == io.EOF {
				 = nil
			}
			break
		}
	}
	return , 
}

func ( *messageWriter) () error {
	if .err != nil {
		return .err
	}
	return .flushFrame(true, nil)
}

// WritePreparedMessage writes prepared message into connection.
func ( *Conn) ( *PreparedMessage) error {
	, ,  := .frame(prepareKey{
		isServer:         .isServer,
		compress:         .newCompressionWriter != nil && .enableWriteCompression && isData(.messageType),
		compressionLevel: .compressionLevel,
	})
	if  != nil {
		return 
	}
	if .isWriting {
		panic("concurrent write to websocket connection")
	}
	.isWriting = true
	 = .write(, .writeDeadline, , nil)
	if !.isWriting {
		panic("concurrent write to websocket connection")
	}
	.isWriting = false
	return 
}

// WriteMessage is a helper method for getting a writer using NextWriter,
// writing the message and closing the writer.
func ( *Conn) ( int,  []byte) error {

	if .isServer && (.newCompressionWriter == nil || !.enableWriteCompression) {
		// Fast path with no allocations and single frame.

		var  messageWriter
		if  := .beginMessage(&, );  != nil {
			return 
		}
		 := copy(.writeBuf[.pos:], )
		.pos += 
		 = [:]
		return .flushFrame(true, )
	}

	,  := .NextWriter()
	if  != nil {
		return 
	}
	if _,  = .Write();  != nil {
		return 
	}
	return .Close()
}

// SetWriteDeadline sets the write deadline on the underlying network
// connection. After a write has timed out, the websocket state is corrupt and
// all future writes will return an error. A zero value for t means writes will
// not time out.
func ( *Conn) ( time.Time) error {
	.writeDeadline = 
	return nil
}

// Read methods

func ( *Conn) () (int, error) {
	// 1. Skip remainder of previous frame.

	if .readRemaining > 0 {
		if ,  := io.CopyN(ioutil.Discard, .br, .readRemaining);  != nil {
			return noFrame, 
		}
	}

	// 2. Read and parse first two bytes of frame header.
	// To aid debugging, collect and report all errors in the first two bytes
	// of the header.

	var  []string

	,  := .read(2)
	if  != nil {
		return noFrame, 
	}

	 := int([0] & 0xf)
	 := [0]&finalBit != 0
	 := [0]&rsv1Bit != 0
	 := [0]&rsv2Bit != 0
	 := [0]&rsv3Bit != 0
	 := [1]&maskBit != 0
	.setReadRemaining(int64([1] & 0x7f))

	.readDecompress = false
	if  {
		if .newDecompressionReader != nil {
			.readDecompress = true
		} else {
			 = append(, "RSV1 set")
		}
	}

	if  {
		 = append(, "RSV2 set")
	}

	if  {
		 = append(, "RSV3 set")
	}

	switch  {
	case CloseMessage, PingMessage, PongMessage:
		if .readRemaining > maxControlFramePayloadSize {
			 = append(, "len > 125 for control")
		}
		if ! {
			 = append(, "FIN not set on control")
		}
	case TextMessage, BinaryMessage:
		if !.readFinal {
			 = append(, "data before FIN")
		}
		.readFinal = 
	case continuationFrame:
		if .readFinal {
			 = append(, "continuation after FIN")
		}
		.readFinal = 
	default:
		 = append(, "bad opcode "+strconv.Itoa())
	}

	if  != .isServer {
		 = append(, "bad MASK")
	}

	if len() > 0 {
		return noFrame, .handleProtocolError(strings.Join(, ", "))
	}

	// 3. Read and parse frame length as per
	// https://tools.ietf.org/html/rfc6455#section-5.2
	//
	// The length of the "Payload data", in bytes: if 0-125, that is the payload
	// length.
	// - If 126, the following 2 bytes interpreted as a 16-bit unsigned
	// integer are the payload length.
	// - If 127, the following 8 bytes interpreted as
	// a 64-bit unsigned integer (the most significant bit MUST be 0) are the
	// payload length. Multibyte length quantities are expressed in network byte
	// order.

	switch .readRemaining {
	case 126:
		,  := .read(2)
		if  != nil {
			return noFrame, 
		}

		if  := .setReadRemaining(int64(binary.BigEndian.Uint16()));  != nil {
			return noFrame, 
		}
	case 127:
		,  := .read(8)
		if  != nil {
			return noFrame, 
		}

		if  := .setReadRemaining(int64(binary.BigEndian.Uint64()));  != nil {
			return noFrame, 
		}
	}

	// 4. Handle frame masking.

	if  {
		.readMaskPos = 0
		,  := .read(len(.readMaskKey))
		if  != nil {
			return noFrame, 
		}
		copy(.readMaskKey[:], )
	}

	// 5. For text and binary messages, enforce read limit and return.

	if  == continuationFrame ||  == TextMessage ||  == BinaryMessage {

		.readLength += .readRemaining
		// Don't allow readLength to overflow in the presence of a large readRemaining
		// counter.
		if .readLength < 0 {
			return noFrame, ErrReadLimit
		}

		if .readLimit > 0 && .readLength > .readLimit {
			.WriteControl(CloseMessage, FormatCloseMessage(CloseMessageTooBig, ""), time.Now().Add(writeWait))
			return noFrame, ErrReadLimit
		}

		return , nil
	}

	// 6. Read control frame payload.

	var  []byte
	if .readRemaining > 0 {
		,  = .read(int(.readRemaining))
		.setReadRemaining(0)
		if  != nil {
			return noFrame, 
		}
		if .isServer {
			maskBytes(.readMaskKey, 0, )
		}
	}

	// 7. Process control frame payload.

	switch  {
	case PongMessage:
		if  := .handlePong(string());  != nil {
			return noFrame, 
		}
	case PingMessage:
		if  := .handlePing(string());  != nil {
			return noFrame, 
		}
	case CloseMessage:
		 := CloseNoStatusReceived
		 := ""
		if len() >= 2 {
			 = int(binary.BigEndian.Uint16())
			if !isValidReceivedCloseCode() {
				return noFrame, .handleProtocolError("bad close code " + strconv.Itoa())
			}
			 = string([2:])
			if !utf8.ValidString() {
				return noFrame, .handleProtocolError("invalid utf8 payload in close frame")
			}
		}
		if  := .handleClose(, );  != nil {
			return noFrame, 
		}
		return noFrame, &CloseError{Code: , Text: }
	}

	return , nil
}

func ( *Conn) ( string) error {
	 := FormatCloseMessage(CloseProtocolError, )
	if len() > maxControlFramePayloadSize {
		 = [:maxControlFramePayloadSize]
	}
	.WriteControl(CloseMessage, , time.Now().Add(writeWait))
	return errors.New("websocket: " + )
}

// NextReader returns the next data message received from the peer. The
// returned messageType is either TextMessage or BinaryMessage.
//
// There can be at most one open reader on a connection. NextReader discards
// the previous message if the application has not already consumed it.
//
// Applications must break out of the application's read loop when this method
// returns a non-nil error value. Errors returned from this method are
// permanent. Once this method returns a non-nil error, all subsequent calls to
// this method return the same error.
func ( *Conn) () ( int,  io.Reader,  error) {
	// Close previous reader, only relevant for decompression.
	if .reader != nil {
		.reader.Close()
		.reader = nil
	}

	.messageReader = nil
	.readLength = 0

	for .readErr == nil {
		,  := .advanceFrame()
		if  != nil {
			.readErr = hideTempErr()
			break
		}

		if  == TextMessage ||  == BinaryMessage {
			.messageReader = &messageReader{}
			.reader = .messageReader
			if .readDecompress {
				.reader = .newDecompressionReader(.reader)
			}
			return , .reader, nil
		}
	}

	// Applications that do handle the error returned from this method spin in
	// tight loop on connection failure. To help application developers detect
	// this error, panic on repeated reads to the failed connection.
	.readErrCount++
	if .readErrCount >= 1000 {
		panic("repeated read on failed websocket connection")
	}

	return noFrame, nil, .readErr
}

type messageReader struct{ c *Conn }

func ( *messageReader) ( []byte) (int, error) {
	 := .c
	if .messageReader !=  {
		return 0, io.EOF
	}

	for .readErr == nil {

		if .readRemaining > 0 {
			if int64(len()) > .readRemaining {
				 = [:.readRemaining]
			}
			,  := .br.Read()
			.readErr = hideTempErr()
			if .isServer {
				.readMaskPos = maskBytes(.readMaskKey, .readMaskPos, [:])
			}
			 := .readRemaining
			 -= int64()
			.setReadRemaining()
			if .readRemaining > 0 && .readErr == io.EOF {
				.readErr = errUnexpectedEOF
			}
			return , .readErr
		}

		if .readFinal {
			.messageReader = nil
			return 0, io.EOF
		}

		,  := .advanceFrame()
		switch {
		case  != nil:
			.readErr = hideTempErr()
		case  == TextMessage ||  == BinaryMessage:
			.readErr = errors.New("websocket: internal error, unexpected text or binary in Reader")
		}
	}

	 := .readErr
	if  == io.EOF && .messageReader ==  {
		 = errUnexpectedEOF
	}
	return 0, 
}

func ( *messageReader) () error {
	return nil
}

// ReadMessage is a helper method for getting a reader using NextReader and
// reading from that reader to a buffer.
func ( *Conn) () ( int,  []byte,  error) {
	var  io.Reader
	, ,  = .NextReader()
	if  != nil {
		return , nil, 
	}
	,  = ioutil.ReadAll()
	return , , 
}

// SetReadDeadline sets the read deadline on the underlying network connection.
// After a read has timed out, the websocket connection state is corrupt and
// all future reads will return an error. A zero value for t means reads will
// not time out.
func ( *Conn) ( time.Time) error {
	return .conn.SetReadDeadline()
}

// SetReadLimit sets the maximum size in bytes for a message read from the peer. If a
// message exceeds the limit, the connection sends a close message to the peer
// and returns ErrReadLimit to the application.
func ( *Conn) ( int64) {
	.readLimit = 
}

// CloseHandler returns the current close handler
func ( *Conn) () func( int,  string) error {
	return .handleClose
}

// SetCloseHandler sets the handler for close messages received from the peer.
// The code argument to h is the received close code or CloseNoStatusReceived
// if the close message is empty. The default close handler sends a close
// message back to the peer.
//
// The handler function is called from the NextReader, ReadMessage and message
// reader Read methods. The application must read the connection to process
// close messages as described in the section on Control Messages above.
//
// The connection read methods return a CloseError when a close message is
// received. Most applications should handle close messages as part of their
// normal error handling. Applications should only set a close handler when the
// application must perform some action before sending a close message back to
// the peer.
func ( *Conn) ( func( int,  string) error) {
	if  == nil {
		 = func( int,  string) error {
			 := FormatCloseMessage(, "")
			.WriteControl(CloseMessage, , time.Now().Add(writeWait))
			return nil
		}
	}
	.handleClose = 
}

// PingHandler returns the current ping handler
func ( *Conn) () func( string) error {
	return .handlePing
}

// SetPingHandler sets the handler for ping messages received from the peer.
// The appData argument to h is the PING message application data. The default
// ping handler sends a pong to the peer.
//
// The handler function is called from the NextReader, ReadMessage and message
// reader Read methods. The application must read the connection to process
// ping messages as described in the section on Control Messages above.
func ( *Conn) ( func( string) error) {
	if  == nil {
		 = func( string) error {
			 := .WriteControl(PongMessage, []byte(), time.Now().Add(writeWait))
			if  == ErrCloseSent {
				return nil
			} else if ,  := .(net.Error);  && .Temporary() {
				return nil
			}
			return 
		}
	}
	.handlePing = 
}

// PongHandler returns the current pong handler
func ( *Conn) () func( string) error {
	return .handlePong
}

// SetPongHandler sets the handler for pong messages received from the peer.
// The appData argument to h is the PONG message application data. The default
// pong handler does nothing.
//
// The handler function is called from the NextReader, ReadMessage and message
// reader Read methods. The application must read the connection to process
// pong messages as described in the section on Control Messages above.
func ( *Conn) ( func( string) error) {
	if  == nil {
		 = func(string) error { return nil }
	}
	.handlePong = 
}

// NetConn returns the underlying connection that is wrapped by c.
// Note that writing to or reading from this connection directly will corrupt the
// WebSocket connection.
func ( *Conn) () net.Conn {
	return .conn
}

// UnderlyingConn returns the internal net.Conn. This can be used to further
// modifications to connection specific flags.
// Deprecated: Use the NetConn method.
func ( *Conn) () net.Conn {
	return .conn
}

// EnableWriteCompression enables and disables write compression of
// subsequent text and binary messages. This function is a noop if
// compression was not negotiated with the peer.
func ( *Conn) ( bool) {
	.enableWriteCompression = 
}

// SetCompressionLevel sets the flate compression level for subsequent text and
// binary messages. This function is a noop if compression was not negotiated
// with the peer. See the compress/flate package for a description of
// compression levels.
func ( *Conn) ( int) error {
	if !isValidCompressionLevel() {
		return errors.New("websocket: invalid compression level")
	}
	.compressionLevel = 
	return nil
}

// FormatCloseMessage formats closeCode and text as a WebSocket close message.
// An empty message is returned for code CloseNoStatusReceived.
func ( int,  string) []byte {
	if  == CloseNoStatusReceived {
		// Return empty message because it's illegal to send
		// CloseNoStatusReceived. Return non-nil value in case application
		// checks for nil.
		return []byte{}
	}
	 := make([]byte, 2+len())
	binary.BigEndian.PutUint16(, uint16())
	copy([2:], )
	return 
}