2014-04-19 01:25:11 +04:00
|
|
|
// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
|
2013-10-16 20:41:47 +04:00
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package websocket
|
|
|
|
|
|
|
|
import (
|
2014-04-18 01:45:40 +04:00
|
|
|
"bufio"
|
|
|
|
"errors"
|
2016-04-27 00:43:57 +03:00
|
|
|
"fmt"
|
2014-04-18 01:45:40 +04:00
|
|
|
"net"
|
2013-10-16 20:41:47 +04:00
|
|
|
"net/http"
|
2014-04-18 02:07:36 +04:00
|
|
|
"net/url"
|
2013-10-26 17:52:30 +04:00
|
|
|
"strings"
|
2014-04-18 01:45:40 +04:00
|
|
|
"time"
|
2013-10-16 20:41:47 +04:00
|
|
|
)
|
|
|
|
|
|
|
|
// HandshakeError describes an error with the handshake from the peer.
|
|
|
|
type HandshakeError struct {
|
2013-10-27 19:34:33 +04:00
|
|
|
message string
|
2013-10-16 20:41:47 +04:00
|
|
|
}
|
|
|
|
|
2013-10-27 19:34:33 +04:00
|
|
|
func (e HandshakeError) Error() string { return e.message }
|
2013-10-16 20:41:47 +04:00
|
|
|
|
2014-04-20 22:38:35 +04:00
|
|
|
// Upgrader specifies parameters for upgrading an HTTP connection to a
|
|
|
|
// WebSocket connection.
|
2014-04-18 01:45:40 +04:00
|
|
|
type Upgrader struct {
|
|
|
|
// HandshakeTimeout specifies the duration for the handshake to complete.
|
|
|
|
HandshakeTimeout time.Duration
|
|
|
|
|
2014-04-20 22:38:35 +04:00
|
|
|
// ReadBufferSize and WriteBufferSize specify I/O buffer sizes. If a buffer
|
|
|
|
// size is zero, then a default value of 4096 is used. The I/O buffer sizes
|
|
|
|
// do not limit the size of the messages that can be sent or received.
|
2014-04-18 01:45:40 +04:00
|
|
|
ReadBufferSize, WriteBufferSize int
|
|
|
|
|
2014-04-20 22:38:35 +04:00
|
|
|
// Subprotocols specifies the server's supported protocols in order of
|
|
|
|
// preference. If this field is set, then the Upgrade method negotiates a
|
|
|
|
// subprotocol by selecting the first match in this list with a protocol
|
|
|
|
// requested by the client.
|
|
|
|
Subprotocols []string
|
2014-04-18 01:45:40 +04:00
|
|
|
|
2016-04-27 00:43:57 +03:00
|
|
|
// Server supported extensions (e.g. permessage-deflate)
|
|
|
|
// Currently only 'permessage-deflate; server_no_context_takeover; client_no_context_takeover'
|
|
|
|
// is supported. i.e. no deflate options at this time.
|
|
|
|
Extensions []string
|
|
|
|
|
2014-04-18 01:45:40 +04:00
|
|
|
// Error specifies the function for generating HTTP error responses. If Error
|
|
|
|
// is nil, then http.Error is used to generate the HTTP response.
|
|
|
|
Error func(w http.ResponseWriter, r *http.Request, status int, reason error)
|
|
|
|
|
2014-04-20 22:38:35 +04:00
|
|
|
// CheckOrigin returns true if the request Origin header is acceptable. If
|
2014-07-01 01:57:20 +04:00
|
|
|
// CheckOrigin is nil, the host in the Origin header must not be set or
|
|
|
|
// must match the host of the request.
|
2014-04-18 01:45:40 +04:00
|
|
|
CheckOrigin func(r *http.Request) bool
|
|
|
|
}
|
|
|
|
|
2014-04-18 02:20:46 +04:00
|
|
|
func (u *Upgrader) returnError(w http.ResponseWriter, r *http.Request, status int, reason string) (*Conn, error) {
|
|
|
|
err := HandshakeError{reason}
|
2014-04-18 01:45:40 +04:00
|
|
|
if u.Error != nil {
|
2014-04-18 02:20:46 +04:00
|
|
|
u.Error(w, r, status, err)
|
2014-04-18 01:45:40 +04:00
|
|
|
} else {
|
2014-04-20 22:38:35 +04:00
|
|
|
http.Error(w, http.StatusText(status), status)
|
2014-04-18 01:45:40 +04:00
|
|
|
}
|
2014-04-18 02:20:46 +04:00
|
|
|
return nil, err
|
2014-04-18 01:45:40 +04:00
|
|
|
}
|
|
|
|
|
2014-07-01 01:57:20 +04:00
|
|
|
// checkSameOrigin returns true if the origin is not set or is equal to the request host.
|
2014-04-20 22:38:35 +04:00
|
|
|
func checkSameOrigin(r *http.Request) bool {
|
2014-07-01 01:57:20 +04:00
|
|
|
origin := r.Header["Origin"]
|
|
|
|
if len(origin) == 0 {
|
|
|
|
return true
|
2014-04-18 02:07:36 +04:00
|
|
|
}
|
2014-07-01 01:57:20 +04:00
|
|
|
u, err := url.Parse(origin[0])
|
2014-04-18 02:07:36 +04:00
|
|
|
if err != nil {
|
|
|
|
return false
|
|
|
|
}
|
2014-04-20 22:38:35 +04:00
|
|
|
return u.Host == r.Host
|
|
|
|
}
|
|
|
|
|
|
|
|
func (u *Upgrader) selectSubprotocol(r *http.Request, responseHeader http.Header) string {
|
|
|
|
if u.Subprotocols != nil {
|
|
|
|
clientProtocols := Subprotocols(r)
|
|
|
|
for _, serverProtocol := range u.Subprotocols {
|
|
|
|
for _, clientProtocol := range clientProtocols {
|
|
|
|
if clientProtocol == serverProtocol {
|
|
|
|
return clientProtocol
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else if responseHeader != nil {
|
|
|
|
return responseHeader.Get("Sec-Websocket-Protocol")
|
|
|
|
}
|
|
|
|
return ""
|
2014-04-18 02:07:36 +04:00
|
|
|
}
|
|
|
|
|
2016-04-27 00:43:57 +03:00
|
|
|
// Check for compression support, select compression type and
|
|
|
|
// return extension with server supported options along with
|
|
|
|
// whether valid compression headers were found.
|
|
|
|
func (u *Upgrader) selectCompressionExtension(r *http.Request) (string, bool, error) {
|
|
|
|
extensions := r.Header.Get("Sec-WebSocket-Extensions")
|
|
|
|
|
|
|
|
if u.Extensions != nil && len(extensions) > 0 {
|
|
|
|
|
|
|
|
extOpts := strings.Split(extensions, " ")
|
|
|
|
if len(extOpts) > 0 && strings.HasPrefix(extOpts[0], "permessage-deflate") {
|
|
|
|
ext := strings.TrimSuffix(extOpts[0], ";")
|
|
|
|
// Find and return extension with supported options.
|
|
|
|
for _, e := range u.Extensions {
|
|
|
|
// Check if server supports supplied extension
|
|
|
|
if strings.HasPrefix(e, ext) {
|
|
|
|
if e != CompressPermessageDeflate {
|
|
|
|
return "", false, fmt.Errorf("Compression options not supported: %s", e)
|
|
|
|
}
|
|
|
|
return e, true, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return "", false, nil
|
|
|
|
}
|
|
|
|
|
2014-04-18 01:45:40 +04:00
|
|
|
// Upgrade upgrades the HTTP server connection to the WebSocket protocol.
|
|
|
|
//
|
|
|
|
// The responseHeader is included in the response to the client's upgrade
|
2014-04-20 22:38:35 +04:00
|
|
|
// request. Use the responseHeader to specify cookies (Set-Cookie) and the
|
|
|
|
// application negotiated subprotocol (Sec-Websocket-Protocol).
|
2014-04-18 01:45:40 +04:00
|
|
|
func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header) (*Conn, error) {
|
2015-11-02 20:08:11 +03:00
|
|
|
if r.Method != "GET" {
|
|
|
|
return u.returnError(w, r, http.StatusMethodNotAllowed, "websocket: method not GET")
|
|
|
|
}
|
2014-04-18 01:45:40 +04:00
|
|
|
if values := r.Header["Sec-Websocket-Version"]; len(values) == 0 || values[0] != "13" {
|
2014-04-18 02:20:46 +04:00
|
|
|
return u.returnError(w, r, http.StatusBadRequest, "websocket: version != 13")
|
2014-04-18 01:45:40 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
if !tokenListContainsValue(r.Header, "Connection", "upgrade") {
|
2015-01-15 09:16:10 +03:00
|
|
|
return u.returnError(w, r, http.StatusBadRequest, "websocket: could not find connection header with token 'upgrade'")
|
2014-04-18 01:45:40 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
if !tokenListContainsValue(r.Header, "Upgrade", "websocket") {
|
2015-01-15 09:16:10 +03:00
|
|
|
return u.returnError(w, r, http.StatusBadRequest, "websocket: could not find upgrade header with token 'websocket'")
|
2014-04-18 01:45:40 +04:00
|
|
|
}
|
|
|
|
|
2014-04-18 02:07:36 +04:00
|
|
|
checkOrigin := u.CheckOrigin
|
|
|
|
if checkOrigin == nil {
|
2014-04-20 22:38:35 +04:00
|
|
|
checkOrigin = checkSameOrigin
|
2014-04-18 02:07:36 +04:00
|
|
|
}
|
|
|
|
if !checkOrigin(r) {
|
2014-04-18 02:20:46 +04:00
|
|
|
return u.returnError(w, r, http.StatusForbidden, "websocket: origin not allowed")
|
2014-04-18 01:45:40 +04:00
|
|
|
}
|
|
|
|
|
2014-04-20 22:38:35 +04:00
|
|
|
challengeKey := r.Header.Get("Sec-Websocket-Key")
|
|
|
|
if challengeKey == "" {
|
2014-04-18 02:20:46 +04:00
|
|
|
return u.returnError(w, r, http.StatusBadRequest, "websocket: key missing or blank")
|
2014-04-18 01:45:40 +04:00
|
|
|
}
|
2014-04-20 22:38:35 +04:00
|
|
|
|
|
|
|
subprotocol := u.selectSubprotocol(r, responseHeader)
|
2014-04-18 01:45:40 +04:00
|
|
|
|
|
|
|
var (
|
|
|
|
netConn net.Conn
|
|
|
|
br *bufio.Reader
|
|
|
|
err error
|
|
|
|
)
|
|
|
|
|
|
|
|
h, ok := w.(http.Hijacker)
|
|
|
|
if !ok {
|
2014-04-20 22:38:35 +04:00
|
|
|
return u.returnError(w, r, http.StatusInternalServerError, "websocket: response does not implement http.Hijacker")
|
2014-04-18 01:45:40 +04:00
|
|
|
}
|
|
|
|
var rw *bufio.ReadWriter
|
|
|
|
netConn, rw, err = h.Hijack()
|
2014-08-16 07:25:38 +04:00
|
|
|
if err != nil {
|
|
|
|
return u.returnError(w, r, http.StatusInternalServerError, err.Error())
|
|
|
|
}
|
2014-04-18 01:45:40 +04:00
|
|
|
br = rw.Reader
|
|
|
|
|
|
|
|
if br.Buffered() > 0 {
|
|
|
|
netConn.Close()
|
|
|
|
return nil, errors.New("websocket: client sent data before handshake is complete")
|
|
|
|
}
|
|
|
|
|
2014-11-05 23:26:52 +03:00
|
|
|
c := newConn(netConn, true, u.ReadBufferSize, u.WriteBufferSize)
|
2014-04-20 22:38:35 +04:00
|
|
|
c.subprotocol = subprotocol
|
2016-04-27 00:43:57 +03:00
|
|
|
_, c.compressionNegotiated, err = u.selectCompressionExtension(r)
|
|
|
|
if err != nil {
|
|
|
|
return u.returnError(w, r, http.StatusInternalServerError, err.Error())
|
|
|
|
}
|
2014-04-18 01:45:40 +04:00
|
|
|
|
|
|
|
p := c.writeBuf[:0]
|
|
|
|
p = append(p, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: "...)
|
|
|
|
p = append(p, computeAcceptKey(challengeKey)...)
|
|
|
|
p = append(p, "\r\n"...)
|
|
|
|
if c.subprotocol != "" {
|
|
|
|
p = append(p, "Sec-Websocket-Protocol: "...)
|
|
|
|
p = append(p, c.subprotocol...)
|
|
|
|
p = append(p, "\r\n"...)
|
|
|
|
}
|
|
|
|
for k, vs := range responseHeader {
|
|
|
|
if k == "Sec-Websocket-Protocol" {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
for _, v := range vs {
|
|
|
|
p = append(p, k...)
|
|
|
|
p = append(p, ": "...)
|
|
|
|
for i := 0; i < len(v); i++ {
|
|
|
|
b := v[i]
|
|
|
|
if b <= 31 {
|
|
|
|
// prevent response splitting.
|
|
|
|
b = ' '
|
|
|
|
}
|
|
|
|
p = append(p, b)
|
|
|
|
}
|
|
|
|
p = append(p, "\r\n"...)
|
|
|
|
}
|
|
|
|
}
|
2016-04-27 00:43:57 +03:00
|
|
|
// Set the selected compression header if enabled.
|
|
|
|
if c.compressionNegotiated {
|
|
|
|
// Turn compression on by default
|
|
|
|
c.writeCompressionEnabled = true
|
|
|
|
p = append(p, "Sec-WebSocket-Extensions: "+CompressPermessageDeflate+"\r\n"...)
|
|
|
|
}
|
|
|
|
|
2014-04-18 01:45:40 +04:00
|
|
|
p = append(p, "\r\n"...)
|
|
|
|
|
2014-06-30 06:47:15 +04:00
|
|
|
// Clear deadlines set by HTTP server.
|
|
|
|
netConn.SetDeadline(time.Time{})
|
|
|
|
|
2014-04-18 01:45:40 +04:00
|
|
|
if u.HandshakeTimeout > 0 {
|
|
|
|
netConn.SetWriteDeadline(time.Now().Add(u.HandshakeTimeout))
|
|
|
|
}
|
|
|
|
if _, err = netConn.Write(p); err != nil {
|
|
|
|
netConn.Close()
|
|
|
|
return nil, err
|
|
|
|
}
|
2014-04-21 17:28:28 +04:00
|
|
|
if u.HandshakeTimeout > 0 {
|
|
|
|
netConn.SetWriteDeadline(time.Time{})
|
|
|
|
}
|
2014-04-18 01:45:40 +04:00
|
|
|
|
|
|
|
return c, nil
|
|
|
|
}
|
|
|
|
|
2013-10-16 20:41:47 +04:00
|
|
|
// Upgrade upgrades the HTTP server connection to the WebSocket protocol.
|
|
|
|
//
|
2014-04-20 22:38:35 +04:00
|
|
|
// This function is deprecated, use websocket.Upgrader instead.
|
|
|
|
//
|
2013-10-16 20:41:47 +04:00
|
|
|
// The application is responsible for checking the request origin before
|
|
|
|
// calling Upgrade. An example implementation of the same origin policy is:
|
|
|
|
//
|
|
|
|
// if req.Header.Get("Origin") != "http://"+req.Host {
|
|
|
|
// http.Error(w, "Origin not allowed", 403)
|
|
|
|
// return
|
|
|
|
// }
|
|
|
|
//
|
2013-12-21 02:54:49 +04:00
|
|
|
// If the endpoint supports subprotocols, then the application is responsible
|
|
|
|
// for negotiating the protocol used on the connection. Use the Subprotocols()
|
|
|
|
// function to get the subprotocols requested by the client. Use the
|
|
|
|
// Sec-Websocket-Protocol response header to specify the subprotocol selected
|
|
|
|
// by the application.
|
2013-10-27 19:34:33 +04:00
|
|
|
//
|
2013-12-21 02:54:49 +04:00
|
|
|
// The responseHeader is included in the response to the client's upgrade
|
|
|
|
// request. Use the responseHeader to specify cookies (Set-Cookie) and the
|
|
|
|
// negotiated subprotocol (Sec-Websocket-Protocol).
|
|
|
|
//
|
|
|
|
// The connection buffers IO to the underlying network connection. The
|
|
|
|
// readBufSize and writeBufSize parameters specify the size of the buffers to
|
|
|
|
// use. Messages can be larger than the buffers.
|
2013-10-27 19:34:33 +04:00
|
|
|
//
|
|
|
|
// If the request is not a valid WebSocket handshake, then Upgrade returns an
|
|
|
|
// error of type HandshakeError. Applications should handle this error by
|
|
|
|
// replying to the client with an HTTP error response.
|
2013-10-16 20:41:47 +04:00
|
|
|
func Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header, readBufSize, writeBufSize int) (*Conn, error) {
|
2014-04-16 19:25:17 +04:00
|
|
|
u := Upgrader{ReadBufferSize: readBufSize, WriteBufferSize: writeBufSize}
|
|
|
|
u.Error = func(w http.ResponseWriter, r *http.Request, status int, reason error) {
|
|
|
|
// don't return errors to maintain backwards compatibility
|
2013-12-14 19:48:43 +04:00
|
|
|
}
|
2014-04-18 02:07:36 +04:00
|
|
|
u.CheckOrigin = func(r *http.Request) bool {
|
|
|
|
// allow all connections by default
|
|
|
|
return true
|
|
|
|
}
|
2014-04-16 19:25:17 +04:00
|
|
|
return u.Upgrade(w, r, responseHeader)
|
2013-10-16 20:41:47 +04:00
|
|
|
}
|
2013-10-26 17:52:30 +04:00
|
|
|
|
|
|
|
// Subprotocols returns the subprotocols requested by the client in the
|
|
|
|
// Sec-Websocket-Protocol header.
|
|
|
|
func Subprotocols(r *http.Request) []string {
|
|
|
|
h := strings.TrimSpace(r.Header.Get("Sec-Websocket-Protocol"))
|
|
|
|
if h == "" {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
protocols := strings.Split(h, ",")
|
|
|
|
for i := range protocols {
|
|
|
|
protocols[i] = strings.TrimSpace(protocols[i])
|
|
|
|
}
|
|
|
|
return protocols
|
|
|
|
}
|