server.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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. }
  41. func (u *Upgrader) returnError(w http.ResponseWriter, r *http.Request, status int, reason string) (*Conn, error) {
  42. err := HandshakeError{reason}
  43. if u.Error != nil {
  44. u.Error(w, r, status, err)
  45. } else {
  46. w.Header().Set("Sec-Websocket-Version", "13")
  47. http.Error(w, http.StatusText(status), status)
  48. }
  49. return nil, err
  50. }
  51. // checkSameOrigin returns true if the origin is not set or is equal to the request host.
  52. func checkSameOrigin(r *http.Request) bool {
  53. origin := r.Header["Origin"]
  54. if len(origin) == 0 {
  55. return true
  56. }
  57. u, err := url.Parse(origin[0])
  58. if err != nil {
  59. return false
  60. }
  61. return u.Host == r.Host
  62. }
  63. func (u *Upgrader) selectSubprotocol(r *http.Request, responseHeader http.Header) string {
  64. if u.Subprotocols != nil {
  65. clientProtocols := Subprotocols(r)
  66. for _, serverProtocol := range u.Subprotocols {
  67. for _, clientProtocol := range clientProtocols {
  68. if clientProtocol == serverProtocol {
  69. return clientProtocol
  70. }
  71. }
  72. }
  73. } else if responseHeader != nil {
  74. return responseHeader.Get("Sec-Websocket-Protocol")
  75. }
  76. return ""
  77. }
  78. // Upgrade upgrades the HTTP server connection to the WebSocket protocol.
  79. //
  80. // The responseHeader is included in the response to the client's upgrade
  81. // request. Use the responseHeader to specify cookies (Set-Cookie) and the
  82. // application negotiated subprotocol (Sec-Websocket-Protocol).
  83. //
  84. // If the upgrade fails, then Upgrade replies to the client with an HTTP error
  85. // response.
  86. func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header) (*Conn, error) {
  87. if r.Method != "GET" {
  88. return u.returnError(w, r, http.StatusMethodNotAllowed, "websocket: method not GET")
  89. }
  90. if !tokenListContainsValue(r.Header, "Sec-Websocket-Version", "13") {
  91. return u.returnError(w, r, http.StatusBadRequest, "websocket: version != 13")
  92. }
  93. if !tokenListContainsValue(r.Header, "Connection", "upgrade") {
  94. return u.returnError(w, r, http.StatusBadRequest, "websocket: could not find connection header with token 'upgrade'")
  95. }
  96. if !tokenListContainsValue(r.Header, "Upgrade", "websocket") {
  97. return u.returnError(w, r, http.StatusBadRequest, "websocket: could not find upgrade header with token 'websocket'")
  98. }
  99. checkOrigin := u.CheckOrigin
  100. if checkOrigin == nil {
  101. checkOrigin = checkSameOrigin
  102. }
  103. if !checkOrigin(r) {
  104. return u.returnError(w, r, http.StatusForbidden, "websocket: origin not allowed")
  105. }
  106. challengeKey := r.Header.Get("Sec-Websocket-Key")
  107. if challengeKey == "" {
  108. return u.returnError(w, r, http.StatusBadRequest, "websocket: key missing or blank")
  109. }
  110. subprotocol := u.selectSubprotocol(r, responseHeader)
  111. var (
  112. netConn net.Conn
  113. br *bufio.Reader
  114. err error
  115. )
  116. h, ok := w.(http.Hijacker)
  117. if !ok {
  118. return u.returnError(w, r, http.StatusInternalServerError, "websocket: response does not implement http.Hijacker")
  119. }
  120. var rw *bufio.ReadWriter
  121. netConn, rw, err = h.Hijack()
  122. if err != nil {
  123. return u.returnError(w, r, http.StatusInternalServerError, err.Error())
  124. }
  125. br = rw.Reader
  126. if br.Buffered() > 0 {
  127. netConn.Close()
  128. return nil, errors.New("websocket: client sent data before handshake is complete")
  129. }
  130. c := newConn(netConn, true, u.ReadBufferSize, u.WriteBufferSize)
  131. c.subprotocol = subprotocol
  132. p := c.writeBuf[:0]
  133. p = append(p, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: "...)
  134. p = append(p, computeAcceptKey(challengeKey)...)
  135. p = append(p, "\r\n"...)
  136. if c.subprotocol != "" {
  137. p = append(p, "Sec-Websocket-Protocol: "...)
  138. p = append(p, c.subprotocol...)
  139. p = append(p, "\r\n"...)
  140. }
  141. for k, vs := range responseHeader {
  142. if k == "Sec-Websocket-Protocol" {
  143. continue
  144. }
  145. for _, v := range vs {
  146. p = append(p, k...)
  147. p = append(p, ": "...)
  148. for i := 0; i < len(v); i++ {
  149. b := v[i]
  150. if b <= 31 {
  151. // prevent response splitting.
  152. b = ' '
  153. }
  154. p = append(p, b)
  155. }
  156. p = append(p, "\r\n"...)
  157. }
  158. }
  159. p = append(p, "\r\n"...)
  160. // Clear deadlines set by HTTP server.
  161. netConn.SetDeadline(time.Time{})
  162. if u.HandshakeTimeout > 0 {
  163. netConn.SetWriteDeadline(time.Now().Add(u.HandshakeTimeout))
  164. }
  165. if _, err = netConn.Write(p); err != nil {
  166. netConn.Close()
  167. return nil, err
  168. }
  169. if u.HandshakeTimeout > 0 {
  170. netConn.SetWriteDeadline(time.Time{})
  171. }
  172. return c, nil
  173. }
  174. // Upgrade upgrades the HTTP server connection to the WebSocket protocol.
  175. //
  176. // This function is deprecated, use websocket.Upgrader instead.
  177. //
  178. // The application is responsible for checking the request origin before
  179. // calling Upgrade. An example implementation of the same origin policy is:
  180. //
  181. // if req.Header.Get("Origin") != "http://"+req.Host {
  182. // http.Error(w, "Origin not allowed", 403)
  183. // return
  184. // }
  185. //
  186. // If the endpoint supports subprotocols, then the application is responsible
  187. // for negotiating the protocol used on the connection. Use the Subprotocols()
  188. // function to get the subprotocols requested by the client. Use the
  189. // Sec-Websocket-Protocol response header to specify the subprotocol selected
  190. // by the application.
  191. //
  192. // The responseHeader is included in the response to the client's upgrade
  193. // request. Use the responseHeader to specify cookies (Set-Cookie) and the
  194. // negotiated subprotocol (Sec-Websocket-Protocol).
  195. //
  196. // The connection buffers IO to the underlying network connection. The
  197. // readBufSize and writeBufSize parameters specify the size of the buffers to
  198. // use. Messages can be larger than the buffers.
  199. //
  200. // If the request is not a valid WebSocket handshake, then Upgrade returns an
  201. // error of type HandshakeError. Applications should handle this error by
  202. // replying to the client with an HTTP error response.
  203. func Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header, readBufSize, writeBufSize int) (*Conn, error) {
  204. u := Upgrader{ReadBufferSize: readBufSize, WriteBufferSize: writeBufSize}
  205. u.Error = func(w http.ResponseWriter, r *http.Request, status int, reason error) {
  206. // don't return errors to maintain backwards compatibility
  207. }
  208. u.CheckOrigin = func(r *http.Request) bool {
  209. // allow all connections by default
  210. return true
  211. }
  212. return u.Upgrade(w, r, responseHeader)
  213. }
  214. // Subprotocols returns the subprotocols requested by the client in the
  215. // Sec-Websocket-Protocol header.
  216. func Subprotocols(r *http.Request) []string {
  217. h := strings.TrimSpace(r.Header.Get("Sec-Websocket-Protocol"))
  218. if h == "" {
  219. return nil
  220. }
  221. protocols := strings.Split(h, ",")
  222. for i := range protocols {
  223. protocols[i] = strings.TrimSpace(protocols[i])
  224. }
  225. return protocols
  226. }
  227. // IsWebSocketUpgrade returns true if the client requested upgrade to the
  228. // WebSocket protocol.
  229. func IsWebSocketUpgrade(r *http.Request) bool {
  230. return tokenListContainsValue(r.Header, "Connection", "upgrade") &&
  231. tokenListContainsValue(r.Header, "Upgrade", "websocket")
  232. }