good morning!!!!

Skip to content
Snippets Groups Projects
write.go 7.1 KiB
Newer Older
Anmol Sethi's avatar
Anmol Sethi committed
// +build !js

Anmol Sethi's avatar
Anmol Sethi committed
package websocket

import (
	"bufio"
	"compress/flate"
	"context"
	"crypto/rand"
	"encoding/binary"
	"io"
Anmol Sethi's avatar
Anmol Sethi committed
	"time"
Anmol Sethi's avatar
Anmol Sethi committed

Anmol Sethi's avatar
Anmol Sethi committed
	"golang.org/x/xerrors"

Anmol Sethi's avatar
Anmol Sethi committed
	"nhooyr.io/websocket/internal/errd"
Anmol Sethi's avatar
Anmol Sethi committed
)

// Writer returns a writer bounded by the context that will write
// a WebSocket message of type dataType to the connection.
//
// You must close the writer once you have written the entire message.
//
// Only one writer can be open at a time, multiple calls will block until the previous writer
// is closed.
//
// Never close the returned writer twice.
func (c *Conn) Writer(ctx context.Context, typ MessageType) (io.WriteCloser, error) {
Anmol Sethi's avatar
Anmol Sethi committed
	w, err := c.writer(ctx, typ)
Anmol Sethi's avatar
Anmol Sethi committed
	if err != nil {
Anmol Sethi's avatar
Anmol Sethi committed
		return nil, xerrors.Errorf("failed to get writer: %w", err)
Anmol Sethi's avatar
Anmol Sethi committed
	}
	return w, nil
}

// Write writes a message to the connection.
//
// See the Writer method if you want to stream a message.
//
Anmol Sethi's avatar
Anmol Sethi committed
// If compression is disabled or the threshold is not met, then it
// will write the message in a single frame.
Anmol Sethi's avatar
Anmol Sethi committed
func (c *Conn) Write(ctx context.Context, typ MessageType, p []byte) error {
Anmol Sethi's avatar
Anmol Sethi committed
	_, err := c.write(ctx, typ, p)
Anmol Sethi's avatar
Anmol Sethi committed
	if err != nil {
Anmol Sethi's avatar
Anmol Sethi committed
		return xerrors.Errorf("failed to write msg: %w", err)
Anmol Sethi's avatar
Anmol Sethi committed
	}
	return nil
}

Anmol Sethi's avatar
Anmol Sethi committed
type msgWriter struct {
	c *Conn

	mu      *mu
	writeMu sync.Mutex
Anmol Sethi's avatar
Anmol Sethi committed

	ctx    context.Context
	opcode opcode
	closed bool
	flate  bool

	trimWriter  *trimLastFourBytesWriter
	flateWriter *flate.Writer
}

Anmol Sethi's avatar
Anmol Sethi committed
func newMsgWriter(c *Conn) *msgWriter {
	mw := &msgWriter{
		c:  c,
		mu: newMu(c),
Anmol Sethi's avatar
Anmol Sethi committed
	}
	return mw
}

