server.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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. "io"
  9. "net"
  10. "net/http"
  11. "net/url"
  12. "strings"
  13. "time"
  14. )
  15. // HandshakeError describes an error with the handshake from the peer.
  16. type HandshakeError struct {
  17. message string
  18. }
  19. func (e HandshakeError) Error() string { return e.message }
  20. // Upgrader specifies parameters for upgrading an HTTP connection to a
  21. // WebSocket connection.
  22. type Upgrader struct {
  23. // HandshakeTimeout specifies the duration for the handshake to complete.
  24. HandshakeTimeout time.Duration
  25. // ReadBufferSize and WriteBufferSize specify I/O buffer sizes. If a buffer
  26. // size is zero, then buffers allocated by the HTTP server are used. The
  27. // I/O buffer sizes do not limit the size of the messages that can be sent
  28. // or received.
  29. ReadBufferSize, WriteBufferSize int
  30. // WriteBufferPool is a pool of buffers for write operations. If the value
  31. // is not set, then write buffers are allocated to the connection for the
  32. // lifetime of the connection.
  33. //
  34. // A pool is most useful when the application has a modest volume of writes
  35. // across a large number of connections.
  36. //
  37. // Applications should use a single pool for each unique value of
  38. // WriteBufferSize.
  39. WriteBufferPool BufferPool
  40. // Subprotocols specifies the server's supported protocols in order of
  41. // preference. If this field is not nil, then the Upgrade method negotiates a
  42. // subprotocol by selecting the first match in this list with a protocol
  43. // requested by the client. If there's no match, then no protocol is
  44. // negotiated (the Sec-Websocket-Protocol header is not included in the
  45. // handshake response).
  46. Subprotocols []string
  47. // Error specifies the function for generating HTTP error responses. If Error
  48. // is nil, then http.Error is used to generate the HTTP response.
  49. Error func(w http.ResponseWriter, r *http.Request, status int, reason error)
  50. // CheckOrigin returns true if the request Origin header is acceptable. If
  51. // CheckOrigin is nil, then a safe default is used: return false if the
  52. // Origin request header is present and the origin host is not equal to
  53. // request Host header.
  54. //
  55. // A CheckOrigin function should carefully validate the request origin to
  56. // prevent cross-site request forgery.
  57. CheckOrigin func(r *http.Request) bool
  58. // EnableCompression specify if the server should attempt to negotiate per
  59. // message compression (RFC 7692). Setting this value to true does not
  60. // guarantee that compression will be supported. Currently only "no context
  61. // takeover" modes are supported.
  62. EnableCompression bool
  63. }
  64. func (u *Upgrader) returnError(w http.ResponseWriter, r *http.Request, status int, reason string) (*Conn, error) {
  65. err := HandshakeError{reason}
  66. if u.Error != nil {
  67. u.Error(w, r, status, err)
  68. } else {
  69. w.Header().Set("Sec-Websocket-Version", "13")
  70. http.Error(w, http.StatusText(status), status)
  71. }
  72. return nil, err
  73. }
  74. // checkSameOrigin returns true if the origin is not set or is equal to the request host.
  75. func checkSameOrigin(r *http.Request) bool {
  76. origin := r.Header["Origin"]
  77. if len(origin) == 0 {
  78. return true
  79. }
  80. u, err := url.Parse(origin[0])
  81. if err != nil {
  82. return false
  83. }
  84. return equalASCIIFold(u.Host, r.Host)
  85. }
  86. func (u *Upgrader) selectSubprotocol(r *http.Request, responseHeader http.Header) string {
  87. if u.Subprotocols != nil {
  88. clientProtocols := Subprotocols(r)
  89. for _, serverProtocol := range u.Subprotocols {
  90. for _, clientProtocol := range clientProtocols {
  91. if clientProtocol == serverProtocol {
  92. return clientProtocol
  93. }
  94. }
  95. }
  96. } else if responseHeader != nil {
  97. return responseHeader.Get("Sec-Websocket-Protocol")
  98. }
  99. return ""
  100. }
  101. // Upgrade upgrades the HTTP server connection to the WebSocket protocol.
  102. //
  103. // The responseHeader is included in the response to the client's upgrade
  104. // request. Use the responseHeader to specify cookies (Set-Cookie) and the
  105. // application negotiated subprotocol (Sec-WebSocket-Protocol).
  106. //
  107. // If the upgrade fails, then Upgrade replies to the client with an HTTP error
  108. // response.
  109. func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header) (*Conn, error) {
  110. const badHandshake = "websocket: the client is not using the websocket protocol: "
  111. if !tokenListContainsValue(r.Header, "Connection", "upgrade") {
  112. return u.returnError(w, r, http.StatusBadRequest, badHandshake+"'upgrade' token not found in 'Connection' header")
  113. }
  114. if !tokenListContainsValue(r.Header, "Upgrade", "websocket") {
  115. return u.returnError(w, r, http.StatusBadRequest, badHandshake+"'websocket' token not found in 'Upgrade' header")
  116. }
  117. if r.Method != "GET" {
  118. return u.returnError(w, r, http.StatusMethodNotAllowed, badHandshake+"request method is not GET")
  119. }
  120. if !tokenListContainsValue(r.Header, "Sec-Websocket-Version", "13") {
  121. return u.returnError(w, r, http.StatusBadRequest, "websocket: unsupported version: 13 not found in 'Sec-Websocket-Version' header")
  122. }
  123. if _, ok := responseHeader["Sec-Websocket-Extensions"]; ok {
  124. return u.returnError(w, r, http.StatusInternalServerError, "websocket: application specific 'Sec-WebSocket-Extensions' headers are unsupported")
  125. }
  126. checkOrigin := u.CheckOrigin
  127. if checkOrigin == nil {
  128. checkOrigin = checkSameOrigin
  129. }
  130. if !checkOrigin(r) {
  131. return u.returnError(w, r, http.StatusForbidden, "websocket: request origin not allowed by Upgrader.CheckOrigin")
  132. }
  133. challengeKey := r.Header.Get("Sec-Websocket-Key")
  134. if challengeKey == "" {
  135. return u.returnError(w, r, http.StatusBadRequest, "websocket: not a websocket handshake: `Sec-WebSocket-Key' header is missing or blank")
  136. }
  137. subprotocol := u.selectSubprotocol(r, responseHeader)
  138. // Negotiate PMCE
  139. var compress bool
  140. if u.EnableCompression {
  141. for _, ext := range parseExtensions(r.Header) {
  142. if ext[""] != "permessage-deflate" {
  143. continue
  144. }
  145. compress = true
  146. break
  147. }
  148. }
  149. var (
  150. netConn net.Conn
  151. err error
  152. )
  153. h, ok := w.(http.Hijacker)
  154. if !ok {
  155. return u.returnError(w, r, http.StatusInternalServerError, "websocket: response does not implement http.Hijacker")
  156. }
  157. var brw *bufio.ReadWriter
  158. netConn, brw, err = h.Hijack()
  159. if err != nil {
  160. return u.returnError(w, r, http.StatusInternalServerError, err.Error())
  161. }
  162. if brw.Reader.Buffered() > 0 {
  163. netConn.Close()
  164. return nil, errors.New("websocket: client sent data before handshake is complete")
  165. }
  166. var br *bufio.Reader
  167. if u.ReadBufferSize == 0 && bufioReaderSize(netConn, brw.Reader) > 256 {
  168. // Reuse hijacked buffered reader as connection reader.
  169. br = brw.Reader
  170. }
  171. buf := bufioWriterBuffer(netConn, brw.Writer)
  172. var writeBuf []byte
  173. if u.WriteBufferPool == nil && u.WriteBufferSize == 0 && len(buf) >= maxFrameHeaderSize+256 {
  174. // Reuse hijacked write buffer as connection buffer.
  175. writeBuf = buf
  176. }
  177. c := newConn(netConn, true, u.ReadBufferSize, u.WriteBufferSize, u.WriteBufferPool, br, writeBuf)
  178. c.subprotocol = subprotocol
  179. if compress {
  180. c.newCompressionWriter = compressNoContextTakeover
  181. c.newDecompressionReader = decompressNoContextTakeover
  182. }
  183. // Use larger of hijacked buffer and connection write buffer for header.
  184. p := buf
  185. if len(c.writeBuf) > len(p) {
  186. p = c.writeBuf
  187. }
  188. p = p[:0]
  189. p = append(p, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: "...)
  190. p = append(p, computeAcceptKey(challengeKey)...)
  191. p = append(p, "\r\n"...)
  192. if c.subprotocol != "" {
  193. p = append(p, "Sec-WebSocket-Protocol: "...)
  194. p = append(p, c.subprotocol...)
  195. p = append(p, "\r\n"...)
  196. }
  197. if compress {
  198. p = append(p, "Sec-WebSocket-Extensions: permessage-deflate; server_no_context_takeover; client_no_context_takeover\r\n"...)
  199. }
  200. for k, vs := range responseHeader {
  201. if k == "Sec-Websocket-Protocol" {
  202. continue
  203. }
  204. for _, v := range vs {
  205. p = append(p, k...)
  206. p = append(p, ": "...)
  207. for i := 0; i < len(v); i++ {
  208. b := v[i]
  209. if b <= 31 {
  210. // prevent response splitting.
  211. b = ' '
  212. }
  213. p = append(p, b)
  214. }
  215. p = append(p, "\r\n"...)
  216. }
  217. }
  218. p = append(p, "\r\n"...)
  219. // Clear deadlines set by HTTP server.
  220. netConn.SetDeadline(time.Time{})
  221. if u.HandshakeTimeout > 0 {
  222. netConn.SetWriteDeadline(time.Now().Add(u.HandshakeTimeout))
  223. }
  224. if _, err = netConn.Write(p); err != nil {
  225. netConn.Close()
  226. return nil, err
  227. }
  228. if u.HandshakeTimeout > 0 {
  229. netConn.SetWriteDeadline(time.Time{})
  230. }
  231. return c, nil
  232. }
  233. // Upgrade upgrades the HTTP server connection to the WebSocket protocol.
  234. //
  235. // Deprecated: Use websocket.Upgrader instead.
  236. //
  237. // Upgrade does not perform origin checking. The application is responsible for
  238. // checking the Origin header before calling Upgrade. An example implementation
  239. // of the same origin policy check is:
  240. //
  241. // if req.Header.Get("Origin") != "http://"+req.Host {
  242. // http.Error(w, "Origin not allowed", http.StatusForbidden)
  243. // return
  244. // }
  245. //
  246. // If the endpoint supports subprotocols, then the application is responsible
  247. // for negotiating the protocol used on the connection. Use the Subprotocols()
  248. // function to get the subprotocols requested by the client. Use the
  249. // Sec-Websocket-Protocol response header to specify the subprotocol selected
  250. // by the application.
  251. //
  252. // The responseHeader is included in the response to the client's upgrade
  253. // request. Use the responseHeader to specify cookies (Set-Cookie) and the
  254. // negotiated subprotocol (Sec-Websocket-Protocol).
  255. //
  256. // The connection buffers IO to the underlying network connection. The
  257. // readBufSize and writeBufSize parameters specify the size of the buffers to
  258. // use. Messages can be larger than the buffers.
  259. //
  260. // If the request is not a valid WebSocket handshake, then Upgrade returns an
  261. // error of type HandshakeError. Applications should handle this error by
  262. // replying to the client with an HTTP error response.
  263. func Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header, readBufSize, writeBufSize int) (*Conn, error) {
  264. u := Upgrader{ReadBufferSize: readBufSize, WriteBufferSize: writeBufSize}
  265. u.Error = func(w http.ResponseWriter, r *http.Request, status int, reason error) {
  266. // don't return errors to maintain backwards compatibility
  267. }
  268. u.CheckOrigin = func(r *http.Request) bool {
  269. // allow all connections by default
  270. return true
  271. }
  272. return u.Upgrade(w, r, responseHeader)
  273. }
  274. // Subprotocols returns the subprotocols requested by the client in the
  275. // Sec-Websocket-Protocol header.
  276. func Subprotocols(r *http.Request) []string {
  277. h := strings.TrimSpace(r.Header.Get("Sec-Websocket-Protocol"))
  278. if h == "" {
  279. return nil
  280. }
  281. protocols := strings.Split(h, ",")
  282. for i := range protocols {
  283. protocols[i] = strings.TrimSpace(protocols[i])
  284. }
  285. return protocols
  286. }
  287. // IsWebSocketUpgrade returns true if the client requested upgrade to the
  288. // WebSocket protocol.
  289. func IsWebSocketUpgrade(r *http.Request) bool {
  290. return tokenListContainsValue(r.Header, "Connection", "upgrade") &&
  291. tokenListContainsValue(r.Header, "Upgrade", "websocket")
  292. }
  293. // bufioReader size returns the size of a bufio.Reader.
  294. func bufioReaderSize(originalReader io.Reader, br *bufio.Reader) int {
  295. // This code assumes that peek on a reset reader returns
  296. // bufio.Reader.buf[:0].
  297. // TODO: Use bufio.Reader.Size() after Go 1.10
  298. br.Reset(originalReader)
  299. if p, err := br.Peek(0); err == nil {
  300. return cap(p)
  301. }
  302. return 0
  303. }
  304. // writeHook is an io.Writer that records the last slice passed to it vio
  305. // io.Writer.Write.
  306. type writeHook struct {
  307. p []byte
  308. }
  309. func (wh *writeHook) Write(p []byte) (int, error) {
  310. wh.p = p
  311. return len(p), nil
  312. }
  313. // bufioWriterBuffer grabs the buffer from a bufio.Writer.
  314. func bufioWriterBuffer(originalWriter io.Writer, bw *bufio.Writer) []byte {
  315. // This code assumes that bufio.Writer.buf[:1] is passed to the
  316. // bufio.Writer's underlying writer.
  317. var wh writeHook
  318. bw.Reset(&wh)
  319. bw.WriteByte(0)
  320. bw.Flush()
  321. bw.Reset(originalWriter)
  322. return wh.p[:cap(wh.p)]
  323. }