// Package ws implements what a relay needs of RFC 6455 WebSockets: the opening // handshake response, masked client frame parsing, and the frame and close bytes // the writer domain sends. // // It deliberately has no connection type. The relay splits a socket between a // reader domain and a writer domain, so a value that owns both directions cannot // be used: the reader calls Reader, the writer calls AppendFrame and AppendClose, // and the connection itself belongs to pkg/domain/io. package ws import ( "crypto/sha1" "encoding/base64" "errors" "strings" ) // Frame opcodes. const ( OpContinuation = 0x0 OpText = 0x1 OpBinary = 0x2 OpClose = 0x8 OpPing = 0x9 OpPong = 0xa ) const acceptGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" var ( // ErrProtocol is returned for a framing violation. ErrProtocol = errors.New("ws: protocol error") // ErrTooLarge is returned when a message exceeds the reader's limit. ErrTooLarge = errors.New("ws: message too large") ) // headerContains reports whether a comma-separated header value contains token. func headerContains(value, token string) bool { for _, part := range strings.Split(value, ",") { if strings.EqualFold(strings.TrimSpace(part), token) { return true } } return false } // HandshakeResponse validates the opening handshake headers and returns the // complete 101 response. Reader workers use it so that only their paired writer // domain writes to the socket. func HandshakeResponse(header map[string]string) ([]byte, error) { if !headerContains(header["upgrade"], "websocket") { return nil, errors.New("ws: missing Upgrade: websocket") } if !headerContains(header["connection"], "upgrade") { return nil, errors.New("ws: missing Connection: Upgrade") } if header["sec-websocket-version"] != "13" { return nil, errors.New("ws: unsupported websocket version") } key := header["sec-websocket-key"] if key == "" { return nil, errors.New("ws: missing Sec-WebSocket-Key") } sum := sha1.Sum([]byte(key + acceptGUID)) accept := base64.StdEncoding.EncodeToString(sum[:]) out := []byte("HTTP/1.1 101 Switching Protocols\r\n" + "Upgrade: websocket\r\n" + "Connection: Upgrade\r\n" + "Sec-WebSocket-Accept: " + accept + "\r\n\r\n") return out, nil }