upgrader.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. // Copyright 2013 Gary Burd. All rights reserved.
  2. // Copyright 2014 Joachim Bauch. All rights reserved.
  3. // Use of this source code is governed by a BSD-style
  4. // license that can be found in the LICENSE file.
  5. package websocket
  6. import (
  7. "bufio"
  8. "errors"
  9. "net"
  10. "net/http"
  11. "time"
  12. )
  13. const (
  14. DEFAULT_READ_BUFFER_SIZE = 4096
  15. DEFAULT_WRITE_BUFFER_SIZE = 4096
  16. )
  17. type Upgrader struct {
  18. // HandshakeTimeout specifies the duration for the handshake to complete.
  19. HandshakeTimeout time.Duration
  20. // Input and output buffer sizes. If the buffer size is zero, then
  21. // default values will be used.
  22. ReadBufferSize, WriteBufferSize int
  23. // Subprotocols specifies the server's supported protocols. If Subprotocols
  24. // is nil, then Upgrade does not negotiate a subprotocol.
  25. Subprotocols []string
  26. // Error specifies the function for generating HTTP error responses. If Error
  27. // is nil, then http.Error is used to generate the HTTP response.
  28. Error func(w http.ResponseWriter, r *http.Request, status int, reason error)
  29. // CheckOrigin returns true if the request Origin header is acceptable.
  30. // If CheckOrigin is nil, then no origin check is done.
  31. CheckOrigin func(r *http.Request) bool
  32. }
  33. // Return an error depending on settings on the Upgrader
  34. func (u *Upgrader) returnError(w http.ResponseWriter, r *http.Request, status int, reason error) {
  35. if u.Error != nil {
  36. u.Error(w, r, status, reason)
  37. } else {
  38. http.Error(w, reason.Error(), status)
  39. }
  40. }
  41. // Check if the passed subprotocol is supported by the server
  42. func (u *Upgrader) hasSubprotocol(subprotocol string) bool {
  43. if u.Subprotocols == nil {
  44. return false
  45. }
  46. for _, s := range u.Subprotocols {
  47. if s == subprotocol {
  48. return true
  49. }
  50. }
  51. return false
  52. }
  53. // Upgrade upgrades the HTTP server connection to the WebSocket protocol.
  54. //
  55. // The responseHeader is included in the response to the client's upgrade
  56. // request. Use the responseHeader to specify cookies (Set-Cookie).
  57. //
  58. // The connection buffers IO to the underlying network connection.
  59. // Messages can be larger than the buffers.
  60. //
  61. // If the request is not a valid WebSocket handshake, then Upgrade returns an
  62. // error of type HandshakeError. Depending on settings on the Upgrader,
  63. // an error message already has been returned to the caller.
  64. func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header) (*Conn, error) {
  65. if values := r.Header["Sec-Websocket-Version"]; len(values) == 0 || values[0] != "13" {
  66. err := HandshakeError{"websocket: version != 13"}
  67. u.returnError(w, r, http.StatusBadRequest, err)
  68. return nil, err
  69. }
  70. if !tokenListContainsValue(r.Header, "Connection", "upgrade") {
  71. err := HandshakeError{"websocket: connection header != upgrade"}
  72. u.returnError(w, r, http.StatusBadRequest, err)
  73. return nil, err
  74. }
  75. if !tokenListContainsValue(r.Header, "Upgrade", "websocket") {
  76. err := HandshakeError{"websocket: upgrade != websocket"}
  77. u.returnError(w, r, http.StatusBadRequest, err)
  78. return nil, err
  79. }
  80. if u.CheckOrigin != nil && !u.CheckOrigin(r) {
  81. err := HandshakeError{"websocket: origin not allowed"}
  82. u.returnError(w, r, http.StatusForbidden, err)
  83. return nil, err
  84. }
  85. var challengeKey string
  86. values := r.Header["Sec-Websocket-Key"]
  87. if len(values) == 0 || values[0] == "" {
  88. err := HandshakeError{"websocket: key missing or blank"}
  89. u.returnError(w, r, http.StatusBadRequest, err)
  90. return nil, err
  91. }
  92. challengeKey = values[0]
  93. var (
  94. netConn net.Conn
  95. br *bufio.Reader
  96. err error
  97. )
  98. h, ok := w.(http.Hijacker)
  99. if !ok {
  100. return nil, errors.New("websocket: response does not implement http.Hijacker")
  101. }
  102. var rw *bufio.ReadWriter
  103. netConn, rw, err = h.Hijack()
  104. br = rw.Reader
  105. if br.Buffered() > 0 {
  106. netConn.Close()
  107. return nil, errors.New("websocket: client sent data before handshake is complete")
  108. }
  109. readBufSize := u.ReadBufferSize
  110. if readBufSize == 0 {
  111. readBufSize = DEFAULT_READ_BUFFER_SIZE
  112. }
  113. writeBufSize := u.WriteBufferSize
  114. if writeBufSize == 0 {
  115. writeBufSize = DEFAULT_WRITE_BUFFER_SIZE
  116. }
  117. c := newConn(netConn, true, readBufSize, writeBufSize)
  118. if u.Subprotocols != nil {
  119. for _, proto := range Subprotocols(r) {
  120. if u.hasSubprotocol(proto) {
  121. c.subprotocol = proto
  122. break
  123. }
  124. }
  125. } else if responseHeader != nil {
  126. c.subprotocol = responseHeader.Get("Sec-Websocket-Protocol")
  127. }
  128. p := c.writeBuf[:0]
  129. p = append(p, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: "...)
  130. p = append(p, computeAcceptKey(challengeKey)...)
  131. p = append(p, "\r\n"...)
  132. if c.subprotocol != "" {
  133. p = append(p, "Sec-Websocket-Protocol: "...)
  134. p = append(p, c.subprotocol...)
  135. p = append(p, "\r\n"...)
  136. }
  137. for k, vs := range responseHeader {
  138. if k == "Sec-Websocket-Protocol" {
  139. continue
  140. }
  141. for _, v := range vs {
  142. p = append(p, k...)
  143. p = append(p, ": "...)
  144. for i := 0; i < len(v); i++ {
  145. b := v[i]
  146. if b <= 31 {
  147. // prevent response splitting.
  148. b = ' '
  149. }
  150. p = append(p, b)
  151. }
  152. p = append(p, "\r\n"...)
  153. }
  154. }
  155. p = append(p, "\r\n"...)
  156. if u.HandshakeTimeout > 0 {
  157. netConn.SetWriteDeadline(time.Now().Add(u.HandshakeTimeout))
  158. }
  159. if _, err = netConn.Write(p); err != nil {
  160. netConn.Close()
  161. return nil, err
  162. }
  163. return c, nil
  164. }