server.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  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 WebSocket subprotocols, then the application is
  28. // responsible for selecting a subprotocol that is acceptable to the client and
  29. // echoing that value back to the client. Use the Subprotocols function to get
  30. // the list of protocols specified by the client. Use the
  31. // Sec-Websocket-Protocol response header to echo the selected protocol back to
  32. // the client.
  33. //
  34. // Appilcations can set cookies by adding a Set-Cookie header to the response
  35. // header.
  36. //
  37. // If the request is not a valid WebSocket handshake, then Upgrade returns an
  38. // error of type HandshakeError. Applications should handle this error by
  39. // replying to the client with an HTTP error response.
  40. func Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header, readBufSize, writeBufSize int) (*Conn, error) {
  41. if values := r.Header["Sec-Websocket-Version"]; len(values) == 0 || values[0] != "13" {
  42. return nil, HandshakeError{"websocket: version != 13"}
  43. }
  44. if !tokenListContainsValue(r.Header, "Connection", "upgrade") {
  45. return nil, HandshakeError{"websocket: connection header != upgrade"}
  46. }
  47. if !tokenListContainsValue(r.Header, "Upgrade", "websocket") {
  48. return nil, HandshakeError{"websocket: upgrade != websocket"}
  49. }
  50. var challengeKey string
  51. values := r.Header["Sec-Websocket-Key"]
  52. if len(values) == 0 || values[0] == "" {
  53. return nil, HandshakeError{"websocket: key missing or blank"}
  54. }
  55. challengeKey = values[0]
  56. var (
  57. netConn net.Conn
  58. br *bufio.Reader
  59. err error
  60. )
  61. h, ok := w.(http.Hijacker)
  62. if !ok {
  63. return nil, errors.New("websocket: response does not implement http.Hijacker")
  64. }
  65. var rw *bufio.ReadWriter
  66. netConn, rw, err = h.Hijack()
  67. br = rw.Reader
  68. if br.Buffered() > 0 {
  69. netConn.Close()
  70. return nil, errors.New("websocket: client sent data before handshake is complete")
  71. }
  72. c := newConn(netConn, true, readBufSize, writeBufSize)
  73. if responseHeader != nil {
  74. c.subprotocol = responseHeader.Get("Sec-Websocket-Protocol")
  75. }
  76. p := c.writeBuf[:0]
  77. p = append(p, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: "...)
  78. p = append(p, computeAcceptKey(challengeKey)...)
  79. p = append(p, "\r\n"...)
  80. for k, vs := range responseHeader {
  81. for _, v := range vs {
  82. p = append(p, k...)
  83. p = append(p, ": "...)
  84. for i := 0; i < len(v); i++ {
  85. b := v[i]
  86. if b <= 31 {
  87. // prevent response splitting.
  88. b = ' '
  89. }
  90. p = append(p, b)
  91. }
  92. p = append(p, "\r\n"...)
  93. }
  94. }
  95. p = append(p, "\r\n"...)
  96. if _, err = netConn.Write(p); err != nil {
  97. netConn.Close()
  98. return nil, err
  99. }
  100. return c, nil
  101. }
  102. // Subprotocols returns the subprotocols requested by the client in the
  103. // Sec-Websocket-Protocol header.
  104. func Subprotocols(r *http.Request) []string {
  105. h := strings.TrimSpace(r.Header.Get("Sec-Websocket-Protocol"))
  106. if h == "" {
  107. return nil
  108. }
  109. protocols := strings.Split(h, ",")
  110. for i := range protocols {
  111. protocols[i] = strings.TrimSpace(protocols[i])
  112. }
  113. return protocols
  114. }