websocket.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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. if err != nil {
  178. return n, err
  179. }
  180. return n, err
  181. }
  182. // Close implements the io.Closer interface.
  183. func (ws *Conn) Close() error {
  184. err := ws.frameHandler.WriteClose(ws.defaultCloseStatus)
  185. err1 := ws.rwc.Close()
  186. if err != nil {
  187. return err
  188. }
  189. return err1
  190. }
  191. func (ws *Conn) IsClientConn() bool { return ws.request == nil }
  192. func (ws *Conn) IsServerConn() bool { return ws.request != nil }
  193. // LocalAddr returns the WebSocket Origin for the connection for client, or
  194. // the WebSocket location for server.
  195. func (ws *Conn) LocalAddr() net.Addr {
  196. if ws.IsClientConn() {
  197. return &Addr{ws.config.Origin}
  198. }
  199. return &Addr{ws.config.Location}
  200. }
  201. // RemoteAddr returns the WebSocket location for the connection for client, or
  202. // the Websocket Origin for server.
  203. func (ws *Conn) RemoteAddr() net.Addr {
  204. if ws.IsClientConn() {
  205. return &Addr{ws.config.Location}
  206. }
  207. return &Addr{ws.config.Origin}
  208. }
  209. var errSetDeadline = errors.New("websocket: cannot set deadline: not using a net.Conn")
  210. // SetDeadline sets the connection's network read & write deadlines.
  211. func (ws *Conn) SetDeadline(t time.Time) error {
  212. if conn, ok := ws.rwc.(net.Conn); ok {
  213. return conn.SetDeadline(t)
  214. }
  215. return errSetDeadline
  216. }
  217. // SetReadDeadline sets the connection's network read deadline.
  218. func (ws *Conn) SetReadDeadline(t time.Time) error {
  219. if conn, ok := ws.rwc.(net.Conn); ok {
  220. return conn.SetReadDeadline(t)
  221. }
  222. return errSetDeadline
  223. }
  224. // SetWriteDeadline sets the connection's network write deadline.
  225. func (ws *Conn) SetWriteDeadline(t time.Time) error {
  226. if conn, ok := ws.rwc.(net.Conn); ok {
  227. return conn.SetWriteDeadline(t)
  228. }
  229. return errSetDeadline
  230. }
  231. // Config returns the WebSocket config.
  232. func (ws *Conn) Config() *Config { return ws.config }
  233. // Request returns the http request upgraded to the WebSocket.
  234. // It is nil for client side.
  235. func (ws *Conn) Request() *http.Request { return ws.request }
  236. // Codec represents a symmetric pair of functions that implement a codec.
  237. type Codec struct {
  238. Marshal func(v interface{}) (data []byte, payloadType byte, err error)
  239. Unmarshal func(data []byte, payloadType byte, v interface{}) (err error)
  240. }
  241. // Send sends v marshaled by cd.Marshal as single frame to ws.
  242. func (cd Codec) Send(ws *Conn, v interface{}) (err error) {
  243. data, payloadType, err := cd.Marshal(v)
  244. if err != nil {
  245. return err
  246. }
  247. ws.wio.Lock()
  248. defer ws.wio.Unlock()
  249. w, err := ws.frameWriterFactory.NewFrameWriter(payloadType)
  250. if err != nil {
  251. return err
  252. }
  253. _, err = w.Write(data)
  254. w.Close()
  255. return err
  256. }
  257. // Receive receives single frame from ws, unmarshaled by cd.Unmarshal and stores in v.
  258. func (cd Codec) Receive(ws *Conn, v interface{}) (err error) {
  259. ws.rio.Lock()
  260. defer ws.rio.Unlock()
  261. if ws.frameReader != nil {
  262. _, err = io.Copy(ioutil.Discard, ws.frameReader)
  263. if err != nil {
  264. return err
  265. }
  266. ws.frameReader = nil
  267. }
  268. again:
  269. frame, err := ws.frameReaderFactory.NewFrameReader()
  270. if err != nil {
  271. return err
  272. }
  273. frame, err = ws.frameHandler.HandleFrame(frame)
  274. if err != nil {
  275. return err
  276. }
  277. if frame == nil {
  278. goto again
  279. }
  280. payloadType := frame.PayloadType()
  281. data, err := ioutil.ReadAll(frame)
  282. if err != nil {
  283. return err
  284. }
  285. return cd.Unmarshal(data, payloadType, v)
  286. }
  287. func marshal(v interface{}) (msg []byte, payloadType byte, err error) {
  288. switch data := v.(type) {
  289. case string:
  290. return []byte(data), TextFrame, nil
  291. case []byte:
  292. return data, BinaryFrame, nil
  293. }
  294. return nil, UnknownFrame, ErrNotSupported
  295. }
  296. func unmarshal(msg []byte, payloadType byte, v interface{}) (err error) {
  297. switch data := v.(type) {
  298. case *string:
  299. *data = string(msg)
  300. return nil
  301. case *[]byte:
  302. *data = msg
  303. return nil
  304. }
  305. return ErrNotSupported
  306. }
  307. /*
  308. Message is a codec to send/receive text/binary data in a frame on WebSocket connection.
  309. To send/receive text frame, use string type.
  310. To send/receive binary frame, use []byte type.
  311. Trivial usage:
  312. import "websocket"
  313. // receive text frame
  314. var message string
  315. websocket.Message.Receive(ws, &message)
  316. // send text frame
  317. message = "hello"
  318. websocket.Message.Send(ws, message)
  319. // receive binary frame
  320. var data []byte
  321. websocket.Message.Receive(ws, &data)
  322. // send binary frame
  323. data = []byte{0, 1, 2}
  324. websocket.Message.Send(ws, data)
  325. */
  326. var Message = Codec{marshal, unmarshal}
  327. func jsonMarshal(v interface{}) (msg []byte, payloadType byte, err error) {
  328. msg, err = json.Marshal(v)
  329. return msg, TextFrame, err
  330. }
  331. func jsonUnmarshal(msg []byte, payloadType byte, v interface{}) (err error) {
  332. return json.Unmarshal(msg, v)
  333. }
  334. /*
  335. JSON is a codec to send/receive JSON data in a frame from a WebSocket connection.
  336. Trivial usage:
  337. import "websocket"
  338. type T struct {
  339. Msg string
  340. Count int
  341. }
  342. // receive JSON type T
  343. var data T
  344. websocket.JSON.Receive(ws, &data)
  345. // send JSON type T
  346. websocket.JSON.Send(ws, data)
  347. */
  348. var JSON = Codec{jsonMarshal, jsonUnmarshal}