server.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. // Copyright 2013 Gary Burd. 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. "strings"
  11. )
  12. // HandshakeError describes an error with the handshake from the peer.
  13. type HandshakeError struct {
  14. message string
  15. }
  16. func (e HandshakeError) Error() string { return e.message }
  17. // Upgrade upgrades the HTTP server connection to the WebSocket protocol.
  18. //
  19. // The application is responsible for checking the request origin before
  20. // calling Upgrade. An example implementation of the same origin policy is:
  21. //
  22. // if req.Header.Get("Origin") != "http://"+req.Host {
  23. // http.Error(w, "Origin not allowed", 403)
  24. // return
  25. // }
  26. //
  27. // If the endpoint supports subprotocols, then the application is responsible
  28. // for negotiating the protocol used on the connection. Use the Subprotocols()
  29. // function to get the subprotocols requested by the client. Use the
  30. // Sec-Websocket-Protocol response header to specify the subprotocol selected
  31. // by the application.
  32. //
  33. // The responseHeader is included in the response to the client's upgrade
  34. // request. Use the responseHeader to specify cookies (Set-Cookie) and the
  35. // negotiated subprotocol (Sec-Websocket-Protocol).
  36. //
  37. // The connection buffers IO to the underlying network connection. The
  38. // readBufSize and writeBufSize parameters specify the size of the buffers to
  39. // use. Messages can be larger than the buffers.
  40. //
  41. // If the request is not a valid WebSocket handshake, then Upgrade returns an
  42. // error of type HandshakeError. Applications should handle this error by
  43. // replying to the client with an HTTP error response.
  44. func Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header, readBufSize, writeBufSize int) (*Conn, error) {
  45. if values := r.Header["Sec-Websocket-Version"]; len(values) == 0 || values[0] != "13" {
  46. return nil, HandshakeError{"websocket: version != 13"}
  47. }
  48. if !tokenListContainsValue(r.Header, "Connection", "upgrade") {
  49. return nil, HandshakeError{"websocket: connection header != upgrade"}
  50. }
  51. if !tokenListContainsValue(r.Header, "Upgrade", "websocket") {
  52. return nil, HandshakeError{"websocket: upgrade != websocket"}
  53. }
  54. var challengeKey string
  55. values := r.Header["Sec-Websocket-Key"]
  56. if len(values) == 0 || values[0] == "" {
  57. return nil, HandshakeError{"websocket: key missing or blank"}
  58. }
  59. challengeKey = values[0]
  60. var (
  61. netConn net.Conn
  62. br *bufio.Reader
  63. err error
  64. )
  65. h, ok := w.(http.Hijacker)
  66. if !ok {
  67. return nil, errors.New("websocket: response does not implement http.Hijacker")
  68. }
  69. var rw *bufio.ReadWriter
  70. netConn, rw, err = h.Hijack()
  71. br = rw.Reader
  72. if br.Buffered() > 0 {
  73. netConn.Close()
  74. return nil, errors.New("websocket: client sent data before handshake is complete")
  75. }
  76. c := newConn(netConn, true, readBufSize, writeBufSize)
  77. if responseHeader != nil {
  78. c.subprotocol = responseHeader.Get("Sec-Websocket-Protocol")
  79. }
  80. p := c.writeBuf[:0]
  81. p = append(p, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: "...)
  82. p = append(p, computeAcceptKey(challengeKey)...)
  83. p = append(p, "\r\n"...)
  84. for k, vs := range responseHeader {
  85. for _, v := range vs {
  86. p = append(p, k...)
  87. p = append(p, ": "...)
  88. for i := 0; i < len(v); i++ {
  89. b := v[i]
  90. if b <= 31 {
  91. // prevent response splitting.
  92. b = ' '
  93. }
  94. p = append(p, b)
  95. }
  96. p = append(p, "\r\n"...)
  97. }
  98. }
  99. p = append(p, "\r\n"...)
  100. if _, err = netConn.Write(p); err != nil {
  101. netConn.Close()
  102. return nil, err
  103. }
  104. return c, nil
  105. }
  106. // Subprotocols returns the subprotocols requested by the client in the
  107. // Sec-Websocket-Protocol header.
  108. func Subprotocols(r *http.Request) []string {
  109. h := strings.TrimSpace(r.Header.Get("Sec-Websocket-Protocol"))
  110. if h == "" {
  111. return nil
  112. }
  113. protocols := strings.Split(h, ",")
  114. for i := range protocols {
  115. protocols[i] = strings.TrimSpace(protocols[i])
  116. }
  117. return protocols
  118. }