Anmol Sethi's avatar
Anmol Sethi committed
func (mw *msgWriter) ensureFlate() {
	if mw.trimWriter == nil {
		mw.trimWriter = &trimLastFourBytesWriter{
			w: writerFunc(mw.write),
	if mw.flateWriter == nil {
Anmol Sethi's avatar
Anmol Sethi committed
		mw.flateWriter = getFlateWriter(mw.trimWriter)
Anmol Sethi's avatar
Anmol Sethi committed
	}

	mw.flate = true
Anmol Sethi's avatar
Anmol Sethi committed
}

Anmol Sethi's avatar
Anmol Sethi committed
func (mw *msgWriter) flateContextTakeover() bool {
Anmol Sethi's avatar
Anmol Sethi committed
	if mw.c.client {
Anmol Sethi's avatar
Anmol Sethi committed
		return !mw.c.copts.clientNoContextTakeover
Anmol Sethi's avatar
Anmol Sethi committed
	}
Anmol Sethi's avatar
Anmol Sethi committed
	return !mw.c.copts.serverNoContextTakeover
Anmol Sethi's avatar
Anmol Sethi committed
}

Anmol Sethi's avatar
Anmol Sethi committed
func (c *Conn) writer(ctx context.Context, typ MessageType) (io.WriteCloser, error) {
	err := c.msgWriter.reset(ctx, typ)
Anmol Sethi's avatar
Anmol Sethi committed
	if err != nil {
		return nil, err
	}
Anmol Sethi's avatar
Anmol Sethi committed
	return c.msgWriter, nil
Anmol Sethi's avatar
Anmol Sethi committed
}

Anmol Sethi's avatar
Anmol Sethi committed
func (c *Conn) write(ctx context.Context, typ MessageType, p []byte) (int, error) {
	mw, err := c.writer(ctx, typ)
Anmol Sethi's avatar
Anmol Sethi committed
	if err != nil {
		return 0, err
	}

Anmol Sethi's avatar
Anmol Sethi committed
	if !c.flate() {
Anmol Sethi's avatar
Anmol Sethi committed
		defer c.msgWriter.mu.Unlock()
Anmol Sethi's avatar
Anmol Sethi committed
		return c.writeFrame(ctx, true, false, c.msgWriter.opcode, p)
Anmol Sethi's avatar
Anmol Sethi committed
	}

Anmol Sethi's avatar
Anmol Sethi committed
	n, err := mw.Write(p)
Anmol Sethi's avatar
Anmol Sethi committed
	if err != nil {
		return n, err
	}

Anmol Sethi's avatar
Anmol Sethi committed
	err = mw.Close()
Anmol Sethi's avatar
Anmol Sethi committed
	return n, err
}

Anmol Sethi's avatar
Anmol Sethi committed
func (mw *msgWriter) reset(ctx context.Context, typ MessageType) error {
Anmol Sethi's avatar
Anmol Sethi committed
	err := mw.mu.Lock(ctx)
	if err != nil {
		return err
	}

	mw.closed = false
	mw.ctx = ctx
	mw.opcode = opcode(typ)
Anmol Sethi's avatar
Anmol Sethi committed
	mw.flate = false

	if mw.trimWriter != nil {
		mw.trimWriter.reset()
	}

Anmol Sethi's avatar
Anmol Sethi committed
	return nil
}

Anmol Sethi's avatar
Anmol Sethi committed
func (mw *msgWriter) returnFlateWriter() {
	if mw.flateWriter != nil {
		putFlateWriter(mw.flateWriter)
		mw.flateWriter = nil
	}
}

Anmol Sethi's avatar
Anmol Sethi committed
// Write writes the given bytes to the WebSocket connection.
Anmol Sethi's avatar
Anmol Sethi committed
func (mw *msgWriter) Write(p []byte) (_ int, err error) {
Anmol Sethi's avatar
Anmol Sethi committed
	defer errd.Wrap(&err, "failed to write")

	mw.writeMu.Lock()
	defer mw.writeMu.Unlock()
Anmol Sethi's avatar
Anmol Sethi committed
	if mw.closed {
Anmol Sethi's avatar
Anmol Sethi committed
		return 0, xerrors.New("cannot use closed writer")
Anmol Sethi's avatar
Anmol Sethi committed
	}

	if mw.c.flate() {
		// Only enables flate if the length crosses the
		// threshold on the first frame
		if mw.opcode != opContinuation && len(p) >= mw.c.flateThreshold {
Anmol Sethi's avatar
Anmol Sethi committed
			mw.ensureFlate()
		}
	}

	if mw.flate {
Anmol Sethi's avatar
Anmol Sethi committed
		return mw.flateWriter.Write(p)
Anmol Sethi's avatar
Anmol Sethi committed
	}

	return mw.write(p)
}

Anmol Sethi's avatar
Anmol Sethi committed
func (mw *msgWriter) write(p []byte) (int, error) {
Anmol Sethi's avatar
Anmol Sethi committed
	n, err := mw.c.writeFrame(mw.ctx, false, mw.flate, mw.opcode, p)
Anmol Sethi's avatar
Anmol Sethi committed
	if err != nil {
Anmol Sethi's avatar
Anmol Sethi committed
		return n, xerrors.Errorf("failed to write data frame: %w", err)
Anmol Sethi's avatar
Anmol Sethi committed
	}
	mw.opcode = opContinuation
	return n, nil
}

// Close flushes the frame to the connection.
Anmol Sethi's avatar
Anmol Sethi committed
func (mw *msgWriter) Close() (err error) {
Anmol Sethi's avatar
Anmol Sethi committed
	defer errd.Wrap(&err, "failed to close writer")

	mw.writeMu.Lock()
	defer mw.writeMu.Unlock()
Anmol Sethi's avatar
Anmol Sethi committed
	if mw.closed {
Anmol Sethi's avatar
Anmol Sethi committed
		return xerrors.New("cannot use closed writer")
Anmol Sethi's avatar
Anmol Sethi committed
	}

Anmol Sethi's avatar
Anmol Sethi committed
	if mw.flate {
Anmol Sethi's avatar
Anmol Sethi committed
		err = mw.flateWriter.Flush()
Anmol Sethi's avatar
Anmol Sethi committed
		if err != nil {
Anmol Sethi's avatar
Anmol Sethi committed
			return xerrors.Errorf("failed to flush flate writer: %w", err)
Anmol Sethi's avatar
Anmol Sethi committed
		}
	}

	// We set closed after flushing the flate writer to ensure Write
	// can succeed.
	mw.closed = true

Anmol Sethi's avatar
Anmol Sethi committed
	_, err = mw.c.writeFrame(mw.ctx, true, mw.flate, mw.opcode, nil)
Anmol Sethi's avatar
Anmol Sethi committed
	if err != nil {
Anmol Sethi's avatar
Anmol Sethi committed
		return xerrors.Errorf("failed to write fin frame: %w", err)
Anmol Sethi's avatar
Anmol Sethi committed
	}

	if mw.flate && !mw.flateContextTakeover() {
Anmol Sethi's avatar
Anmol Sethi committed
		mw.returnFlateWriter()
Anmol Sethi's avatar
Anmol Sethi committed
	}
	mw.mu.Unlock()
	return nil
}

Anmol Sethi's avatar
Anmol Sethi committed
func (mw *msgWriter) close() {
	mw.writeMu.Lock()
Anmol Sethi's avatar
Anmol Sethi committed
	mw.returnFlateWriter()
Anmol Sethi's avatar
Anmol Sethi committed
}

func (c *Conn) writeControl(ctx context.Context, opcode opcode, p []byte) error {
Anmol Sethi's avatar
Anmol Sethi committed
	ctx, cancel := context.WithTimeout(ctx, time.Second*5)
	defer cancel()

Anmol Sethi's avatar
Anmol Sethi committed
	_, err := c.writeFrame(ctx, true, false, opcode, p)
Anmol Sethi's avatar
Anmol Sethi committed
	if err != nil {
Anmol Sethi's avatar
Anmol Sethi committed
		return xerrors.Errorf("failed to write control frame %v: %w", opcode, err)
Anmol Sethi's avatar
Anmol Sethi committed
	}
	return nil
}

// frame handles all writes to the connection.
Anmol Sethi's avatar
Anmol Sethi committed
func (c *Conn) writeFrame(ctx context.Context, fin bool, flate bool, opcode opcode, p []byte) (int, error) {
Anmol Sethi's avatar
Anmol Sethi committed
	err := c.writeFrameMu.Lock(ctx)
Anmol Sethi's avatar
Anmol Sethi committed
	if err != nil {
		return 0, err
	}
Anmol Sethi's avatar
Anmol Sethi committed
	defer c.writeFrameMu.Unlock()
Anmol Sethi's avatar
Anmol Sethi committed

	select {
Anmol Sethi's avatar
Anmol Sethi committed
	case <-c.closed:
		return 0, c.closeErr
	case c.writeTimeout <- ctx:
Anmol Sethi's avatar
Anmol Sethi committed
	}

Anmol Sethi's avatar
Anmol Sethi committed
	c.writeHeader.fin = fin
	c.writeHeader.opcode = opcode
	c.writeHeader.payloadLength = int64(len(p))
Anmol Sethi's avatar
Anmol Sethi committed

Anmol Sethi's avatar
Anmol Sethi committed
	if c.client {
		c.writeHeader.masked = true
		err = binary.Read(rand.Reader, binary.LittleEndian, &c.writeHeader.maskKey)
Anmol Sethi's avatar
Anmol Sethi committed
		if err != nil {
Anmol Sethi's avatar
Anmol Sethi committed
			return 0, xerrors.Errorf("failed to generate masking key: %w", err)
Anmol Sethi's avatar
Anmol Sethi committed
		}
	}

Anmol Sethi's avatar
Anmol Sethi committed
	c.writeHeader.rsv1 = false
Anmol Sethi's avatar
Anmol Sethi committed
	if flate && (opcode == opText || opcode == opBinary) {
Anmol Sethi's avatar
Anmol Sethi committed
		c.writeHeader.rsv1 = true
	}

	err = writeFrameHeader(c.writeHeader, c.bw)
Anmol Sethi's avatar
Anmol Sethi committed
	if err != nil {
		return 0, err
	}

Anmol Sethi's avatar
Anmol Sethi committed
	n, err := c.writeFramePayload(p)
Anmol Sethi's avatar
Anmol Sethi committed
	if err != nil {
		return n, err
	}

Anmol Sethi's avatar
Anmol Sethi committed
	if c.writeHeader.fin {
		err = c.bw.Flush()
Anmol Sethi's avatar
Anmol Sethi committed
		if err != nil {
Anmol Sethi's avatar
Anmol Sethi committed
			return n, xerrors.Errorf("failed to flush: %w", err)
Anmol Sethi's avatar
Anmol Sethi committed
		}
	}

	select {
Anmol Sethi's avatar
Anmol Sethi committed
	case <-c.closed:
		return n, c.closeErr
	case c.writeTimeout <- context.Background():
Anmol Sethi's avatar
Anmol Sethi committed
	}

	return n, nil
}

Anmol Sethi's avatar
Anmol Sethi committed
func (c *Conn) writeFramePayload(p []byte) (_ int, err error) {
Anmol Sethi's avatar
Anmol Sethi committed
	defer errd.Wrap(&err, "failed to write frame payload")

Anmol Sethi's avatar
Anmol Sethi committed
	if !c.writeHeader.masked {
		return c.bw.Write(p)
Anmol Sethi's avatar
Anmol Sethi committed
	}

	var n int
Anmol Sethi's avatar
Anmol Sethi committed
	maskKey := c.writeHeader.maskKey
Anmol Sethi's avatar
Anmol Sethi committed
	for len(p) > 0 {
		// If the buffer is full, we need to flush.
Anmol Sethi's avatar
Anmol Sethi committed
		if c.bw.Available() == 0 {
			err = c.bw.Flush()
Anmol Sethi's avatar
Anmol Sethi committed
			if err != nil {
				return n, err
			}
		}

		// Start of next write in the buffer.
Anmol Sethi's avatar
Anmol Sethi committed
		i := c.bw.Buffered()
Anmol Sethi's avatar
Anmol Sethi committed

		j := len(p)
Anmol Sethi's avatar
Anmol Sethi committed
		if j > c.bw.Available() {
			j = c.bw.Available()
Anmol Sethi's avatar
Anmol Sethi committed
		}

Anmol Sethi's avatar
Anmol Sethi committed
		_, err := c.bw.Write(p[:j])
Anmol Sethi's avatar
Anmol Sethi committed
		if err != nil {
			return n, err
		}

Anmol Sethi's avatar
Anmol Sethi committed
		maskKey = mask(maskKey, c.writeBuf[i:c.bw.Buffered()])
Anmol Sethi's avatar
Anmol Sethi committed

		p = p[j:]
		n += j
	}

	return n, nil
}

type writerFunc func(p []byte) (int, error)

func (f writerFunc) Write(p []byte) (int, error) {
	return f(p)
}

// extractBufioWriterBuf grabs the []byte backing a *bufio.Writer
// and returns it.
func extractBufioWriterBuf(bw *bufio.Writer, w io.Writer) []byte {
	var writeBuf []byte
	bw.Reset(writerFunc(func(p2 []byte) (int, error) {
		writeBuf = p2[:cap(p2)]
		return len(p2), nil
	}))

	bw.WriteByte(0)
	bw.Flush()

	bw.Reset(w)

	return writeBuf
}
Anmol Sethi's avatar
Anmol Sethi committed

func (c *Conn) writeError(code StatusCode, err error) {
	c.setCloseErr(err)
	c.writeClose(code, err.Error())
	c.close(nil)
}