server.go 9.9 KB

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