http urls monitor.

server.go 12KB

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