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