websocket.go 10 KB

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