websocket.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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. DefaultMaxPayloadBytes = 32 << 20 // 32MB
  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. // ErrFrameTooLarge is returned by Codec's Receive method if payload size
  55. // exceeds limit set by Conn.MaxPayloadBytes
  56. var ErrFrameTooLarge = errors.New("websocket: frame payload size exceeds limit")
  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. // Additional header fields to be sent in WebSocket opening handshake.
  76. Header http.Header
  77. // Dialer used when opening websocket connections.
  78. Dialer *net.Dialer
  79. handshakeData map[string]string
  80. }
  81. // serverHandshaker is an interface to handle WebSocket server side handshake.
  82. type serverHandshaker interface {
  83. // ReadHandshake reads handshake request message from client.
  84. // Returns http response code and error if any.
  85. ReadHandshake(buf *bufio.Reader, req *http.Request) (code int, err error)
  86. // AcceptHandshake accepts the client handshake request and sends
  87. // handshake response back to client.
  88. AcceptHandshake(buf *bufio.Writer) (err error)
  89. // NewServerConn creates a new WebSocket connection.
  90. NewServerConn(buf *bufio.ReadWriter, rwc io.ReadWriteCloser, request *http.Request) (conn *Conn)
  91. }
  92. // frameReader is an interface to read a WebSocket frame.
  93. type frameReader interface {
  94. // Reader is to read payload of the frame.
  95. io.Reader
  96. // PayloadType returns payload type.
  97. PayloadType() byte
  98. // HeaderReader returns a reader to read header of the frame.
  99. HeaderReader() io.Reader
  100. // TrailerReader returns a reader to read trailer of the frame.
  101. // If it returns nil, there is no trailer in the frame.
  102. TrailerReader() io.Reader
  103. // Len returns total length of the frame, including header and trailer.
  104. Len() int
  105. }
  106. // frameReaderFactory is an interface to creates new frame reader.
  107. type frameReaderFactory interface {
  108. NewFrameReader() (r frameReader, err error)
  109. }
  110. // frameWriter is an interface to write a WebSocket frame.
  111. type frameWriter interface {
  112. // Writer is to write payload of the frame.
  113. io.WriteCloser
  114. }
  115. // frameWriterFactory is an interface to create new frame writer.
  116. type frameWriterFactory interface {
  117. NewFrameWriter(payloadType byte) (w frameWriter, err error)
  118. }
  119. type frameHandler interface {
  120. HandleFrame(frame frameReader) (r frameReader, err error)
  121. WriteClose(status int) (err error)
  122. }
  123. // Conn represents a WebSocket connection.
  124. //
  125. // Multiple goroutines may invoke methods on a Conn simultaneously.
  126. type Conn struct {
  127. config *Config
  128. request *http.Request
  129. buf *bufio.ReadWriter
  130. rwc io.ReadWriteCloser
  131. rio sync.Mutex
  132. frameReaderFactory
  133. frameReader
  134. wio sync.Mutex
  135. frameWriterFactory
  136. frameHandler
  137. PayloadType byte
  138. defaultCloseStatus int
  139. // MaxPayloadBytes limits the size of frame payload received over Conn
  140. // by Codec's Receive method. If zero, DefaultMaxPayloadBytes is used.
  141. MaxPayloadBytes int
  142. }
  143. // Read implements the io.Reader interface:
  144. // it reads data of a frame from the WebSocket connection.
  145. // if msg is not large enough for the frame data, it fills the msg and next Read
  146. // will read the rest of the frame data.
  147. // it reads Text frame or Binary frame.
  148. func (ws *Conn) Read(msg []byte) (n int, err error) {
  149. ws.rio.Lock()
  150. defer ws.rio.Unlock()
  151. again:
  152. if ws.frameReader == nil {
  153. frame, err := ws.frameReaderFactory.NewFrameReader()
  154. if err != nil {
  155. return 0, err
  156. }
  157. ws.frameReader, err = ws.frameHandler.HandleFrame(frame)
  158. if err != nil {
  159. return 0, err
  160. }
  161. if ws.frameReader == nil {
  162. goto again
  163. }
  164. }
  165. n, err = ws.frameReader.Read(msg)
  166. if err == io.EOF {
  167. if trailer := ws.frameReader.TrailerReader(); trailer != nil {
  168. io.Copy(ioutil.Discard, trailer)
  169. }
  170. ws.frameReader = nil
  171. goto again
  172. }
  173. return n, err
  174. }
  175. // Write implements the io.Writer interface:
  176. // it writes data as a frame to the WebSocket connection.
  177. func (ws *Conn) Write(msg []byte) (n int, err error) {
  178. ws.wio.Lock()
  179. defer ws.wio.Unlock()
  180. w, err := ws.frameWriterFactory.NewFrameWriter(ws.PayloadType)
  181. if err != nil {
  182. return 0, err
  183. }
  184. n, err = w.Write(msg)
  185. w.Close()
  186. return n, err
  187. }
  188. // Close implements the io.Closer interface.
  189. func (ws *Conn) Close() error {
  190. err := ws.frameHandler.WriteClose(ws.defaultCloseStatus)
  191. err1 := ws.rwc.Close()
  192. if err != nil {
  193. return err
  194. }
  195. return err1
  196. }
  197. func (ws *Conn) IsClientConn() bool { return ws.request == nil }
  198. func (ws *Conn) IsServerConn() bool { return ws.request != nil }
  199. // LocalAddr returns the WebSocket Origin for the connection for client, or
  200. // the WebSocket location for server.
  201. func (ws *Conn) LocalAddr() net.Addr {
  202. if ws.IsClientConn() {
  203. return &Addr{ws.config.Origin}
  204. }
  205. return &Addr{ws.config.Location}
  206. }
  207. // RemoteAddr returns the WebSocket location for the connection for client, or
  208. // the Websocket Origin for server.
  209. func (ws *Conn) RemoteAddr() net.Addr {
  210. if ws.IsClientConn() {
  211. return &Addr{ws.config.Location}
  212. }
  213. return &Addr{ws.config.Origin}
  214. }
  215. var errSetDeadline = errors.New("websocket: cannot set deadline: not using a net.Conn")
  216. // SetDeadline sets the connection's network read & write deadlines.
  217. func (ws *Conn) SetDeadline(t time.Time) error {
  218. if conn, ok := ws.rwc.(net.Conn); ok {
  219. return conn.SetDeadline(t)
  220. }
  221. return errSetDeadline
  222. }
  223. // SetReadDeadline sets the connection's network read deadline.
  224. func (ws *Conn) SetReadDeadline(t time.Time) error {
  225. if conn, ok := ws.rwc.(net.Conn); ok {
  226. return conn.SetReadDeadline(t)
  227. }
  228. return errSetDeadline
  229. }
  230. // SetWriteDeadline sets the connection's network write deadline.
  231. func (ws *Conn) SetWriteDeadline(t time.Time) error {
  232. if conn, ok := ws.rwc.(net.Conn); ok {
  233. return conn.SetWriteDeadline(t)
  234. }
  235. return errSetDeadline
  236. }
  237. // Config returns the WebSocket config.
  238. func (ws *Conn) Config() *Config { return ws.config }
  239. // Request returns the http request upgraded to the WebSocket.
  240. // It is nil for client side.
  241. func (ws *Conn) Request() *http.Request { return ws.request }
  242. // Codec represents a symmetric pair of functions that implement a codec.
  243. type Codec struct {
  244. Marshal func(v interface{}) (data []byte, payloadType byte, err error)
  245. Unmarshal func(data []byte, payloadType byte, v interface{}) (err error)
  246. }
  247. // Send sends v marshaled by cd.Marshal as single frame to ws.
  248. func (cd Codec) Send(ws *Conn, v interface{}) (err error) {
  249. data, payloadType, err := cd.Marshal(v)
  250. if err != nil {
  251. return err
  252. }
  253. ws.wio.Lock()
  254. defer ws.wio.Unlock()
  255. w, err := ws.frameWriterFactory.NewFrameWriter(payloadType)
  256. if err != nil {
  257. return err
  258. }
  259. _, err = w.Write(data)
  260. w.Close()
  261. return err
  262. }
  263. // Receive receives single frame from ws, unmarshaled by cd.Unmarshal and stores
  264. // in v. The whole frame payload is read to an in-memory buffer; max size of
  265. // payload is defined by ws.MaxPayloadBytes. If frame payload size exceeds
  266. // limit, ErrFrameTooLarge is returned; in this case frame is not read off wire
  267. // completely. The next call to Receive would read and discard leftover data of
  268. // previous oversized frame before processing next frame.
  269. func (cd Codec) Receive(ws *Conn, v interface{}) (err error) {
  270. ws.rio.Lock()
  271. defer ws.rio.Unlock()
  272. if ws.frameReader != nil {
  273. _, err = io.Copy(ioutil.Discard, ws.frameReader)
  274. if err != nil {
  275. return err
  276. }
  277. ws.frameReader = nil
  278. }
  279. again:
  280. frame, err := ws.frameReaderFactory.NewFrameReader()
  281. if err != nil {
  282. return err
  283. }
  284. frame, err = ws.frameHandler.HandleFrame(frame)
  285. if err != nil {
  286. return err
  287. }
  288. if frame == nil {
  289. goto again
  290. }
  291. maxPayloadBytes := ws.MaxPayloadBytes
  292. if maxPayloadBytes == 0 {
  293. maxPayloadBytes = DefaultMaxPayloadBytes
  294. }
  295. if hf, ok := frame.(*hybiFrameReader); ok && hf.header.Length > int64(maxPayloadBytes) {
  296. // payload size exceeds limit, no need to call Unmarshal
  297. //
  298. // set frameReader to current oversized frame so that
  299. // the next call to this function can drain leftover
  300. // data before processing the next frame
  301. ws.frameReader = frame
  302. return ErrFrameTooLarge
  303. }
  304. payloadType := frame.PayloadType()
  305. data, err := ioutil.ReadAll(frame)
  306. if err != nil {
  307. return err
  308. }
  309. return cd.Unmarshal(data, payloadType, v)
  310. }
  311. func marshal(v interface{}) (msg []byte, payloadType byte, err error) {
  312. switch data := v.(type) {
  313. case string:
  314. return []byte(data), TextFrame, nil
  315. case []byte:
  316. return data, BinaryFrame, nil
  317. }
  318. return nil, UnknownFrame, ErrNotSupported
  319. }
  320. func unmarshal(msg []byte, payloadType byte, v interface{}) (err error) {
  321. switch data := v.(type) {
  322. case *string:
  323. *data = string(msg)
  324. return nil
  325. case *[]byte:
  326. *data = msg
  327. return nil
  328. }
  329. return ErrNotSupported
  330. }
  331. /*
  332. Message is a codec to send/receive text/binary data in a frame on WebSocket connection.
  333. To send/receive text frame, use string type.
  334. To send/receive binary frame, use []byte type.
  335. Trivial usage:
  336. import "websocket"
  337. // receive text frame
  338. var message string
  339. websocket.Message.Receive(ws, &message)
  340. // send text frame
  341. message = "hello"
  342. websocket.Message.Send(ws, message)
  343. // receive binary frame
  344. var data []byte
  345. websocket.Message.Receive(ws, &data)
  346. // send binary frame
  347. data = []byte{0, 1, 2}
  348. websocket.Message.Send(ws, data)
  349. */
  350. var Message = Codec{marshal, unmarshal}
  351. func jsonMarshal(v interface{}) (msg []byte, payloadType byte, err error) {
  352. msg, err = json.Marshal(v)
  353. return msg, TextFrame, err
  354. }
  355. func jsonUnmarshal(msg []byte, payloadType byte, v interface{}) (err error) {
  356. return json.Unmarshal(msg, v)
  357. }
  358. /*
  359. JSON is a codec to send/receive JSON data in a frame from a WebSocket connection.
  360. Trivial usage:
  361. import "websocket"
  362. type T struct {
  363. Msg string
  364. Count int
  365. }
  366. // receive JSON type T
  367. var data T
  368. websocket.JSON.Receive(ws, &data)
  369. // send JSON type T
  370. websocket.JSON.Send(ws, data)
  371. */
  372. var JSON = Codec{jsonMarshal, jsonUnmarshal}