websocket.go 10 KB

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