server.go 7.9 KB

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