server.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  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
  32. // to the client.
  33. //
  34. // Appilcations can set cookies by adding a Set-Cookie header to the
  35. // response 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. p := c.writeBuf[:0]
  74. p = append(p, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: "...)
  75. p = append(p, computeAcceptKey(challengeKey)...)
  76. p = append(p, "\r\n"...)
  77. for k, vs := range responseHeader {
  78. for _, v := range vs {
  79. p = append(p, k...)
  80. p = append(p, ": "...)
  81. for i := 0; i < len(v); i++ {
  82. b := v[i]
  83. if b <= 31 {
  84. // prevent response splitting.
  85. b = ' '
  86. }
  87. p = append(p, b)
  88. }
  89. p = append(p, "\r\n"...)
  90. }
  91. }
  92. p = append(p, "\r\n"...)
  93. if _, err = netConn.Write(p); err != nil {
  94. netConn.Close()
  95. return nil, err
  96. }
  97. return c, nil
  98. }
  99. // Subprotocols returns the subprotocols requested by the client in the
  100. // Sec-Websocket-Protocol header.
  101. func Subprotocols(r *http.Request) []string {
  102. h := strings.TrimSpace(r.Header.Get("Sec-Websocket-Protocol"))
  103. if h == "" {
  104. return nil
  105. }
  106. protocols := strings.Split(h, ",")
  107. for i := range protocols {
  108. protocols[i] = strings.TrimSpace(protocols[i])
  109. }
  110. return protocols
  111. }