conn.go 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201
  1. // Copyright 2013 The Gorilla WebSocket 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
  5. import (
  6. "bufio"
  7. "encoding/binary"
  8. "errors"
  9. "io"
  10. "io/ioutil"
  11. "math/rand"
  12. "net"
  13. "strconv"
  14. "sync"
  15. "time"
  16. "unicode/utf8"
  17. )
  18. const (
  19. // Frame header byte 0 bits from Section 5.2 of RFC 6455
  20. finalBit = 1 << 7
  21. rsv1Bit = 1 << 6
  22. rsv2Bit = 1 << 5
  23. rsv3Bit = 1 << 4
  24. // Frame header byte 1 bits from Section 5.2 of RFC 6455
  25. maskBit = 1 << 7
  26. maxFrameHeaderSize = 2 + 8 + 4 // Fixed header + length + mask
  27. maxControlFramePayloadSize = 125
  28. writeWait = time.Second
  29. defaultReadBufferSize = 4096
  30. defaultWriteBufferSize = 4096
  31. continuationFrame = 0
  32. noFrame = -1
  33. )
  34. // Close codes defined in RFC 6455, section 11.7.
  35. const (
  36. CloseNormalClosure = 1000
  37. CloseGoingAway = 1001
  38. CloseProtocolError = 1002
  39. CloseUnsupportedData = 1003
  40. CloseNoStatusReceived = 1005
  41. CloseAbnormalClosure = 1006
  42. CloseInvalidFramePayloadData = 1007
  43. ClosePolicyViolation = 1008
  44. CloseMessageTooBig = 1009
  45. CloseMandatoryExtension = 1010
  46. CloseInternalServerErr = 1011
  47. CloseServiceRestart = 1012
  48. CloseTryAgainLater = 1013
  49. CloseTLSHandshake = 1015
  50. )
  51. // The message types are defined in RFC 6455, section 11.8.
  52. const (
  53. // TextMessage denotes a text data message. The text message payload is
  54. // interpreted as UTF-8 encoded text data.
  55. TextMessage = 1
  56. // BinaryMessage denotes a binary data message.
  57. BinaryMessage = 2
  58. // CloseMessage denotes a close control message. The optional message
  59. // payload contains a numeric code and text. Use the FormatCloseMessage
  60. // function to format a close message payload.
  61. CloseMessage = 8
  62. // PingMessage denotes a ping control message. The optional message payload
  63. // is UTF-8 encoded text.
  64. PingMessage = 9
  65. // PongMessage denotes a pong control message. The optional message payload
  66. // is UTF-8 encoded text.
  67. PongMessage = 10
  68. )
  69. // ErrCloseSent is returned when the application writes a message to the
  70. // connection after sending a close message.
  71. var ErrCloseSent = errors.New("websocket: close sent")
  72. // ErrReadLimit is returned when reading a message that is larger than the
  73. // read limit set for the connection.
  74. var ErrReadLimit = errors.New("websocket: read limit exceeded")
  75. // netError satisfies the net Error interface.
  76. type netError struct {
  77. msg string
  78. temporary bool
  79. timeout bool
  80. }
  81. func (e *netError) Error() string { return e.msg }
  82. func (e *netError) Temporary() bool { return e.temporary }
  83. func (e *netError) Timeout() bool { return e.timeout }
  84. // CloseError represents a close message.
  85. type CloseError struct {
  86. // Code is defined in RFC 6455, section 11.7.
  87. Code int
  88. // Text is the optional text payload.
  89. Text string
  90. }
  91. func (e *CloseError) Error() string {
  92. s := []byte("websocket: close ")
  93. s = strconv.AppendInt(s, int64(e.Code), 10)
  94. switch e.Code {
  95. case CloseNormalClosure:
  96. s = append(s, " (normal)"...)
  97. case CloseGoingAway:
  98. s = append(s, " (going away)"...)
  99. case CloseProtocolError:
  100. s = append(s, " (protocol error)"...)
  101. case CloseUnsupportedData:
  102. s = append(s, " (unsupported data)"...)
  103. case CloseNoStatusReceived:
  104. s = append(s, " (no status)"...)
  105. case CloseAbnormalClosure:
  106. s = append(s, " (abnormal closure)"...)
  107. case CloseInvalidFramePayloadData:
  108. s = append(s, " (invalid payload data)"...)
  109. case ClosePolicyViolation:
  110. s = append(s, " (policy violation)"...)
  111. case CloseMessageTooBig:
  112. s = append(s, " (message too big)"...)
  113. case CloseMandatoryExtension:
  114. s = append(s, " (mandatory extension missing)"...)
  115. case CloseInternalServerErr:
  116. s = append(s, " (internal server error)"...)
  117. case CloseTLSHandshake:
  118. s = append(s, " (TLS handshake error)"...)
  119. }
  120. if e.Text != "" {
  121. s = append(s, ": "...)
  122. s = append(s, e.Text...)
  123. }
  124. return string(s)
  125. }
  126. // IsCloseError returns boolean indicating whether the error is a *CloseError
  127. // with one of the specified codes.
  128. func IsCloseError(err error, codes ...int) bool {
  129. if e, ok := err.(*CloseError); ok {
  130. for _, code := range codes {
  131. if e.Code == code {
  132. return true
  133. }
  134. }
  135. }
  136. return false
  137. }
  138. // IsUnexpectedCloseError returns boolean indicating whether the error is a
  139. // *CloseError with a code not in the list of expected codes.
  140. func IsUnexpectedCloseError(err error, expectedCodes ...int) bool {
  141. if e, ok := err.(*CloseError); ok {
  142. for _, code := range expectedCodes {
  143. if e.Code == code {
  144. return false
  145. }
  146. }
  147. return true
  148. }
  149. return false
  150. }
  151. var (
  152. errWriteTimeout = &netError{msg: "websocket: write timeout", timeout: true, temporary: true}
  153. errUnexpectedEOF = &CloseError{Code: CloseAbnormalClosure, Text: io.ErrUnexpectedEOF.Error()}
  154. errBadWriteOpCode = errors.New("websocket: bad write message type")
  155. errWriteClosed = errors.New("websocket: write closed")
  156. errInvalidControlFrame = errors.New("websocket: invalid control frame")
  157. )
  158. func newMaskKey() [4]byte {
  159. n := rand.Uint32()
  160. return [4]byte{byte(n), byte(n >> 8), byte(n >> 16), byte(n >> 24)}
  161. }
  162. func hideTempErr(err error) error {
  163. if e, ok := err.(net.Error); ok && e.Temporary() {
  164. err = &netError{msg: e.Error(), timeout: e.Timeout()}
  165. }
  166. return err
  167. }
  168. func isControl(frameType int) bool {
  169. return frameType == CloseMessage || frameType == PingMessage || frameType == PongMessage
  170. }
  171. func isData(frameType int) bool {
  172. return frameType == TextMessage || frameType == BinaryMessage
  173. }
  174. var validReceivedCloseCodes = map[int]bool{
  175. // see http://www.iana.org/assignments/websocket/websocket.xhtml#close-code-number
  176. CloseNormalClosure: true,
  177. CloseGoingAway: true,
  178. CloseProtocolError: true,
  179. CloseUnsupportedData: true,
  180. CloseNoStatusReceived: false,
  181. CloseAbnormalClosure: false,
  182. CloseInvalidFramePayloadData: true,
  183. ClosePolicyViolation: true,
  184. CloseMessageTooBig: true,
  185. CloseMandatoryExtension: true,
  186. CloseInternalServerErr: true,
  187. CloseServiceRestart: true,
  188. CloseTryAgainLater: true,
  189. CloseTLSHandshake: false,
  190. }
  191. func isValidReceivedCloseCode(code int) bool {
  192. return validReceivedCloseCodes[code] || (code >= 3000 && code <= 4999)
  193. }
  194. // BufferPool represents a pool of buffers. The *sync.Pool type satisfies this
  195. // interface. The type of the value stored in a pool is not specified.
  196. type BufferPool interface {
  197. // Get gets a value from the pool or returns nil if the pool is empty.
  198. Get() interface{}
  199. // Put adds a value to the pool.
  200. Put(interface{})
  201. }
  202. // writePoolData is the type added to the write buffer pool. This wrapper is
  203. // used to prevent applications from peeking at and depending on the values
  204. // added to the pool.
  205. type writePoolData struct{ buf []byte }
  206. // The Conn type represents a WebSocket connection.
  207. type Conn struct {
  208. conn net.Conn
  209. isServer bool
  210. subprotocol string
  211. // Write fields
  212. mu chan struct{} // used as mutex to protect write to conn
  213. writeBuf []byte // frame is constructed in this buffer.
  214. writePool BufferPool
  215. writeBufSize int
  216. writeDeadline time.Time
  217. writer io.WriteCloser // the current writer returned to the application
  218. isWriting bool // for best-effort concurrent write detection
  219. writeErrMu sync.Mutex
  220. writeErr error
  221. enableWriteCompression bool
  222. compressionLevel int
  223. newCompressionWriter func(io.WriteCloser, int) io.WriteCloser
  224. // Read fields
  225. reader io.ReadCloser // the current reader returned to the application
  226. readErr error
  227. br *bufio.Reader
  228. // bytes remaining in current frame.
  229. // set setReadRemaining to safely update this value and prevent overflow
  230. readRemaining int64
  231. readFinal bool // true the current message has more frames.
  232. readLength int64 // Message size.
  233. readLimit int64 // Maximum message size.
  234. readMaskPos int
  235. readMaskKey [4]byte
  236. handlePong func(string) error
  237. handlePing func(string) error
  238. handleClose func(int, string) error
  239. readErrCount int
  240. messageReader *messageReader // the current low-level reader
  241. readDecompress bool // whether last read frame had RSV1 set
  242. newDecompressionReader func(io.Reader) io.ReadCloser
  243. }
  244. func newConn(conn net.Conn, isServer bool, readBufferSize, writeBufferSize int, writeBufferPool BufferPool, br *bufio.Reader, writeBuf []byte) *Conn {
  245. if br == nil {
  246. if readBufferSize == 0 {
  247. readBufferSize = defaultReadBufferSize
  248. } else if readBufferSize < maxControlFramePayloadSize {
  249. // must be large enough for control frame
  250. readBufferSize = maxControlFramePayloadSize
  251. }
  252. br = bufio.NewReaderSize(conn, readBufferSize)
  253. }
  254. if writeBufferSize <= 0 {
  255. writeBufferSize = defaultWriteBufferSize
  256. }
  257. writeBufferSize += maxFrameHeaderSize
  258. if writeBuf == nil && writeBufferPool == nil {
  259. writeBuf = make([]byte, writeBufferSize)
  260. }
  261. mu := make(chan struct{}, 1)
  262. mu <- struct{}{}
  263. c := &Conn{
  264. isServer: isServer,
  265. br: br,
  266. conn: conn,
  267. mu: mu,
  268. readFinal: true,
  269. writeBuf: writeBuf,
  270. writePool: writeBufferPool,
  271. writeBufSize: writeBufferSize,
  272. enableWriteCompression: true,
  273. compressionLevel: defaultCompressionLevel,
  274. }
  275. c.SetCloseHandler(nil)
  276. c.SetPingHandler(nil)
  277. c.SetPongHandler(nil)
  278. return c
  279. }
  280. // setReadRemaining tracks the number of bytes remaining on the connection. If n
  281. // overflows, an ErrReadLimit is returned.
  282. func (c *Conn) setReadRemaining(n int64) error {
  283. if n < 0 {
  284. return ErrReadLimit
  285. }
  286. c.readRemaining = n
  287. return nil
  288. }
  289. // Subprotocol returns the negotiated protocol for the connection.
  290. func (c *Conn) Subprotocol() string {
  291. return c.subprotocol
  292. }
  293. // Close closes the underlying network connection without sending or waiting
  294. // for a close message.
  295. func (c *Conn) Close() error {
  296. return c.conn.Close()
  297. }
  298. // LocalAddr returns the local network address.
  299. func (c *Conn) LocalAddr() net.Addr {
  300. return c.conn.LocalAddr()
  301. }
  302. // RemoteAddr returns the remote network address.
  303. func (c *Conn) RemoteAddr() net.Addr {
  304. return c.conn.RemoteAddr()
  305. }
  306. // Write methods
  307. func (c *Conn) writeFatal(err error) error {
  308. err = hideTempErr(err)
  309. c.writeErrMu.Lock()
  310. if c.writeErr == nil {
  311. c.writeErr = err
  312. }
  313. c.writeErrMu.Unlock()
  314. return err
  315. }
  316. func (c *Conn) read(n int) ([]byte, error) {
  317. p, err := c.br.Peek(n)
  318. if err == io.EOF {
  319. err = errUnexpectedEOF
  320. }
  321. c.br.Discard(len(p))
  322. return p, err
  323. }
  324. func (c *Conn) write(frameType int, deadline time.Time, buf0, buf1 []byte) error {
  325. <-c.mu
  326. defer func() { c.mu <- struct{}{} }()
  327. c.writeErrMu.Lock()
  328. err := c.writeErr
  329. c.writeErrMu.Unlock()
  330. if err != nil {
  331. return err
  332. }
  333. c.conn.SetWriteDeadline(deadline)
  334. if len(buf1) == 0 {
  335. _, err = c.conn.Write(buf0)
  336. } else {
  337. err = c.writeBufs(buf0, buf1)
  338. }
  339. if err != nil {
  340. return c.writeFatal(err)
  341. }
  342. if frameType == CloseMessage {
  343. c.writeFatal(ErrCloseSent)
  344. }
  345. return nil
  346. }
  347. // WriteControl writes a control message with the given deadline. The allowed
  348. // message types are CloseMessage, PingMessage and PongMessage.
  349. func (c *Conn) WriteControl(messageType int, data []byte, deadline time.Time) error {
  350. if !isControl(messageType) {
  351. return errBadWriteOpCode
  352. }
  353. if len(data) > maxControlFramePayloadSize {
  354. return errInvalidControlFrame
  355. }
  356. b0 := byte(messageType) | finalBit
  357. b1 := byte(len(data))
  358. if !c.isServer {
  359. b1 |= maskBit
  360. }
  361. buf := make([]byte, 0, maxFrameHeaderSize+maxControlFramePayloadSize)
  362. buf = append(buf, b0, b1)
  363. if c.isServer {
  364. buf = append(buf, data...)
  365. } else {
  366. key := newMaskKey()
  367. buf = append(buf, key[:]...)
  368. buf = append(buf, data...)
  369. maskBytes(key, 0, buf[6:])
  370. }
  371. d := 1000 * time.Hour
  372. if !deadline.IsZero() {
  373. d = deadline.Sub(time.Now())
  374. if d < 0 {
  375. return errWriteTimeout
  376. }
  377. }
  378. timer := time.NewTimer(d)
  379. select {
  380. case <-c.mu:
  381. timer.Stop()
  382. case <-timer.C:
  383. return errWriteTimeout
  384. }
  385. defer func() { c.mu <- struct{}{} }()
  386. c.writeErrMu.Lock()
  387. err := c.writeErr
  388. c.writeErrMu.Unlock()
  389. if err != nil {
  390. return err
  391. }
  392. c.conn.SetWriteDeadline(deadline)
  393. _, err = c.conn.Write(buf)
  394. if err != nil {
  395. return c.writeFatal(err)
  396. }
  397. if messageType == CloseMessage {
  398. c.writeFatal(ErrCloseSent)
  399. }
  400. return err
  401. }
  402. // beginMessage prepares a connection and message writer for a new message.
  403. func (c *Conn) beginMessage(mw *messageWriter, messageType int) error {
  404. // Close previous writer if not already closed by the application. It's
  405. // probably better to return an error in this situation, but we cannot
  406. // change this without breaking existing applications.
  407. if c.writer != nil {
  408. c.writer.Close()
  409. c.writer = nil
  410. }
  411. if !isControl(messageType) && !isData(messageType) {
  412. return errBadWriteOpCode
  413. }
  414. c.writeErrMu.Lock()
  415. err := c.writeErr
  416. c.writeErrMu.Unlock()
  417. if err != nil {
  418. return err
  419. }
  420. mw.c = c
  421. mw.frameType = messageType
  422. mw.pos = maxFrameHeaderSize
  423. if c.writeBuf == nil {
  424. wpd, ok := c.writePool.Get().(writePoolData)
  425. if ok {
  426. c.writeBuf = wpd.buf
  427. } else {
  428. c.writeBuf = make([]byte, c.writeBufSize)
  429. }
  430. }
  431. return nil
  432. }
  433. // NextWriter returns a writer for the next message to send. The writer's Close
  434. // method flushes the complete message to the network.
  435. //
  436. // There can be at most one open writer on a connection. NextWriter closes the
  437. // previous writer if the application has not already done so.
  438. //
  439. // All message types (TextMessage, BinaryMessage, CloseMessage, PingMessage and
  440. // PongMessage) are supported.
  441. func (c *Conn) NextWriter(messageType int) (io.WriteCloser, error) {
  442. var mw messageWriter
  443. if err := c.beginMessage(&mw, messageType); err != nil {
  444. return nil, err
  445. }
  446. c.writer = &mw
  447. if c.newCompressionWriter != nil && c.enableWriteCompression && isData(messageType) {
  448. w := c.newCompressionWriter(c.writer, c.compressionLevel)
  449. mw.compress = true
  450. c.writer = w
  451. }
  452. return c.writer, nil
  453. }
  454. type messageWriter struct {
  455. c *Conn
  456. compress bool // whether next call to flushFrame should set RSV1
  457. pos int // end of data in writeBuf.
  458. frameType int // type of the current frame.
  459. err error
  460. }
  461. func (w *messageWriter) endMessage(err error) error {
  462. if w.err != nil {
  463. return err
  464. }
  465. c := w.c
  466. w.err = err
  467. c.writer = nil
  468. if c.writePool != nil {
  469. c.writePool.Put(writePoolData{buf: c.writeBuf})
  470. c.writeBuf = nil
  471. }
  472. return err
  473. }
  474. // flushFrame writes buffered data and extra as a frame to the network. The
  475. // final argument indicates that this is the last frame in the message.
  476. func (w *messageWriter) flushFrame(final bool, extra []byte) error {
  477. c := w.c
  478. length := w.pos - maxFrameHeaderSize + len(extra)
  479. // Check for invalid control frames.
  480. if isControl(w.frameType) &&
  481. (!final || length > maxControlFramePayloadSize) {
  482. return w.endMessage(errInvalidControlFrame)
  483. }
  484. b0 := byte(w.frameType)
  485. if final {
  486. b0 |= finalBit
  487. }
  488. if w.compress {
  489. b0 |= rsv1Bit
  490. }
  491. w.compress = false
  492. b1 := byte(0)
  493. if !c.isServer {
  494. b1 |= maskBit
  495. }
  496. // Assume that the frame starts at beginning of c.writeBuf.
  497. framePos := 0
  498. if c.isServer {
  499. // Adjust up if mask not included in the header.
  500. framePos = 4
  501. }
  502. switch {
  503. case length >= 65536:
  504. c.writeBuf[framePos] = b0
  505. c.writeBuf[framePos+1] = b1 | 127
  506. binary.BigEndian.PutUint64(c.writeBuf[framePos+2:], uint64(length))
  507. case length > 125:
  508. framePos += 6
  509. c.writeBuf[framePos] = b0
  510. c.writeBuf[framePos+1] = b1 | 126
  511. binary.BigEndian.PutUint16(c.writeBuf[framePos+2:], uint16(length))
  512. default:
  513. framePos += 8
  514. c.writeBuf[framePos] = b0
  515. c.writeBuf[framePos+1] = b1 | byte(length)
  516. }
  517. if !c.isServer {
  518. key := newMaskKey()
  519. copy(c.writeBuf[maxFrameHeaderSize-4:], key[:])
  520. maskBytes(key, 0, c.writeBuf[maxFrameHeaderSize:w.pos])
  521. if len(extra) > 0 {
  522. return w.endMessage(c.writeFatal(errors.New("websocket: internal error, extra used in client mode")))
  523. }
  524. }
  525. // Write the buffers to the connection with best-effort detection of
  526. // concurrent writes. See the concurrency section in the package
  527. // documentation for more info.
  528. if c.isWriting {
  529. panic("concurrent write to websocket connection")
  530. }
  531. c.isWriting = true
  532. err := c.write(w.frameType, c.writeDeadline, c.writeBuf[framePos:w.pos], extra)
  533. if !c.isWriting {
  534. panic("concurrent write to websocket connection")
  535. }
  536. c.isWriting = false
  537. if err != nil {
  538. return w.endMessage(err)
  539. }
  540. if final {
  541. w.endMessage(errWriteClosed)
  542. return nil
  543. }
  544. // Setup for next frame.
  545. w.pos = maxFrameHeaderSize
  546. w.frameType = continuationFrame
  547. return nil
  548. }
  549. func (w *messageWriter) ncopy(max int) (int, error) {
  550. n := len(w.c.writeBuf) - w.pos
  551. if n <= 0 {
  552. if err := w.flushFrame(false, nil); err != nil {
  553. return 0, err
  554. }
  555. n = len(w.c.writeBuf) - w.pos
  556. }
  557. if n > max {
  558. n = max
  559. }
  560. return n, nil
  561. }
  562. func (w *messageWriter) Write(p []byte) (int, error) {
  563. if w.err != nil {
  564. return 0, w.err
  565. }
  566. if len(p) > 2*len(w.c.writeBuf) && w.c.isServer {
  567. // Don't buffer large messages.
  568. err := w.flushFrame(false, p)
  569. if err != nil {
  570. return 0, err
  571. }
  572. return len(p), nil
  573. }
  574. nn := len(p)
  575. for len(p) > 0 {
  576. n, err := w.ncopy(len(p))
  577. if err != nil {
  578. return 0, err
  579. }
  580. copy(w.c.writeBuf[w.pos:], p[:n])
  581. w.pos += n
  582. p = p[n:]
  583. }
  584. return nn, nil
  585. }
  586. func (w *messageWriter) WriteString(p string) (int, error) {
  587. if w.err != nil {
  588. return 0, w.err
  589. }
  590. nn := len(p)
  591. for len(p) > 0 {
  592. n, err := w.ncopy(len(p))
  593. if err != nil {
  594. return 0, err
  595. }
  596. copy(w.c.writeBuf[w.pos:], p[:n])
  597. w.pos += n
  598. p = p[n:]
  599. }
  600. return nn, nil
  601. }
  602. func (w *messageWriter) ReadFrom(r io.Reader) (nn int64, err error) {
  603. if w.err != nil {
  604. return 0, w.err
  605. }
  606. for {
  607. if w.pos == len(w.c.writeBuf) {
  608. err = w.flushFrame(false, nil)
  609. if err != nil {
  610. break
  611. }
  612. }
  613. var n int
  614. n, err = r.Read(w.c.writeBuf[w.pos:])
  615. w.pos += n
  616. nn += int64(n)
  617. if err != nil {
  618. if err == io.EOF {
  619. err = nil
  620. }
  621. break
  622. }
  623. }
  624. return nn, err
  625. }
  626. func (w *messageWriter) Close() error {
  627. if w.err != nil {
  628. return w.err
  629. }
  630. return w.flushFrame(true, nil)
  631. }
  632. // WritePreparedMessage writes prepared message into connection.
  633. func (c *Conn) WritePreparedMessage(pm *PreparedMessage) error {
  634. frameType, frameData, err := pm.frame(prepareKey{
  635. isServer: c.isServer,
  636. compress: c.newCompressionWriter != nil && c.enableWriteCompression && isData(pm.messageType),
  637. compressionLevel: c.compressionLevel,
  638. })
  639. if err != nil {
  640. return err
  641. }
  642. if c.isWriting {
  643. panic("concurrent write to websocket connection")
  644. }
  645. c.isWriting = true
  646. err = c.write(frameType, c.writeDeadline, frameData, nil)
  647. if !c.isWriting {
  648. panic("concurrent write to websocket connection")
  649. }
  650. c.isWriting = false
  651. return err
  652. }
  653. // WriteMessage is a helper method for getting a writer using NextWriter,
  654. // writing the message and closing the writer.
  655. func (c *Conn) WriteMessage(messageType int, data []byte) error {
  656. if c.isServer && (c.newCompressionWriter == nil || !c.enableWriteCompression) {
  657. // Fast path with no allocations and single frame.
  658. var mw messageWriter
  659. if err := c.beginMessage(&mw, messageType); err != nil {
  660. return err
  661. }
  662. n := copy(c.writeBuf[mw.pos:], data)
  663. mw.pos += n
  664. data = data[n:]
  665. return mw.flushFrame(true, data)
  666. }
  667. w, err := c.NextWriter(messageType)
  668. if err != nil {
  669. return err
  670. }
  671. if _, err = w.Write(data); err != nil {
  672. return err
  673. }
  674. return w.Close()
  675. }
  676. // SetWriteDeadline sets the write deadline on the underlying network
  677. // connection. After a write has timed out, the websocket state is corrupt and
  678. // all future writes will return an error. A zero value for t means writes will
  679. // not time out.
  680. func (c *Conn) SetWriteDeadline(t time.Time) error {
  681. c.writeDeadline = t
  682. return nil
  683. }
  684. // Read methods
  685. func (c *Conn) advanceFrame() (int, error) {
  686. // 1. Skip remainder of previous frame.
  687. if c.readRemaining > 0 {
  688. if _, err := io.CopyN(ioutil.Discard, c.br, c.readRemaining); err != nil {
  689. return noFrame, err
  690. }
  691. }
  692. // 2. Read and parse first two bytes of frame header.
  693. p, err := c.read(2)
  694. if err != nil {
  695. return noFrame, err
  696. }
  697. final := p[0]&finalBit != 0
  698. frameType := int(p[0] & 0xf)
  699. mask := p[1]&maskBit != 0
  700. c.setReadRemaining(int64(p[1] & 0x7f))
  701. c.readDecompress = false
  702. if c.newDecompressionReader != nil && (p[0]&rsv1Bit) != 0 {
  703. c.readDecompress = true
  704. p[0] &^= rsv1Bit
  705. }
  706. if rsv := p[0] & (rsv1Bit | rsv2Bit | rsv3Bit); rsv != 0 {
  707. return noFrame, c.handleProtocolError("unexpected reserved bits 0x" + strconv.FormatInt(int64(rsv), 16))
  708. }
  709. switch frameType {
  710. case CloseMessage, PingMessage, PongMessage:
  711. if c.readRemaining > maxControlFramePayloadSize {
  712. return noFrame, c.handleProtocolError("control frame length > 125")
  713. }
  714. if !final {
  715. return noFrame, c.handleProtocolError("control frame not final")
  716. }
  717. case TextMessage, BinaryMessage:
  718. if !c.readFinal {
  719. return noFrame, c.handleProtocolError("message start before final message frame")
  720. }
  721. c.readFinal = final
  722. case continuationFrame:
  723. if c.readFinal {
  724. return noFrame, c.handleProtocolError("continuation after final message frame")
  725. }
  726. c.readFinal = final
  727. default:
  728. return noFrame, c.handleProtocolError("unknown opcode " + strconv.Itoa(frameType))
  729. }
  730. // 3. Read and parse frame length as per
  731. // https://tools.ietf.org/html/rfc6455#section-5.2
  732. //
  733. // The length of the "Payload data", in bytes: if 0-125, that is the payload
  734. // length.
  735. // - If 126, the following 2 bytes interpreted as a 16-bit unsigned
  736. // integer are the payload length.
  737. // - If 127, the following 8 bytes interpreted as
  738. // a 64-bit unsigned integer (the most significant bit MUST be 0) are the
  739. // payload length. Multibyte length quantities are expressed in network byte
  740. // order.
  741. switch c.readRemaining {
  742. case 126:
  743. p, err := c.read(2)
  744. if err != nil {
  745. return noFrame, err
  746. }
  747. if err := c.setReadRemaining(int64(binary.BigEndian.Uint16(p))); err != nil {
  748. return noFrame, err
  749. }
  750. case 127:
  751. p, err := c.read(8)
  752. if err != nil {
  753. return noFrame, err
  754. }
  755. if err := c.setReadRemaining(int64(binary.BigEndian.Uint64(p))); err != nil {
  756. return noFrame, err
  757. }
  758. }
  759. // 4. Handle frame masking.
  760. if mask != c.isServer {
  761. return noFrame, c.handleProtocolError("incorrect mask flag")
  762. }
  763. if mask {
  764. c.readMaskPos = 0
  765. p, err := c.read(len(c.readMaskKey))
  766. if err != nil {
  767. return noFrame, err
  768. }
  769. copy(c.readMaskKey[:], p)
  770. }
  771. // 5. For text and binary messages, enforce read limit and return.
  772. if frameType == continuationFrame || frameType == TextMessage || frameType == BinaryMessage {
  773. c.readLength += c.readRemaining
  774. // Don't allow readLength to overflow in the presence of a large readRemaining
  775. // counter.
  776. if c.readLength < 0 {
  777. return noFrame, ErrReadLimit
  778. }
  779. if c.readLimit > 0 && c.readLength > c.readLimit {
  780. c.WriteControl(CloseMessage, FormatCloseMessage(CloseMessageTooBig, ""), time.Now().Add(writeWait))
  781. return noFrame, ErrReadLimit
  782. }
  783. return frameType, nil
  784. }
  785. // 6. Read control frame payload.
  786. var payload []byte
  787. if c.readRemaining > 0 {
  788. payload, err = c.read(int(c.readRemaining))
  789. c.setReadRemaining(0)
  790. if err != nil {
  791. return noFrame, err
  792. }
  793. if c.isServer {
  794. maskBytes(c.readMaskKey, 0, payload)
  795. }
  796. }
  797. // 7. Process control frame payload.
  798. switch frameType {
  799. case PongMessage:
  800. if err := c.handlePong(string(payload)); err != nil {
  801. return noFrame, err
  802. }
  803. case PingMessage:
  804. if err := c.handlePing(string(payload)); err != nil {
  805. return noFrame, err
  806. }
  807. case CloseMessage:
  808. closeCode := CloseNoStatusReceived
  809. closeText := ""
  810. if len(payload) >= 2 {
  811. closeCode = int(binary.BigEndian.Uint16(payload))
  812. if !isValidReceivedCloseCode(closeCode) {
  813. return noFrame, c.handleProtocolError("invalid close code")
  814. }
  815. closeText = string(payload[2:])
  816. if !utf8.ValidString(closeText) {
  817. return noFrame, c.handleProtocolError("invalid utf8 payload in close frame")
  818. }
  819. }
  820. if err := c.handleClose(closeCode, closeText); err != nil {
  821. return noFrame, err
  822. }
  823. return noFrame, &CloseError{Code: closeCode, Text: closeText}
  824. }
  825. return frameType, nil
  826. }
  827. func (c *Conn) handleProtocolError(message string) error {
  828. c.WriteControl(CloseMessage, FormatCloseMessage(CloseProtocolError, message), time.Now().Add(writeWait))
  829. return errors.New("websocket: " + message)
  830. }
  831. // NextReader returns the next data message received from the peer. The
  832. // returned messageType is either TextMessage or BinaryMessage.
  833. //
  834. // There can be at most one open reader on a connection. NextReader discards
  835. // the previous message if the application has not already consumed it.
  836. //
  837. // Applications must break out of the application's read loop when this method
  838. // returns a non-nil error value. Errors returned from this method are
  839. // permanent. Once this method returns a non-nil error, all subsequent calls to
  840. // this method return the same error.
  841. func (c *Conn) NextReader() (messageType int, r io.Reader, err error) {
  842. // Close previous reader, only relevant for decompression.
  843. if c.reader != nil {
  844. c.reader.Close()
  845. c.reader = nil
  846. }
  847. c.messageReader = nil
  848. c.readLength = 0
  849. for c.readErr == nil {
  850. frameType, err := c.advanceFrame()
  851. if err != nil {
  852. c.readErr = hideTempErr(err)
  853. break
  854. }
  855. if frameType == TextMessage || frameType == BinaryMessage {
  856. c.messageReader = &messageReader{c}
  857. c.reader = c.messageReader
  858. if c.readDecompress {
  859. c.reader = c.newDecompressionReader(c.reader)
  860. }
  861. return frameType, c.reader, nil
  862. }
  863. }
  864. // Applications that do handle the error returned from this method spin in
  865. // tight loop on connection failure. To help application developers detect
  866. // this error, panic on repeated reads to the failed connection.
  867. c.readErrCount++
  868. if c.readErrCount >= 1000 {
  869. panic("repeated read on failed websocket connection")
  870. }
  871. return noFrame, nil, c.readErr
  872. }
  873. type messageReader struct{ c *Conn }
  874. func (r *messageReader) Read(b []byte) (int, error) {
  875. c := r.c
  876. if c.messageReader != r {
  877. return 0, io.EOF
  878. }
  879. for c.readErr == nil {
  880. if c.readRemaining > 0 {
  881. if int64(len(b)) > c.readRemaining {
  882. b = b[:c.readRemaining]
  883. }
  884. n, err := c.br.Read(b)
  885. c.readErr = hideTempErr(err)
  886. if c.isServer {
  887. c.readMaskPos = maskBytes(c.readMaskKey, c.readMaskPos, b[:n])
  888. }
  889. rem := c.readRemaining
  890. rem -= int64(n)
  891. c.setReadRemaining(rem)
  892. if c.readRemaining > 0 && c.readErr == io.EOF {
  893. c.readErr = errUnexpectedEOF
  894. }
  895. return n, c.readErr
  896. }
  897. if c.readFinal {
  898. c.messageReader = nil
  899. return 0, io.EOF
  900. }
  901. frameType, err := c.advanceFrame()
  902. switch {
  903. case err != nil:
  904. c.readErr = hideTempErr(err)
  905. case frameType == TextMessage || frameType == BinaryMessage:
  906. c.readErr = errors.New("websocket: internal error, unexpected text or binary in Reader")
  907. }
  908. }
  909. err := c.readErr
  910. if err == io.EOF && c.messageReader == r {
  911. err = errUnexpectedEOF
  912. }
  913. return 0, err
  914. }
  915. func (r *messageReader) Close() error {
  916. return nil
  917. }
  918. // ReadMessage is a helper method for getting a reader using NextReader and
  919. // reading from that reader to a buffer.
  920. func (c *Conn) ReadMessage() (messageType int, p []byte, err error) {
  921. var r io.Reader
  922. messageType, r, err = c.NextReader()
  923. if err != nil {
  924. return messageType, nil, err
  925. }
  926. p, err = ioutil.ReadAll(r)
  927. return messageType, p, err
  928. }
  929. // SetReadDeadline sets the read deadline on the underlying network connection.
  930. // After a read has timed out, the websocket connection state is corrupt and
  931. // all future reads will return an error. A zero value for t means reads will
  932. // not time out.
  933. func (c *Conn) SetReadDeadline(t time.Time) error {
  934. return c.conn.SetReadDeadline(t)
  935. }
  936. // SetReadLimit sets the maximum size in bytes for a message read from the peer. If a
  937. // message exceeds the limit, the connection sends a close message to the peer
  938. // and returns ErrReadLimit to the application.
  939. func (c *Conn) SetReadLimit(limit int64) {
  940. c.readLimit = limit
  941. }
  942. // CloseHandler returns the current close handler
  943. func (c *Conn) CloseHandler() func(code int, text string) error {
  944. return c.handleClose
  945. }
  946. // SetCloseHandler sets the handler for close messages received from the peer.
  947. // The code argument to h is the received close code or CloseNoStatusReceived
  948. // if the close message is empty. The default close handler sends a close
  949. // message back to the peer.
  950. //
  951. // The handler function is called from the NextReader, ReadMessage and message
  952. // reader Read methods. The application must read the connection to process
  953. // close messages as described in the section on Control Messages above.
  954. //
  955. // The connection read methods return a CloseError when a close message is
  956. // received. Most applications should handle close messages as part of their
  957. // normal error handling. Applications should only set a close handler when the
  958. // application must perform some action before sending a close message back to
  959. // the peer.
  960. func (c *Conn) SetCloseHandler(h func(code int, text string) error) {
  961. if h == nil {
  962. h = func(code int, text string) error {
  963. message := FormatCloseMessage(code, "")
  964. c.WriteControl(CloseMessage, message, time.Now().Add(writeWait))
  965. return nil
  966. }
  967. }
  968. c.handleClose = h
  969. }
  970. // PingHandler returns the current ping handler
  971. func (c *Conn) PingHandler() func(appData string) error {
  972. return c.handlePing
  973. }
  974. // SetPingHandler sets the handler for ping messages received from the peer.
  975. // The appData argument to h is the PING message application data. The default
  976. // ping handler sends a pong to the peer.
  977. //
  978. // The handler function is called from the NextReader, ReadMessage and message
  979. // reader Read methods. The application must read the connection to process
  980. // ping messages as described in the section on Control Messages above.
  981. func (c *Conn) SetPingHandler(h func(appData string) error) {
  982. if h == nil {
  983. h = func(message string) error {
  984. err := c.WriteControl(PongMessage, []byte(message), time.Now().Add(writeWait))
  985. if err == ErrCloseSent {
  986. return nil
  987. } else if e, ok := err.(net.Error); ok && e.Temporary() {
  988. return nil
  989. }
  990. return err
  991. }
  992. }
  993. c.handlePing = h
  994. }
  995. // PongHandler returns the current pong handler
  996. func (c *Conn) PongHandler() func(appData string) error {
  997. return c.handlePong
  998. }
  999. // SetPongHandler sets the handler for pong messages received from the peer.
  1000. // The appData argument to h is the PONG message application data. The default
  1001. // pong handler does nothing.
  1002. //
  1003. // The handler function is called from the NextReader, ReadMessage and message
  1004. // reader Read methods. The application must read the connection to process
  1005. // pong messages as described in the section on Control Messages above.
  1006. func (c *Conn) SetPongHandler(h func(appData string) error) {
  1007. if h == nil {
  1008. h = func(string) error { return nil }
  1009. }
  1010. c.handlePong = h
  1011. }
  1012. // UnderlyingConn returns the internal net.Conn. This can be used to further
  1013. // modifications to connection specific flags.
  1014. func (c *Conn) UnderlyingConn() net.Conn {
  1015. return c.conn
  1016. }
  1017. // EnableWriteCompression enables and disables write compression of
  1018. // subsequent text and binary messages. This function is a noop if
  1019. // compression was not negotiated with the peer.
  1020. func (c *Conn) EnableWriteCompression(enable bool) {
  1021. c.enableWriteCompression = enable
  1022. }
  1023. // SetCompressionLevel sets the flate compression level for subsequent text and
  1024. // binary messages. This function is a noop if compression was not negotiated
  1025. // with the peer. See the compress/flate package for a description of
  1026. // compression levels.
  1027. func (c *Conn) SetCompressionLevel(level int) error {
  1028. if !isValidCompressionLevel(level) {
  1029. return errors.New("websocket: invalid compression level")
  1030. }
  1031. c.compressionLevel = level
  1032. return nil
  1033. }
  1034. // FormatCloseMessage formats closeCode and text as a WebSocket close message.
  1035. // An empty message is returned for code CloseNoStatusReceived.
  1036. func FormatCloseMessage(closeCode int, text string) []byte {
  1037. if closeCode == CloseNoStatusReceived {
  1038. // Return empty message because it's illegal to send
  1039. // CloseNoStatusReceived. Return non-nil value in case application
  1040. // checks for nil.
  1041. return []byte{}
  1042. }
  1043. buf := make([]byte, 2+len(text))
  1044. binary.BigEndian.PutUint16(buf, uint16(closeCode))
  1045. copy(buf[2:], text)
  1046. return buf
  1047. }