server.go 8.0 KB

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