1 // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
17 // HandshakeError describes an error with the handshake from the peer.
18 type HandshakeError struct {
22 func (e HandshakeError) Error() string { return e.message }
24 // Upgrader specifies parameters for upgrading an HTTP connection to a
25 // WebSocket connection.
26 type Upgrader struct {
27 // HandshakeTimeout specifies the duration for the handshake to complete.
28 HandshakeTimeout time.Duration
30 // ReadBufferSize and WriteBufferSize specify I/O buffer sizes in bytes. If a buffer
31 // size is zero, then buffers allocated by the HTTP server are used. The
32 // I/O buffer sizes do not limit the size of the messages that can be sent
34 ReadBufferSize, WriteBufferSize int
36 // WriteBufferPool is a pool of buffers for write operations. If the value
37 // is not set, then write buffers are allocated to the connection for the
38 // lifetime of the connection.
40 // A pool is most useful when the application has a modest volume of writes
41 // across a large number of connections.
43 // Applications should use a single pool for each unique value of
45 WriteBufferPool BufferPool
47 // Subprotocols specifies the server's supported protocols in order of
48 // preference. If this field is not nil, then the Upgrade method negotiates a
49 // subprotocol by selecting the first match in this list with a protocol
50 // requested by the client. If there's no match, then no protocol is
51 // negotiated (the Sec-Websocket-Protocol header is not included in the
52 // handshake response).
55 // Error specifies the function for generating HTTP error responses. If Error
56 // is nil, then http.Error is used to generate the HTTP response.
57 Error func(w http.ResponseWriter, r *http.Request, status int, reason error)
59 // CheckOrigin returns true if the request Origin header is acceptable. If
60 // CheckOrigin is nil, then a safe default is used: return false if the
61 // Origin request header is present and the origin host is not equal to
62 // request Host header.
64 // A CheckOrigin function should carefully validate the request origin to
65 // prevent cross-site request forgery.
66 CheckOrigin func(r *http.Request) bool
68 // EnableCompression specify if the server should attempt to negotiate per
69 // message compression (RFC 7692). Setting this value to true does not
70 // guarantee that compression will be supported. Currently only "no context
71 // takeover" modes are supported.
72 EnableCompression bool
75 func (u *Upgrader) returnError(w http.ResponseWriter, r *http.Request, status int, reason string) (*Conn, error) {
76 err := HandshakeError{reason}
78 u.Error(w, r, status, err)
80 w.Header().Set("Sec-Websocket-Version", "13")
81 http.Error(w, http.StatusText(status), status)
86 // checkSameOrigin returns true if the origin is not set or is equal to the request host.
87 func checkSameOrigin(r *http.Request) bool {
88 origin := r.Header["Origin"]
92 u, err := url.Parse(origin[0])
96 return equalASCIIFold(u.Host, r.Host)
99 func (u *Upgrader) selectSubprotocol(r *http.Request, responseHeader http.Header) string {
100 if u.Subprotocols != nil {
101 clientProtocols := Subprotocols(r)
102 for _, serverProtocol := range u.Subprotocols {
103 for _, clientProtocol := range clientProtocols {
104 if clientProtocol == serverProtocol {
105 return clientProtocol
109 } else if responseHeader != nil {
110 return responseHeader.Get("Sec-Websocket-Protocol")
115 // Upgrade upgrades the HTTP server connection to the WebSocket protocol.
117 // The responseHeader is included in the response to the client's upgrade
118 // request. Use the responseHeader to specify cookies (Set-Cookie) and the
119 // application negotiated subprotocol (Sec-WebSocket-Protocol).
121 // If the upgrade fails, then Upgrade replies to the client with an HTTP error
123 func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header) (*Conn, error) {
124 const badHandshake = "websocket: the client is not using the websocket protocol: "
126 if !tokenListContainsValue(r.Header, "Connection", "upgrade") {
127 return u.returnError(w, r, http.StatusBadRequest, badHandshake+"'upgrade' token not found in 'Connection' header")
130 if !tokenListContainsValue(r.Header, "Upgrade", "websocket") {
131 return u.returnError(w, r, http.StatusBadRequest, badHandshake+"'websocket' token not found in 'Upgrade' header")
134 if r.Method != "GET" {
135 return u.returnError(w, r, http.StatusMethodNotAllowed, badHandshake+"request method is not GET")
138 if !tokenListContainsValue(r.Header, "Sec-Websocket-Version", "13") {
139 return u.returnError(w, r, http.StatusBadRequest, "websocket: unsupported version: 13 not found in 'Sec-Websocket-Version' header")
142 if _, ok := responseHeader["Sec-Websocket-Extensions"]; ok {
143 return u.returnError(w, r, http.StatusInternalServerError, "websocket: application specific 'Sec-WebSocket-Extensions' headers are unsupported")
146 checkOrigin := u.CheckOrigin
147 if checkOrigin == nil {
148 checkOrigin = checkSameOrigin
151 return u.returnError(w, r, http.StatusForbidden, "websocket: request origin not allowed by Upgrader.CheckOrigin")
154 challengeKey := r.Header.Get("Sec-Websocket-Key")
155 if challengeKey == "" {
156 return u.returnError(w, r, http.StatusBadRequest, "websocket: not a websocket handshake: `Sec-WebSocket-Key' header is missing or blank")
159 subprotocol := u.selectSubprotocol(r, responseHeader)
163 if u.EnableCompression {
164 for _, ext := range parseExtensions(r.Header) {
165 if ext[""] != "permessage-deflate" {
173 h, ok := w.(http.Hijacker)
175 return u.returnError(w, r, http.StatusInternalServerError, "websocket: response does not implement http.Hijacker")
177 var brw *bufio.ReadWriter
178 netConn, brw, err := h.Hijack()
180 return u.returnError(w, r, http.StatusInternalServerError, err.Error())
183 if brw.Reader.Buffered() > 0 {
185 return nil, errors.New("websocket: client sent data before handshake is complete")
189 if u.ReadBufferSize == 0 && bufioReaderSize(netConn, brw.Reader) > 256 {
190 // Reuse hijacked buffered reader as connection reader.
194 buf := bufioWriterBuffer(netConn, brw.Writer)
197 if u.WriteBufferPool == nil && u.WriteBufferSize == 0 && len(buf) >= maxFrameHeaderSize+256 {
198 // Reuse hijacked write buffer as connection buffer.
202 c := newConn(netConn, true, u.ReadBufferSize, u.WriteBufferSize, u.WriteBufferPool, br, writeBuf)
203 c.subprotocol = subprotocol
206 c.newCompressionWriter = compressNoContextTakeover
207 c.newDecompressionReader = decompressNoContextTakeover
210 // Use larger of hijacked buffer and connection write buffer for header.
212 if len(c.writeBuf) > len(p) {
217 p = append(p, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: "...)
218 p = append(p, computeAcceptKey(challengeKey)...)
219 p = append(p, "\r\n"...)
220 if c.subprotocol != "" {
221 p = append(p, "Sec-WebSocket-Protocol: "...)
222 p = append(p, c.subprotocol...)
223 p = append(p, "\r\n"...)
226 p = append(p, "Sec-WebSocket-Extensions: permessage-deflate; server_no_context_takeover; client_no_context_takeover\r\n"...)
228 for k, vs := range responseHeader {
229 if k == "Sec-Websocket-Protocol" {
232 for _, v := range vs {
234 p = append(p, ": "...)
235 for i := 0; i < len(v); i++ {
238 // prevent response splitting.
243 p = append(p, "\r\n"...)
246 p = append(p, "\r\n"...)
248 // Clear deadlines set by HTTP server.
249 netConn.SetDeadline(time.Time{})
251 if u.HandshakeTimeout > 0 {
252 netConn.SetWriteDeadline(time.Now().Add(u.HandshakeTimeout))
254 if _, err = netConn.Write(p); err != nil {
258 if u.HandshakeTimeout > 0 {
259 netConn.SetWriteDeadline(time.Time{})
265 // Upgrade upgrades the HTTP server connection to the WebSocket protocol.
267 // Deprecated: Use websocket.Upgrader instead.
269 // Upgrade does not perform origin checking. The application is responsible for
270 // checking the Origin header before calling Upgrade. An example implementation
271 // of the same origin policy check is:
273 // if req.Header.Get("Origin") != "http://"+req.Host {
274 // http.Error(w, "Origin not allowed", http.StatusForbidden)
278 // If the endpoint supports subprotocols, then the application is responsible
279 // for negotiating the protocol used on the connection. Use the Subprotocols()
280 // function to get the subprotocols requested by the client. Use the
281 // Sec-Websocket-Protocol response header to specify the subprotocol selected
282 // by the application.
284 // The responseHeader is included in the response to the client's upgrade
285 // request. Use the responseHeader to specify cookies (Set-Cookie) and the
286 // negotiated subprotocol (Sec-Websocket-Protocol).
288 // The connection buffers IO to the underlying network connection. The
289 // readBufSize and writeBufSize parameters specify the size of the buffers to
290 // use. Messages can be larger than the buffers.
292 // If the request is not a valid WebSocket handshake, then Upgrade returns an
293 // error of type HandshakeError. Applications should handle this error by
294 // replying to the client with an HTTP error response.
295 func Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header, readBufSize, writeBufSize int) (*Conn, error) {
296 u := Upgrader{ReadBufferSize: readBufSize, WriteBufferSize: writeBufSize}
297 u.Error = func(w http.ResponseWriter, r *http.Request, status int, reason error) {
298 // don't return errors to maintain backwards compatibility
300 u.CheckOrigin = func(r *http.Request) bool {
301 // allow all connections by default
304 return u.Upgrade(w, r, responseHeader)
307 // Subprotocols returns the subprotocols requested by the client in the
308 // Sec-Websocket-Protocol header.
309 func Subprotocols(r *http.Request) []string {
310 h := strings.TrimSpace(r.Header.Get("Sec-Websocket-Protocol"))
314 protocols := strings.Split(h, ",")
315 for i := range protocols {
316 protocols[i] = strings.TrimSpace(protocols[i])
321 // IsWebSocketUpgrade returns true if the client requested upgrade to the
322 // WebSocket protocol.
323 func IsWebSocketUpgrade(r *http.Request) bool {
324 return tokenListContainsValue(r.Header, "Connection", "upgrade") &&
325 tokenListContainsValue(r.Header, "Upgrade", "websocket")
328 // bufioReaderSize size returns the size of a bufio.Reader.
329 func bufioReaderSize(originalReader io.Reader, br *bufio.Reader) int {
330 // This code assumes that peek on a reset reader returns
331 // bufio.Reader.buf[:0].
332 // TODO: Use bufio.Reader.Size() after Go 1.10
333 br.Reset(originalReader)
334 if p, err := br.Peek(0); err == nil {
340 // writeHook is an io.Writer that records the last slice passed to it vio
342 type writeHook struct {
346 func (wh *writeHook) Write(p []byte) (int, error) {
351 // bufioWriterBuffer grabs the buffer from a bufio.Writer.
352 func bufioWriterBuffer(originalWriter io.Writer, bw *bufio.Writer) []byte {
353 // This code assumes that bufio.Writer.buf[:1] is passed to the
354 // bufio.Writer's underlying writer.
360 bw.Reset(originalWriter)
362 return wh.p[:cap(wh.p)]