server.go 7.5 KB

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