server.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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.
  4. package websocket
  5. import (
  6. "bufio"
  7. "errors"
  8. "net"
  9. "net/http"
  10. "net/url"
  11. "strings"
  12. "time"
  13. )
  14. // HandshakeError describes an error with the handshake from the peer.
  15. type HandshakeError struct {
  16. message string
  17. }
  18. func (e HandshakeError) Error() string { return e.message }
  19. // Upgrader specifies parameters for upgrading an HTTP connection to a
  20. // WebSocket connection.
  21. type Upgrader struct {
  22. // HandshakeTimeout specifies the duration for the handshake to complete.
  23. HandshakeTimeout time.Duration
  24. // ReadBufferSize and WriteBufferSize specify I/O buffer sizes. If a buffer
  25. // size is zero, then a default value of 4096 is used. The I/O buffer sizes
  26. // do not limit the size of the messages that can be sent or received.
  27. ReadBufferSize, WriteBufferSize int
  28. // Subprotocols specifies the server's supported protocols in order of
  29. // preference. If this field is set, then the Upgrade method negotiates a
  30. // subprotocol by selecting the first match in this list with a protocol
  31. // requested by the client.
  32. Subprotocols []string
  33. // Error specifies the function for generating HTTP error responses. If Error
  34. // is nil, then http.Error is used to generate the HTTP response.
  35. Error func(w http.ResponseWriter, r *http.Request, status int, reason error)
  36. // CheckOrigin returns true if the request Origin header is acceptable. If
  37. // CheckOrigin is nil, the host in the Origin header must not be set or
  38. // must match the host of the request.
  39. CheckOrigin func(r *http.Request) bool
  40. // EnableCompression specify if the server should attempt to negotiate per
  41. // message compression (RFC 7692). Setting this value to true does not
  42. // guarantee that compression will be supported. Currently only "no context
  43. // takeover" modes are supported.
  44. EnableCompression bool
  45. }
  46. func (u *Upgrader) returnError(w http.ResponseWriter, r *http.Request, status int, reason string) (*Conn, error) {
  47. err := HandshakeError{reason}
  48. if u.Error != nil {
  49. u.Error(w, r, status, err)
  50. } else {
  51. w.Header().Set("Sec-Websocket-Version", "13")
  52. http.Error(w, http.StatusText(status), status)
  53. }
  54. return nil, err
  55. }
  56. // checkSameOrigin returns true if the origin is not set or is equal to the request host.
  57. func checkSameOrigin(r *http.Request) bool {
  58. origin := r.Header["Origin"]
  59. if len(origin) == 0 {
  60. return true
  61. }
  62. u, err := url.Parse(origin[0])
  63. if err != nil {
  64. return false
  65. }
  66. return u.Host == r.Host
  67. }
  68. func (u *Upgrader) selectSubprotocol(r *http.Request, responseHeader http.Header) string {
  69. if u.Subprotocols != nil {
  70. clientProtocols := Subprotocols(r)
  71. for _, serverProtocol := range u.Subprotocols {
  72. for _, clientProtocol := range clientProtocols {
  73. if clientProtocol == serverProtocol {
  74. return clientProtocol
  75. }
  76. }
  77. }
  78. } else if responseHeader != nil {
  79. return responseHeader.Get("Sec-Websocket-Protocol")
  80. }
  81. return ""
  82. }
  83. // Upgrade upgrades the HTTP server connection to the WebSocket protocol.
  84. //
  85. // The responseHeader is included in the response to the client's upgrade
  86. // request. Use the responseHeader to specify cookies (Set-Cookie) and the
  87. // application negotiated subprotocol (Sec-Websocket-Protocol).
  88. //
  89. // If the upgrade fails, then Upgrade replies to the client with an HTTP error
  90. // response.
  91. func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header) (*Conn, error) {
  92. if r.Method != "GET" {
  93. return u.returnError(w, r, http.StatusMethodNotAllowed, "websocket: not a websocket handshake: request method is not GET")
  94. }
  95. if _, ok := responseHeader["Sec-Websocket-Extensions"]; ok {
  96. return u.returnError(w, r, http.StatusInternalServerError, "websocket: application specific 'Sec-Websocket-Extensions' headers are unsupported")
  97. }
  98. if !tokenListContainsValue(r.Header, "Connection", "upgrade") {
  99. return u.returnError(w, r, http.StatusBadRequest, "websocket: not a websocket handshake: 'upgrade' token not found in 'Connection' header")
  100. }
  101. if !tokenListContainsValue(r.Header, "Upgrade", "websocket") {
  102. return u.returnError(w, r, http.StatusBadRequest, "websocket: not a websocket handshake: 'websocket' token not found in 'Upgrade' header")
  103. }
  104. if !tokenListContainsValue(r.Header, "Sec-Websocket-Version", "13") {
  105. return u.returnError(w, r, http.StatusBadRequest, "websocket: unsupported version: 13 not found in 'Sec-Websocket-Version' header")
  106. }
  107. checkOrigin := u.CheckOrigin
  108. if checkOrigin == nil {
  109. checkOrigin = checkSameOrigin
  110. }
  111. if !checkOrigin(r) {
  112. return u.returnError(w, r, http.StatusForbidden, "websocket: 'Origin' header value not allowed")
  113. }
  114. challengeKey := r.Header.Get("Sec-Websocket-Key")
  115. if challengeKey == "" {
  116. return u.returnError(w, r, http.StatusBadRequest, "websocket: not a websocket handshake: `Sec-Websocket-Key' header is missing or blank")
  117. }
  118. subprotocol := u.selectSubprotocol(r, responseHeader)
  119. // Negotiate PMCE
  120. var compress bool
  121. if u.EnableCompression {
  122. for _, ext := range parseExtensions(r.Header) {
  123. if ext[""] != "permessage-deflate" {
  124. continue
  125. }
  126. compress = true
  127. break
  128. }
  129. }
  130. var (
  131. netConn net.Conn
  132. err error
  133. )
  134. h, ok := w.(http.Hijacker)
  135. if !ok {
  136. return u.returnError(w, r, http.StatusInternalServerError, "websocket: response does not implement http.Hijacker")
  137. }
  138. var brw *bufio.ReadWriter
  139. netConn, brw, err = h.Hijack()
  140. if err != nil {
  141. return u.returnError(w, r, http.StatusInternalServerError, err.Error())
  142. }
  143. if brw.Reader.Buffered() > 0 {
  144. netConn.Close()
  145. return nil, errors.New("websocket: client sent data before handshake is complete")
  146. }
  147. c := newConnBRW(netConn, true, u.ReadBufferSize, u.WriteBufferSize, brw)
  148. c.subprotocol = subprotocol
  149. if compress {
  150. c.newCompressionWriter = compressNoContextTakeover
  151. c.newDecompressionReader = decompressNoContextTakeover
  152. }
  153. p := c.writeBuf[:0]
  154. p = append(p, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: "...)
  155. p = append(p, computeAcceptKey(challengeKey)...)
  156. p = append(p, "\r\n"...)
  157. if c.subprotocol != "" {
  158. p = append(p, "Sec-Websocket-Protocol: "...)
  159. p = append(p, c.subprotocol...)
  160. p = append(p, "\r\n"...)
  161. }
  162. if compress {
  163. p = append(p, "Sec-Websocket-Extensions: permessage-deflate; server_no_context_takeover; client_no_context_takeover\r\n"...)
  164. }
  165. for k, vs := range responseHeader {
  166. if k == "Sec-Websocket-Protocol" {
  167. continue
  168. }
  169. for _, v := range vs {
  170. p = append(p, k...)
  171. p = append(p, ": "...)
  172. for i := 0; i < len(v); i++ {
  173. b := v[i]
  174. if b <= 31 {
  175. // prevent response splitting.
  176. b = ' '
  177. }
  178. p = append(p, b)
  179. }
  180. p = append(p, "\r\n"...)
  181. }
  182. }
  183. p = append(p, "\r\n"...)
  184. // Clear deadlines set by HTTP server.
  185. netConn.SetDeadline(time.Time{})
  186. if u.HandshakeTimeout > 0 {
  187. netConn.SetWriteDeadline(time.Now().Add(u.HandshakeTimeout))
  188. }
  189. if _, err = netConn.Write(p); err != nil {
  190. netConn.Close()
  191. return nil, err
  192. }
  193. if u.HandshakeTimeout > 0 {
  194. netConn.SetWriteDeadline(time.Time{})
  195. }
  196. return c, nil
  197. }
  198. // Upgrade upgrades the HTTP server connection to the WebSocket protocol.
  199. //
  200. // This function is deprecated, use websocket.Upgrader instead.
  201. //
  202. // The application is responsible for checking the request origin before
  203. // calling Upgrade. An example implementation of the same origin policy is:
  204. //
  205. // if req.Header.Get("Origin") != "http://"+req.Host {
  206. // http.Error(w, "Origin not allowed", 403)
  207. // return
  208. // }
  209. //
  210. // If the endpoint supports subprotocols, then the application is responsible
  211. // for negotiating the protocol used on the connection. Use the Subprotocols()
  212. // function to get the subprotocols requested by the client. Use the
  213. // Sec-Websocket-Protocol response header to specify the subprotocol selected
  214. // by the application.
  215. //
  216. // The responseHeader is included in the response to the client's upgrade
  217. // request. Use the responseHeader to specify cookies (Set-Cookie) and the
  218. // negotiated subprotocol (Sec-Websocket-Protocol).
  219. //
  220. // The connection buffers IO to the underlying network connection. The
  221. // readBufSize and writeBufSize parameters specify the size of the buffers to
  222. // use. Messages can be larger than the buffers.
  223. //
  224. // If the request is not a valid WebSocket handshake, then Upgrade returns an
  225. // error of type HandshakeError. Applications should handle this error by
  226. // replying to the client with an HTTP error response.
  227. func Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header, readBufSize, writeBufSize int) (*Conn, error) {
  228. u := Upgrader{ReadBufferSize: readBufSize, WriteBufferSize: writeBufSize}
  229. u.Error = func(w http.ResponseWriter, r *http.Request, status int, reason error) {
  230. // don't return errors to maintain backwards compatibility
  231. }
  232. u.CheckOrigin = func(r *http.Request) bool {
  233. // allow all connections by default
  234. return true
  235. }
  236. return u.Upgrade(w, r, responseHeader)
  237. }
  238. // Subprotocols returns the subprotocols requested by the client in the
  239. // Sec-Websocket-Protocol header.
  240. func Subprotocols(r *http.Request) []string {
  241. h := strings.TrimSpace(r.Header.Get("Sec-Websocket-Protocol"))
  242. if h == "" {
  243. return nil
  244. }
  245. protocols := strings.Split(h, ",")
  246. for i := range protocols {
  247. protocols[i] = strings.TrimSpace(protocols[i])
  248. }
  249. return protocols
  250. }
  251. // IsWebSocketUpgrade returns true if the client requested upgrade to the
  252. // WebSocket protocol.
  253. func IsWebSocketUpgrade(r *http.Request) bool {
  254. return tokenListContainsValue(r.Header, "Connection", "upgrade") &&
  255. tokenListContainsValue(r.Header, "Upgrade", "websocket")
  256. }