websocket.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. // Copyright 2009 The Go 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 implements a client and server for the WebSocket protocol
  5. // as specified in RFC 6455.
  6. package websocket // import "golang.org/x/net/websocket"
  7. import (
  8. "bufio"
  9. "crypto/tls"
  10. "encoding/json"
  11. "errors"
  12. "io"
  13. "io/ioutil"
  14. "net"
  15. "net/http"
  16. "net/url"
  17. "sync"
  18. "time"
  19. )
  20. const (
  21. ProtocolVersionHybi13 = 13
  22. ProtocolVersionHybi = ProtocolVersionHybi13
  23. SupportedProtocolVersion = "13"
  24. ContinuationFrame = 0
  25. TextFrame = 1
  26. BinaryFrame = 2
  27. CloseFrame = 8
  28. PingFrame = 9
  29. PongFrame = 10
  30. UnknownFrame = 255
  31. )
  32. // ProtocolError represents WebSocket protocol errors.
  33. type ProtocolError struct {
  34. ErrorString string
  35. }
  36. func (err *ProtocolError) Error() string { return err.ErrorString }
  37. var (
  38. ErrBadProtocolVersion = &ProtocolError{"bad protocol version"}
  39. ErrBadScheme = &ProtocolError{"bad scheme"}
  40. ErrBadStatus = &ProtocolError{"bad status"}
  41. ErrBadUpgrade = &ProtocolError{"missing or bad upgrade"}
  42. ErrBadWebSocketOrigin = &ProtocolError{"missing or bad WebSocket-Origin"}
  43. ErrBadWebSocketLocation = &ProtocolError{"missing or bad WebSocket-Location"}
  44. ErrBadWebSocketProtocol = &ProtocolError{"missing or bad WebSocket-Protocol"}
  45. ErrBadWebSocketVersion = &ProtocolError{"missing or bad WebSocket Version"}
  46. ErrChallengeResponse = &ProtocolError{"mismatch challenge/response"}
  47. ErrBadFrame = &ProtocolError{"bad frame"}
  48. ErrBadFrameBoundary = &ProtocolError{"not on frame boundary"}
  49. ErrNotWebSocket = &ProtocolError{"not websocket protocol"}
  50. ErrBadRequestMethod = &ProtocolError{"bad method"}
  51. ErrNotSupported = &ProtocolError{"not supported"}
  52. )
  53. // Addr is an implementation of net.Addr for WebSocket.
  54. type Addr struct {
  55. *url.URL
  56. }
  57. // Network returns the network type for a WebSocket, "websocket".
  58. func (addr *Addr) Network() string { return "websocket" }
  59. // Config is a WebSocket configuration
  60. type Config struct {
  61. // A WebSocket server address.
  62. Location *url.URL
  63. // A Websocket client origin.
  64. Origin *url.URL
  65. // WebSocket subprotocols.
  66. Protocol []string
  67. // WebSocket protocol version.
  68. Version int
  69. // TLS config for secure WebSocket (wss).
  70. TlsConfig *tls.Config
  71. // Additional header fields to be sent in WebSocket opening handshake.
  72. Header http.Header
  73. handshakeData map[string]string
  74. }
  75. // serverHandshaker is an interface to handle WebSocket server side handshake.
  76. type serverHandshaker interface {
  77. // ReadHandshake reads handshake request message from client.
  78. // Returns http response code and error if any.
  79. ReadHandshake(buf *bufio.Reader, req *http.Request) (code int, err error)
  80. // AcceptHandshake accepts the client handshake request and sends
  81. // handshake response back to client.
  82. AcceptHandshake(buf *bufio.Writer) (err error)
  83. // NewServerConn creates a new WebSocket connection.
  84. NewServerConn(buf *bufio.ReadWriter, rwc io.ReadWriteCloser, request *http.Request) (conn *Conn)
  85. }
  86. // frameReader is an interface to read a WebSocket frame.
  87. type frameReader interface {
  88. // Reader is to read payload of the frame.
  89. io.Reader
  90. // PayloadType returns payload type.
  91. PayloadType() byte
  92. // HeaderReader returns a reader to read header of the frame.
  93. HeaderReader() io.Reader
  94. // TrailerReader returns a reader to read trailer of the frame.
  95. // If it returns nil, there is no trailer in the frame.
  96. TrailerReader() io.Reader
  97. // Len returns total length of the frame, including header and trailer.
  98. Len() int
  99. }
  100. // frameReaderFactory is an interface to creates new frame reader.
  101. type frameReaderFactory interface {
  102. NewFrameReader() (r frameReader, err error)
  103. }
  104. // frameWriter is an interface to write a WebSocket frame.
  105. type frameWriter interface {
  106. // Writer is to write payload of the frame.
  107. io.WriteCloser
  108. }
  109. // frameWriterFactory is an interface to create new frame writer.
  110. type frameWriterFactory interface {
  111. NewFrameWriter(payloadType byte) (w frameWriter, err error)
  112. }
  113. type frameHandler interface {
  114. HandleFrame(frame frameReader) (r frameReader, err error)
  115. WriteClose(status int) (err error)
  116. }
  117. // Conn represents a WebSocket connection.
  118. //
  119. // Multiple goroutines may invoke methods on a Conn simultaneously.
  120. type Conn struct {
  121. config *Config
  122. request *http.Request
  123. buf *bufio.ReadWriter
  124. rwc io.ReadWriteCloser
  125. rio sync.Mutex
  126. frameReaderFactory
  127. frameReader
  128. wio sync.Mutex
  129. frameWriterFactory
  130. frameHandler
  131. PayloadType byte
  132. defaultCloseStatus int
  133. }
  134. // Read implements the io.Reader interface:
  135. // it reads data of a frame from the WebSocket connection.
  136. // if msg is not large enough for the frame data, it fills the msg and next Read
  137. // will read the rest of the frame data.
  138. // it reads Text frame or Binary frame.
  139. func (ws *Conn) Read(msg []byte) (n int, err error) {
  140. ws.rio.Lock()
  141. defer ws.rio.Unlock()
  142. again:
  143. if ws.frameReader == nil {
  144. frame, err := ws.frameReaderFactory.NewFrameReader()
  145. if err != nil {
  146. return 0, err
  147. }
  148. ws.frameReader, err = ws.frameHandler.HandleFrame(frame)
  149. if err != nil {
  150. return 0, err
  151. }
  152. if ws.frameReader == nil {
  153. goto again
  154. }
  155. }
  156. n, err = ws.frameReader.Read(msg)
  157. if err == io.EOF {
  158. if trailer := ws.frameReader.TrailerReader(); trailer != nil {
  159. io.Copy(ioutil.Discard, trailer)
  160. }
  161. ws.frameReader = nil
  162. goto again
  163. }
  164. return n, err
  165. }
  166. // Write implements the io.Writer interface:
  167. // it writes data as a frame to the WebSocket connection.
  168. func (ws *Conn) Write(msg []byte) (n int, err error) {
  169. ws.wio.Lock()
  170. defer ws.wio.Unlock()
  171. w, err := ws.frameWriterFactory.NewFrameWriter(ws.PayloadType)
  172. if err != nil {
  173. return 0, err
  174. }
  175. n, err = w.Write(msg)
  176. w.Close()
  177. return n, err
  178. }
  179. // Close implements the io.Closer interface.
  180. func (ws *Conn) Close() error {
  181. err := ws.frameHandler.WriteClose(ws.defaultCloseStatus)
  182. err1 := ws.rwc.Close()
  183. if err != nil {
  184. return err
  185. }
  186. return err1
  187. }
  188. func (ws *Conn) IsClientConn() bool { return ws.request == nil }
  189. func (ws *Conn) IsServerConn() bool { return ws.request != nil }
  190. // LocalAddr returns the WebSocket Origin for the connection for client, or
  191. // the WebSocket location for server.
  192. func (ws *Conn) LocalAddr() net.Addr {
  193. if ws.IsClientConn() {
  194. return &Addr{ws.config.Origin}
  195. }
  196. return &Addr{ws.config.Location}
  197. }
  198. // RemoteAddr returns the WebSocket location for the connection for client, or
  199. // the Websocket Origin for server.
  200. func (ws *Conn) RemoteAddr() net.Addr {
  201. if ws.IsClientConn() {
  202. return &Addr{ws.config.Location}
  203. }
  204. return &Addr{ws.config.Origin}
  205. }
  206. var errSetDeadline = errors.New("websocket: cannot set deadline: not using a net.Conn")
  207. // SetDeadline sets the connection's network read & write deadlines.
  208. func (ws *Conn) SetDeadline(t time.Time) error {
  209. if conn, ok := ws.rwc.(net.Conn); ok {
  210. return conn.SetDeadline(t)
  211. }
  212. return errSetDeadline
  213. }
  214. // SetReadDeadline sets the connection's network read deadline.
  215. func (ws *Conn) SetReadDeadline(t time.Time) error {
  216. if conn, ok := ws.rwc.(net.Conn); ok {
  217. return conn.SetReadDeadline(t)
  218. }
  219. return errSetDeadline
  220. }
  221. // SetWriteDeadline sets the connection's network write deadline.
  222. func (ws *Conn) SetWriteDeadline(t time.Time) error {
  223. if conn, ok := ws.rwc.(net.Conn); ok {
  224. return conn.SetWriteDeadline(t)
  225. }
  226. return errSetDeadline
  227. }
  228. // Config returns the WebSocket config.
  229. func (ws *Conn) Config() *Config { return ws.config }
  230. // Request returns the http request upgraded to the WebSocket.
  231. // It is nil for client side.
  232. func (ws *Conn) Request() *http.Request { return ws.request }
  233. // Codec represents a symmetric pair of functions that implement a codec.
  234. type Codec struct {
  235. Marshal func(v interface{}) (data []byte, payloadType byte, err error)
  236. Unmarshal func(data []byte, payloadType byte, v interface{}) (err error)
  237. }
  238. // Send sends v marshaled by cd.Marshal as single frame to ws.
  239. func (cd Codec) Send(ws *Conn, v interface{}) (err error) {
  240. data, payloadType, err := cd.Marshal(v)
  241. if err != nil {
  242. return err
  243. }
  244. ws.wio.Lock()
  245. defer ws.wio.Unlock()
  246. w, err := ws.frameWriterFactory.NewFrameWriter(payloadType)
  247. if err != nil {
  248. return err
  249. }
  250. _, err = w.Write(data)
  251. w.Close()
  252. return err
  253. }
  254. // Receive receives single frame from ws, unmarshaled by cd.Unmarshal and stores in v.
  255. func (cd Codec) Receive(ws *Conn, v interface{}) (err error) {
  256. ws.rio.Lock()
  257. defer ws.rio.Unlock()
  258. if ws.frameReader != nil {
  259. _, err = io.Copy(ioutil.Discard, ws.frameReader)
  260. if err != nil {
  261. return err
  262. }
  263. ws.frameReader = nil
  264. }
  265. again:
  266. frame, err := ws.frameReaderFactory.NewFrameReader()
  267. if err != nil {
  268. return err
  269. }
  270. frame, err = ws.frameHandler.HandleFrame(frame)
  271. if err != nil {
  272. return err
  273. }
  274. if frame == nil {
  275. goto again
  276. }
  277. payloadType := frame.PayloadType()
  278. data, err := ioutil.ReadAll(frame)
  279. if err != nil {
  280. return err
  281. }
  282. return cd.Unmarshal(data, payloadType, v)
  283. }
  284. func marshal(v interface{}) (msg []byte, payloadType byte, err error) {
  285. switch data := v.(type) {
  286. case string:
  287. return []byte(data), TextFrame, nil
  288. case []byte:
  289. return data, BinaryFrame, nil
  290. }
  291. return nil, UnknownFrame, ErrNotSupported
  292. }
  293. func unmarshal(msg []byte, payloadType byte, v interface{}) (err error) {
  294. switch data := v.(type) {
  295. case *string:
  296. *data = string(msg)
  297. return nil
  298. case *[]byte:
  299. *data = msg
  300. return nil
  301. }
  302. return ErrNotSupported
  303. }
  304. /*
  305. Message is a codec to send/receive text/binary data in a frame on WebSocket connection.
  306. To send/receive text frame, use string type.
  307. To send/receive binary frame, use []byte type.
  308. Trivial usage:
  309. import "websocket"
  310. // receive text frame
  311. var message string
  312. websocket.Message.Receive(ws, &message)
  313. // send text frame
  314. message = "hello"
  315. websocket.Message.Send(ws, message)
  316. // receive binary frame
  317. var data []byte
  318. websocket.Message.Receive(ws, &data)
  319. // send binary frame
  320. data = []byte{0, 1, 2}
  321. websocket.Message.Send(ws, data)
  322. */
  323. var Message = Codec{marshal, unmarshal}
  324. func jsonMarshal(v interface{}) (msg []byte, payloadType byte, err error) {
  325. msg, err = json.Marshal(v)
  326. return msg, TextFrame, err
  327. }
  328. func jsonUnmarshal(msg []byte, payloadType byte, v interface{}) (err error) {
  329. return json.Unmarshal(msg, v)
  330. }
  331. /*
  332. JSON is a codec to send/receive JSON data in a frame from a WebSocket connection.
  333. Trivial usage:
  334. import "websocket"
  335. type T struct {
  336. Msg string
  337. Count int
  338. }
  339. // receive JSON type T
  340. var data T
  341. websocket.JSON.Receive(ws, &data)
  342. // send JSON type T
  343. websocket.JSON.Send(ws, data)
  344. */
  345. var JSON = Codec{jsonMarshal, jsonUnmarshal}