server.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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. "log"
  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. //
  23. // It is safe to call Upgrader's methods concurrently.
  24. type Upgrader struct {
  25. // HandshakeTimeout specifies the duration for the handshake to complete.
  26. HandshakeTimeout time.Duration
  27. // ReadBufferSize and WriteBufferSize specify I/O buffer sizes in bytes. If a buffer
  28. // size is zero, then buffers allocated by the HTTP server are used. The
  29. // I/O buffer sizes do not limit the size of the messages that can be sent
  30. // or received.
  31. ReadBufferSize, WriteBufferSize int
  32. // WriteBufferPool is a pool of buffers for write operations. If the value
  33. // is not set, then write buffers are allocated to the connection for the
  34. // lifetime of the connection.
  35. //
  36. // A pool is most useful when the application has a modest volume of writes
  37. // across a large number of connections.
  38. //
  39. // Applications should use a single pool for each unique value of
  40. // WriteBufferSize.
  41. WriteBufferPool BufferPool
  42. // Subprotocols specifies the server's supported protocols in order of
  43. // preference. If this field is not nil, then the Upgrade method negotiates a
  44. // subprotocol by selecting the first match in this list with a protocol
  45. // requested by the client. If there's no match, then no protocol is
  46. // negotiated (the Sec-Websocket-Protocol header is not included in the
  47. // handshake response).
  48. Subprotocols []string
  49. // Error specifies the function for generating HTTP error responses. If Error
  50. // is nil, then http.Error is used to generate the HTTP response.
  51. Error func(w http.ResponseWriter, r *http.Request, status int, reason error)
  52. // CheckOrigin returns true if the request Origin header is acceptable. If
  53. // CheckOrigin is nil, then a safe default is used: return false if the
  54. // Origin request header is present and the origin host is not equal to
  55. // request Host header.
  56. //
  57. // A CheckOrigin function should carefully validate the request origin to
  58. // prevent cross-site request forgery.
  59. CheckOrigin func(r *http.Request) bool
  60. // EnableCompression specify if the server should attempt to negotiate per
  61. // message compression (RFC 7692). Setting this value to true does not
  62. // guarantee that compression will be supported. Currently only "no context
  63. // takeover" modes are supported.
  64. EnableCompression bool
  65. }
  66. func (u *Upgrader) returnError(w http.ResponseWriter, r *http.Request, status int, reason string) (*Conn, error) {
  67. err := HandshakeError{reason}
  68. if u.Error != nil {
  69. u.Error(w, r, status, err)
  70. } else {
  71. w.Header().Set("Sec-Websocket-Version", "13")
  72. http.Error(w, http.StatusText(status), status)
  73. }
  74. return nil, err
  75. }
  76. // checkSameOrigin returns true if the origin is not set or is equal to the request host.
  77. func checkSameOrigin(r *http.Request) bool {
  78. origin := r.Header["Origin"]
  79. if len(origin) == 0 {
  80. return true
  81. }
  82. u, err := url.Parse(origin[0])
  83. if err != nil {
  84. return false
  85. }
  86. return equalASCIIFold(u.Host, r.Host)
  87. }
  88. func (u *Upgrader) selectSubprotocol(r *http.Request, responseHeader http.Header) string {
  89. if u.Subprotocols != nil {
  90. clientProtocols := Subprotocols(r)
  91. for _, serverProtocol := range u.Subprotocols {
  92. for _, clientProtocol := range clientProtocols {
  93. if clientProtocol == serverProtocol {
  94. return clientProtocol
  95. }
  96. }
  97. }
  98. } else if responseHeader != nil {
  99. return responseHeader.Get("Sec-Websocket-Protocol")
  100. }
  101. return ""
  102. }
  103. // Upgrade upgrades the HTTP server connection to the WebSocket protocol.
  104. //
  105. // The responseHeader is included in the response to the client's upgrade
  106. // request. Use the responseHeader to specify cookies (Set-Cookie). To specify
  107. // subprotocols supported by the server, set Upgrader.Subprotocols directly.
  108. //
  109. // If the upgrade fails, then Upgrade replies to the client with an HTTP error
  110. // response.
  111. func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header) (*Conn, error) {
  112. const badHandshake = "websocket: the client is not using the websocket protocol: "
  113. if !tokenListContainsValue(r.Header, "Connection", "upgrade") {
  114. return u.returnError(w, r, http.StatusBadRequest, badHandshake+"'upgrade' token not found in 'Connection' header")
  115. }
  116. if !tokenListContainsValue(r.Header, "Upgrade", "websocket") {
  117. return u.returnError(w, r, http.StatusBadRequest, badHandshake+"'websocket' token not found in 'Upgrade' header")
  118. }
  119. if r.Method != http.MethodGet {
  120. return u.returnError(w, r, http.StatusMethodNotAllowed, badHandshake+"request method is not GET")
  121. }
  122. if !tokenListContainsValue(r.Header, "Sec-Websocket-Version", "13") {
  123. return u.returnError(w, r, http.StatusBadRequest, "websocket: unsupported version: 13 not found in 'Sec-Websocket-Version' header")
  124. }
  125. if _, ok := responseHeader["Sec-Websocket-Extensions"]; ok {
  126. return u.returnError(w, r, http.StatusInternalServerError, "websocket: application specific 'Sec-WebSocket-Extensions' headers are unsupported")
  127. }
  128. checkOrigin := u.CheckOrigin
  129. if checkOrigin == nil {
  130. checkOrigin = checkSameOrigin
  131. }
  132. if !checkOrigin(r) {
  133. return u.returnError(w, r, http.StatusForbidden, "websocket: request origin not allowed by Upgrader.CheckOrigin")
  134. }
  135. challengeKey := r.Header.Get("Sec-Websocket-Key")
  136. if !isValidChallengeKey(challengeKey) {
  137. return u.returnError(w, r, http.StatusBadRequest, "websocket: not a websocket handshake: 'Sec-WebSocket-Key' header must be Base64 encoded value of 16-byte in length")
  138. }
  139. subprotocol := u.selectSubprotocol(r, responseHeader)
  140. // Negotiate PMCE
  141. var compress bool
  142. if u.EnableCompression {
  143. for _, ext := range parseExtensions(r.Header) {
  144. if ext[""] != "permessage-deflate" {
  145. continue
  146. }
  147. compress = true
  148. break
  149. }
  150. }
  151. h, ok := w.(http.Hijacker)
  152. if !ok {
  153. return u.returnError(w, r, http.StatusInternalServerError, "websocket: response does not implement http.Hijacker")
  154. }
  155. var brw *bufio.ReadWriter
  156. netConn, brw, err := h.Hijack()
  157. if err != nil {
  158. return u.returnError(w, r, http.StatusInternalServerError, err.Error())
  159. }
  160. if brw.Reader.Buffered() > 0 {
  161. if err := netConn.Close(); err != nil {
  162. log.Printf("websocket: failed to close network connection: %v", err)
  163. }
  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. if err := netConn.SetDeadline(time.Time{}); err != nil {
  221. if err := netConn.Close(); err != nil {
  222. log.Printf("websocket: failed to close network connection: %v", err)
  223. }
  224. return nil, err
  225. }
  226. if u.HandshakeTimeout > 0 {
  227. if err := netConn.SetWriteDeadline(time.Now().Add(u.HandshakeTimeout)); err != nil {
  228. if err := netConn.Close(); err != nil {
  229. log.Printf("websocket: failed to close network connection: %v", err)
  230. }
  231. return nil, err
  232. }
  233. }
  234. if _, err = netConn.Write(p); err != nil {
  235. if err := netConn.Close(); err != nil {
  236. log.Printf("websocket: failed to close network connection: %v", err)
  237. }
  238. return nil, err
  239. }
  240. if u.HandshakeTimeout > 0 {
  241. if err := netConn.SetWriteDeadline(time.Time{}); err != nil {
  242. if err := netConn.Close(); err != nil {
  243. log.Printf("websocket: failed to close network connection: %v", err)
  244. }
  245. return nil, err
  246. }
  247. }
  248. return c, nil
  249. }
  250. // Upgrade upgrades the HTTP server connection to the WebSocket protocol.
  251. //
  252. // Deprecated: Use websocket.Upgrader instead.
  253. //
  254. // Upgrade does not perform origin checking. The application is responsible for
  255. // checking the Origin header before calling Upgrade. An example implementation
  256. // of the same origin policy check is:
  257. //
  258. // if req.Header.Get("Origin") != "http://"+req.Host {
  259. // http.Error(w, "Origin not allowed", http.StatusForbidden)
  260. // return
  261. // }
  262. //
  263. // If the endpoint supports subprotocols, then the application is responsible
  264. // for negotiating the protocol used on the connection. Use the Subprotocols()
  265. // function to get the subprotocols requested by the client. Use the
  266. // Sec-Websocket-Protocol response header to specify the subprotocol selected
  267. // by the application.
  268. //
  269. // The responseHeader is included in the response to the client's upgrade
  270. // request. Use the responseHeader to specify cookies (Set-Cookie) and the
  271. // negotiated subprotocol (Sec-Websocket-Protocol).
  272. //
  273. // The connection buffers IO to the underlying network connection. The
  274. // readBufSize and writeBufSize parameters specify the size of the buffers to
  275. // use. Messages can be larger than the buffers.
  276. //
  277. // If the request is not a valid WebSocket handshake, then Upgrade returns an
  278. // error of type HandshakeError. Applications should handle this error by
  279. // replying to the client with an HTTP error response.
  280. func Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header, readBufSize, writeBufSize int) (*Conn, error) {
  281. u := Upgrader{ReadBufferSize: readBufSize, WriteBufferSize: writeBufSize}
  282. u.Error = func(w http.ResponseWriter, r *http.Request, status int, reason error) {
  283. // don't return errors to maintain backwards compatibility
  284. }
  285. u.CheckOrigin = func(r *http.Request) bool {
  286. // allow all connections by default
  287. return true
  288. }
  289. return u.Upgrade(w, r, responseHeader)
  290. }
  291. // Subprotocols returns the subprotocols requested by the client in the
  292. // Sec-Websocket-Protocol header.
  293. func Subprotocols(r *http.Request) []string {
  294. h := strings.TrimSpace(r.Header.Get("Sec-Websocket-Protocol"))
  295. if h == "" {
  296. return nil
  297. }
  298. protocols := strings.Split(h, ",")
  299. for i := range protocols {
  300. protocols[i] = strings.TrimSpace(protocols[i])
  301. }
  302. return protocols
  303. }
  304. // IsWebSocketUpgrade returns true if the client requested upgrade to the
  305. // WebSocket protocol.
  306. func IsWebSocketUpgrade(r *http.Request) bool {
  307. return tokenListContainsValue(r.Header, "Connection", "upgrade") &&
  308. tokenListContainsValue(r.Header, "Upgrade", "websocket")
  309. }
  310. // bufioReaderSize size returns the size of a bufio.Reader.
  311. func bufioReaderSize(originalReader io.Reader, br *bufio.Reader) int {
  312. // This code assumes that peek on a reset reader returns
  313. // bufio.Reader.buf[:0].
  314. // TODO: Use bufio.Reader.Size() after Go 1.10
  315. br.Reset(originalReader)
  316. if p, err := br.Peek(0); err == nil {
  317. return cap(p)
  318. }
  319. return 0
  320. }
  321. // writeHook is an io.Writer that records the last slice passed to it vio
  322. // io.Writer.Write.
  323. type writeHook struct {
  324. p []byte
  325. }
  326. func (wh *writeHook) Write(p []byte) (int, error) {
  327. wh.p = p
  328. return len(p), nil
  329. }
  330. // bufioWriterBuffer grabs the buffer from a bufio.Writer.
  331. func bufioWriterBuffer(originalWriter io.Writer, bw *bufio.Writer) []byte {
  332. // This code assumes that bufio.Writer.buf[:1] is passed to the
  333. // bufio.Writer's underlying writer.
  334. var wh writeHook
  335. bw.Reset(&wh)
  336. if err := bw.WriteByte(0); err != nil {
  337. panic(err)
  338. }
  339. if err := bw.Flush(); err != nil {
  340. log.Printf("websocket: bufioWriterBuffer: Flush: %v", err)
  341. }
  342. bw.Reset(originalWriter)
  343. return wh.p[:cap(wh.p)]
  344. }