handshake.go raw

   1  // Package ws implements what a relay needs of RFC 6455 WebSockets: the opening
   2  // handshake response, masked client frame parsing, and the frame and close bytes
   3  // the writer domain sends.
   4  //
   5  // It deliberately has no connection type. The relay splits a socket between a
   6  // reader domain and a writer domain, so a value that owns both directions cannot
   7  // be used: the reader calls Reader, the writer calls AppendFrame and AppendClose,
   8  // and the connection itself belongs to pkg/domain/io.
   9  package ws
  10  
  11  import (
  12  	"crypto/sha1"
  13  	"encoding/base64"
  14  	"errors"
  15  	"strings"
  16  )
  17  
  18  // Frame opcodes.
  19  const (
  20  	OpContinuation = 0x0
  21  	OpText         = 0x1
  22  	OpBinary       = 0x2
  23  	OpClose        = 0x8
  24  	OpPing         = 0x9
  25  	OpPong         = 0xa
  26  )
  27  
  28  const acceptGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
  29  
  30  var (
  31  	// ErrProtocol is returned for a framing violation.
  32  	ErrProtocol = errors.New("ws: protocol error")
  33  	// ErrTooLarge is returned when a message exceeds the reader's limit.
  34  	ErrTooLarge = errors.New("ws: message too large")
  35  )
  36  
  37  // headerContains reports whether a comma-separated header value contains token.
  38  func headerContains(value, token string) bool {
  39  	for _, part := range strings.Split(value, ",") {
  40  		if strings.EqualFold(strings.TrimSpace(part), token) {
  41  			return true
  42  		}
  43  	}
  44  	return false
  45  }
  46  
  47  // HandshakeResponse validates the opening handshake headers and returns the
  48  // complete 101 response. Reader workers use it so that only their paired writer
  49  // domain writes to the socket.
  50  func HandshakeResponse(header map[string]string) ([]byte, error) {
  51  	if !headerContains(header["upgrade"], "websocket") {
  52  		return nil, errors.New("ws: missing Upgrade: websocket")
  53  	}
  54  	if !headerContains(header["connection"], "upgrade") {
  55  		return nil, errors.New("ws: missing Connection: Upgrade")
  56  	}
  57  	if header["sec-websocket-version"] != "13" {
  58  		return nil, errors.New("ws: unsupported websocket version")
  59  	}
  60  	key := header["sec-websocket-key"]
  61  	if key == "" {
  62  		return nil, errors.New("ws: missing Sec-WebSocket-Key")
  63  	}
  64  	sum := sha1.Sum([]byte(key + acceptGUID))
  65  	accept := base64.StdEncoding.EncodeToString(sum[:])
  66  	out := []byte("HTTP/1.1 101 Switching Protocols\r\n" +
  67  		"Upgrade: websocket\r\n" +
  68  		"Connection: Upgrade\r\n" +
  69  		"Sec-WebSocket-Accept: " + accept + "\r\n\r\n")
  70  	return out, nil
  71  }
  72