另客网go项目公用的代码库

server.go 9.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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. "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. // 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. // Subprotocols specifies the server's supported protocols in order of
  30. // preference. If this field is set, then the Upgrade method negotiates a
  31. // subprotocol by selecting the first match in this list with a protocol
  32. // requested by the client.
  33. Subprotocols []string
  34. // Error specifies the function for generating HTTP error responses. If Error
  35. // is nil, then http.Error is used to generate the HTTP response.
  36. Error func(w http.ResponseWriter, r *http.Request, status int, reason error)
  37. // CheckOrigin returns true if the request Origin header is acceptable. If
  38. // CheckOrigin is nil, the host in the Origin header must not be set or
  39. // must match the host of the request.
  40. CheckOrigin func(r *http.Request) bool
  41. // EnableCompression specify if the server should attempt to negotiate per
  42. // message compression (RFC 7692). Setting this value to true does not
  43. // guarantee that compression will be supported. Currently only "no context
  44. // takeover" modes are supported.
  45. EnableCompression bool
  46. }
  47. func (u *Upgrader) returnError(w http.ResponseWriter, r *http.Request, status int, reason string) (*Conn, error) {
  48. err := HandshakeError{reason}
  49. if u.Error != nil {
  50. u.Error(w, r, status, err)
  51. } else {
  52. w.Header().Set("Sec-Websocket-Version", "13")
  53. http.Error(w, http.StatusText(status), status)
  54. }
  55. return nil, err
  56. }
  57. // checkSameOrigin returns true if the origin is not set or is equal to the request host.
  58. func checkSameOrigin(r *http.Request) bool {
  59. origin := r.Header["Origin"]
  60. if len(origin) == 0 {
  61. return true
  62. }
  63. u, err := url.Parse(origin[0])
  64. if err != nil {
  65. return false
  66. }
  67. return u.Host == r.Host
  68. }
  69. func (u *Upgrader) selectSubprotocol(r *http.Request, responseHeader http.Header) string {
  70. if u.Subprotocols != nil {
  71. clientProtocols := Subprotocols(r)
  72. for _, serverProtocol := range u.Subprotocols {
  73. for _, clientProtocol := range clientProtocols {
  74. if clientProtocol == serverProtocol {
  75. return clientProtocol
  76. }
  77. }
  78. }
  79. } else if responseHeader != nil {
  80. return responseHeader.Get("Sec-Websocket-Protocol")
  81. }
  82. return ""
  83. }
  84. // Upgrade upgrades the HTTP server connection to the WebSocket protocol.
  85. //
  86. // The responseHeader is included in the response to the client's upgrade
  87. // request. Use the responseHeader to specify cookies (Set-Cookie) and the
  88. // application negotiated subprotocol (Sec-Websocket-Protocol).
  89. //
  90. // If the upgrade fails, then Upgrade replies to the client with an HTTP error
  91. // response.
  92. func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header) (*Conn, error) {
  93. if r.Method != "GET" {
  94. return u.returnError(w, r, http.StatusMethodNotAllowed, "websocket: not a websocket handshake: request method is not GET")
  95. }
  96. if _, ok := responseHeader["Sec-Websocket-Extensions"]; ok {
  97. return u.returnError(w, r, http.StatusInternalServerError, "websocket: application specific 'Sec-Websocket-Extensions' headers are unsupported")
  98. }
  99. if !tokenListContainsValue(r.Header, "Connection", "upgrade") {
  100. return u.returnError(w, r, http.StatusBadRequest, "websocket: not a websocket handshake: 'upgrade' token not found in 'Connection' header")
  101. }
  102. if !tokenListContainsValue(r.Header, "Upgrade", "websocket") {
  103. return u.returnError(w, r, http.StatusBadRequest, "websocket: not a websocket handshake: 'websocket' token not found in 'Upgrade' header")
  104. }
  105. if !tokenListContainsValue(r.Header, "Sec-Websocket-Version", "13") {
  106. return u.returnError(w, r, http.StatusBadRequest, "websocket: unsupported version: 13 not found in 'Sec-Websocket-Version' header")
  107. }
  108. checkOrigin := u.CheckOrigin
  109. if checkOrigin == nil {
  110. checkOrigin = checkSameOrigin
  111. }
  112. if !checkOrigin(r) {
  113. return u.returnError(w, r, http.StatusForbidden, "websocket: 'Origin' header value not allowed")
  114. }
  115. challengeKey := r.Header.Get("Sec-Websocket-Key")
  116. if challengeKey == "" {
  117. return u.returnError(w, r, http.StatusBadRequest, "websocket: not a websocket handshake: `Sec-Websocket-Key' header is missing or blank")
  118. }
  119. subprotocol := u.selectSubprotocol(r, responseHeader)
  120. // Negotiate PMCE
  121. var compress bool
  122. if u.EnableCompression {
  123. for _, ext := range parseExtensions(r.Header) {
  124. if ext[""] != "permessage-deflate" {
  125. continue
  126. }
  127. compress = true
  128. break
  129. }
  130. }
  131. var (
  132. netConn net.Conn
  133. err error
  134. )
  135. h, ok := w.(http.Hijacker)
  136. if !ok {
  137. return u.returnError(w, r, http.StatusInternalServerError, "websocket: response does not implement http.Hijacker")
  138. }
  139. var brw *bufio.ReadWriter
  140. netConn, brw, err = h.Hijack()
  141. if err != nil {
  142. return u.returnError(w, r, http.StatusInternalServerError, err.Error())
  143. }
  144. if brw.Reader.Buffered() > 0 {
  145. netConn.Close()
  146. return nil, errors.New("websocket: client sent data before handshake is complete")
  147. }
  148. c := newConnBRW(netConn, true, u.ReadBufferSize, u.WriteBufferSize, brw)
  149. c.subprotocol = subprotocol
  150. if compress {
  151. c.newCompressionWriter = compressNoContextTakeover
  152. c.newDecompressionReader = decompressNoContextTakeover
  153. }
  154. p := c.writeBuf[:0]
  155. p = append(p, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: "...)
  156. p = append(p, computeAcceptKey(challengeKey)...)
  157. p = append(p, "\r\n"...)
  158. if c.subprotocol != "" {
  159. p = append(p, "Sec-Websocket-Protocol: "...)
  160. p = append(p, c.subprotocol...)
  161. p = append(p, "\r\n"...)
  162. }
  163. if compress {
  164. p = append(p, "Sec-Websocket-Extensions: permessage-deflate; server_no_context_takeover; client_no_context_takeover\r\n"...)
  165. }
  166. for k, vs := range responseHeader {
  167. if k == "Sec-Websocket-Protocol" {
  168. continue
  169. }
  170. for _, v := range vs {
  171. p = append(p, k...)
  172. p = append(p, ": "...)
  173. for i := 0; i < len(v); i++ {
  174. b := v[i]
  175. if b <= 31 {
  176. // prevent response splitting.
  177. b = ' '
  178. }
  179. p = append(p, b)
  180. }
  181. p = append(p, "\r\n"...)
  182. }
  183. }
  184. p = append(p, "\r\n"...)
  185. // Clear deadlines set by HTTP server.
  186. netConn.SetDeadline(time.Time{})
  187. if u.HandshakeTimeout > 0 {
  188. netConn.SetWriteDeadline(time.Now().Add(u.HandshakeTimeout))
  189. }
  190. if _, err = netConn.Write(p); err != nil {
  191. netConn.Close()
  192. return nil, err
  193. }
  194. if u.HandshakeTimeout > 0 {
  195. netConn.SetWriteDeadline(time.Time{})
  196. }
  197. return c, nil
  198. }
  199. // Upgrade upgrades the HTTP server connection to the WebSocket protocol.
  200. //
  201. // This function is deprecated, use websocket.Upgrader instead.
  202. //
  203. // The application is responsible for checking the request origin before
  204. // calling Upgrade. An example implementation of the same origin policy is:
  205. //
  206. // if req.Header.Get("Origin") != "http://"+req.Host {
  207. // http.Error(w, "Origin not allowed", 403)
  208. // return
  209. // }
  210. //
  211. // If the endpoint supports subprotocols, then the application is responsible
  212. // for negotiating the protocol used on the connection. Use the Subprotocols()
  213. // function to get the subprotocols requested by the client. Use the
  214. // Sec-Websocket-Protocol response header to specify the subprotocol selected
  215. // by the application.
  216. //
  217. // The responseHeader is included in the response to the client's upgrade
  218. // request. Use the responseHeader to specify cookies (Set-Cookie) and the
  219. // negotiated subprotocol (Sec-Websocket-Protocol).
  220. //
  221. // The connection buffers IO to the underlying network connection. The
  222. // readBufSize and writeBufSize parameters specify the size of the buffers to
  223. // use. Messages can be larger than the buffers.
  224. //
  225. // If the request is not a valid WebSocket handshake, then Upgrade returns an
  226. // error of type HandshakeError. Applications should handle this error by
  227. // replying to the client with an HTTP error response.
  228. func Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header, readBufSize, writeBufSize int) (*Conn, error) {
  229. u := Upgrader{ReadBufferSize: readBufSize, WriteBufferSize: writeBufSize}
  230. u.Error = func(w http.ResponseWriter, r *http.Request, status int, reason error) {
  231. // don't return errors to maintain backwards compatibility
  232. }
  233. u.CheckOrigin = func(r *http.Request) bool {
  234. // allow all connections by default
  235. return true
  236. }
  237. return u.Upgrade(w, r, responseHeader)
  238. }
  239. // Subprotocols returns the subprotocols requested by the client in the
  240. // Sec-Websocket-Protocol header.
  241. func Subprotocols(r *http.Request) []string {
  242. h := strings.TrimSpace(r.Header.Get("Sec-Websocket-Protocol"))
  243. if h == "" {
  244. return nil
  245. }
  246. protocols := strings.Split(h, ",")
  247. for i := range protocols {
  248. protocols[i] = strings.TrimSpace(protocols[i])
  249. }
  250. return protocols
  251. }
  252. // IsWebSocketUpgrade returns true if the client requested upgrade to the
  253. // WebSocket protocol.
  254. func IsWebSocketUpgrade(r *http.Request) bool {
  255. return tokenListContainsValue(r.Header, "Connection", "upgrade") &&
  256. tokenListContainsValue(r.Header, "Upgrade", "websocket")
  257. }