http urls monitor.

conn.go 30KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166
  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 bool // 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. readRemaining int64 // bytes remaining in current frame.
  229. readFinal bool // true the current message has more frames.
  230. readLength int64 // Message size.
  231. readLimit int64 // Maximum message size.
  232. readMaskPos int
  233. readMaskKey [4]byte
  234. handlePong func(string) error
  235. handlePing func(string) error
  236. handleClose func(int, string) error
  237. readErrCount int
  238. messageReader *messageReader // the current low-level reader
  239. readDecompress bool // whether last read frame had RSV1 set
  240. newDecompressionReader func(io.Reader) io.ReadCloser
  241. }
  242. func newConn(conn net.Conn, isServer bool, readBufferSize, writeBufferSize int, writeBufferPool BufferPool, br *bufio.Reader, writeBuf []byte) *Conn {
  243. if br == nil {
  244. if readBufferSize == 0 {
  245. readBufferSize = defaultReadBufferSize
  246. } else if readBufferSize < maxControlFramePayloadSize {
  247. // must be large enough for control frame
  248. readBufferSize = maxControlFramePayloadSize
  249. }
  250. br = bufio.NewReaderSize(conn, readBufferSize)
  251. }
  252. if writeBufferSize <= 0 {
  253. writeBufferSize = defaultWriteBufferSize
  254. }
  255. writeBufferSize += maxFrameHeaderSize
  256. if writeBuf == nil && writeBufferPool == nil {
  257. writeBuf = make([]byte, writeBufferSize)
  258. }
  259. mu := make(chan bool, 1)
  260. mu <- true
  261. c := &Conn{
  262. isServer: isServer,
  263. br: br,
  264. conn: conn,
  265. mu: mu,
  266. readFinal: true,
  267. writeBuf: writeBuf,
  268. writePool: writeBufferPool,
  269. writeBufSize: writeBufferSize,
  270. enableWriteCompression: true,
  271. compressionLevel: defaultCompressionLevel,
  272. }
  273. c.SetCloseHandler(nil)
  274. c.SetPingHandler(nil)
  275. c.SetPongHandler(nil)
  276. return c
  277. }
  278. // Subprotocol returns the negotiated protocol for the connection.
  279. func (c *Conn) Subprotocol() string {
  280. return c.subprotocol
  281. }
  282. // Close closes the underlying network connection without sending or waiting
  283. // for a close message.
  284. func (c *Conn) Close() error {
  285. return c.conn.Close()
  286. }
  287. // LocalAddr returns the local network address.
  288. func (c *Conn) LocalAddr() net.Addr {
  289. return c.conn.LocalAddr()
  290. }
  291. // RemoteAddr returns the remote network address.
  292. func (c *Conn) RemoteAddr() net.Addr {
  293. return c.conn.RemoteAddr()
  294. }
  295. // Write methods
  296. func (c *Conn) writeFatal(err error) error {
  297. err = hideTempErr(err)
  298. c.writeErrMu.Lock()
  299. if c.writeErr == nil {
  300. c.writeErr = err
  301. }
  302. c.writeErrMu.Unlock()
  303. return err
  304. }
  305. func (c *Conn) read(n int) ([]byte, error) {
  306. p, err := c.br.Peek(n)
  307. if err == io.EOF {
  308. err = errUnexpectedEOF
  309. }
  310. c.br.Discard(len(p))
  311. return p, err
  312. }
  313. func (c *Conn) write(frameType int, deadline time.Time, buf0, buf1 []byte) error {
  314. <-c.mu
  315. defer func() { c.mu <- true }()
  316. c.writeErrMu.Lock()
  317. err := c.writeErr
  318. c.writeErrMu.Unlock()
  319. if err != nil {
  320. return err
  321. }
  322. c.conn.SetWriteDeadline(deadline)
  323. if len(buf1) == 0 {
  324. _, err = c.conn.Write(buf0)
  325. } else {
  326. err = c.writeBufs(buf0, buf1)
  327. }
  328. if err != nil {
  329. return c.writeFatal(err)
  330. }
  331. if frameType == CloseMessage {
  332. c.writeFatal(ErrCloseSent)
  333. }
  334. return nil
  335. }
  336. // WriteControl writes a control message with the given deadline. The allowed
  337. // message types are CloseMessage, PingMessage and PongMessage.
  338. func (c *Conn) WriteControl(messageType int, data []byte, deadline time.Time) error {
  339. if !isControl(messageType) {
  340. return errBadWriteOpCode
  341. }
  342. if len(data) > maxControlFramePayloadSize {
  343. return errInvalidControlFrame
  344. }
  345. b0 := byte(messageType) | finalBit
  346. b1 := byte(len(data))
  347. if !c.isServer {
  348. b1 |= maskBit
  349. }
  350. buf := make([]byte, 0, maxFrameHeaderSize+maxControlFramePayloadSize)
  351. buf = append(buf, b0, b1)
  352. if c.isServer {
  353. buf = append(buf, data...)
  354. } else {
  355. key := newMaskKey()
  356. buf = append(buf, key[:]...)
  357. buf = append(buf, data...)
  358. maskBytes(key, 0, buf[6:])
  359. }
  360. d := time.Hour * 1000
  361. if !deadline.IsZero() {
  362. d = deadline.Sub(time.Now())
  363. if d < 0 {
  364. return errWriteTimeout
  365. }
  366. }
  367. timer := time.NewTimer(d)
  368. select {
  369. case <-c.mu:
  370. timer.Stop()
  371. case <-timer.C:
  372. return errWriteTimeout
  373. }
  374. defer func() { c.mu <- true }()
  375. c.writeErrMu.Lock()
  376. err := c.writeErr
  377. c.writeErrMu.Unlock()
  378. if err != nil {
  379. return err
  380. }
  381. c.conn.SetWriteDeadline(deadline)
  382. _, err = c.conn.Write(buf)
  383. if err != nil {
  384. return c.writeFatal(err)
  385. }
  386. if messageType == CloseMessage {
  387. c.writeFatal(ErrCloseSent)
  388. }
  389. return err
  390. }
  391. func (c *Conn) prepWrite(messageType int) error {
  392. // Close previous writer if not already closed by the application. It's
  393. // probably better to return an error in this situation, but we cannot
  394. // change this without breaking existing applications.
  395. if c.writer != nil {
  396. c.writer.Close()
  397. c.writer = nil
  398. }
  399. if !isControl(messageType) && !isData(messageType) {
  400. return errBadWriteOpCode
  401. }
  402. c.writeErrMu.Lock()
  403. err := c.writeErr
  404. c.writeErrMu.Unlock()
  405. if err != nil {
  406. return err
  407. }
  408. if c.writeBuf == nil {
  409. wpd, ok := c.writePool.Get().(writePoolData)
  410. if ok {
  411. c.writeBuf = wpd.buf
  412. } else {
  413. c.writeBuf = make([]byte, c.writeBufSize)
  414. }
  415. }
  416. return nil
  417. }
  418. // NextWriter returns a writer for the next message to send. The writer's Close
  419. // method flushes the complete message to the network.
  420. //
  421. // There can be at most one open writer on a connection. NextWriter closes the
  422. // previous writer if the application has not already done so.
  423. //
  424. // All message types (TextMessage, BinaryMessage, CloseMessage, PingMessage and
  425. // PongMessage) are supported.
  426. func (c *Conn) NextWriter(messageType int) (io.WriteCloser, error) {
  427. if err := c.prepWrite(messageType); err != nil {
  428. return nil, err
  429. }
  430. mw := &messageWriter{
  431. c: c,
  432. frameType: messageType,
  433. pos: maxFrameHeaderSize,
  434. }
  435. c.writer = mw
  436. if c.newCompressionWriter != nil && c.enableWriteCompression && isData(messageType) {
  437. w := c.newCompressionWriter(c.writer, c.compressionLevel)
  438. mw.compress = true
  439. c.writer = w
  440. }
  441. return c.writer, nil
  442. }
  443. type messageWriter struct {
  444. c *Conn
  445. compress bool // whether next call to flushFrame should set RSV1
  446. pos int // end of data in writeBuf.
  447. frameType int // type of the current frame.
  448. err error
  449. }
  450. func (w *messageWriter) fatal(err error) error {
  451. if w.err != nil {
  452. w.err = err
  453. w.c.writer = nil
  454. }
  455. return err
  456. }
  457. // flushFrame writes buffered data and extra as a frame to the network. The
  458. // final argument indicates that this is the last frame in the message.
  459. func (w *messageWriter) flushFrame(final bool, extra []byte) error {
  460. c := w.c
  461. length := w.pos - maxFrameHeaderSize + len(extra)
  462. // Check for invalid control frames.
  463. if isControl(w.frameType) &&
  464. (!final || length > maxControlFramePayloadSize) {
  465. return w.fatal(errInvalidControlFrame)
  466. }
  467. b0 := byte(w.frameType)
  468. if final {
  469. b0 |= finalBit
  470. }
  471. if w.compress {
  472. b0 |= rsv1Bit
  473. }
  474. w.compress = false
  475. b1 := byte(0)
  476. if !c.isServer {
  477. b1 |= maskBit
  478. }
  479. // Assume that the frame starts at beginning of c.writeBuf.
  480. framePos := 0
  481. if c.isServer {
  482. // Adjust up if mask not included in the header.
  483. framePos = 4
  484. }
  485. switch {
  486. case length >= 65536:
  487. c.writeBuf[framePos] = b0
  488. c.writeBuf[framePos+1] = b1 | 127
  489. binary.BigEndian.PutUint64(c.writeBuf[framePos+2:], uint64(length))
  490. case length > 125:
  491. framePos += 6
  492. c.writeBuf[framePos] = b0
  493. c.writeBuf[framePos+1] = b1 | 126
  494. binary.BigEndian.PutUint16(c.writeBuf[framePos+2:], uint16(length))
  495. default:
  496. framePos += 8
  497. c.writeBuf[framePos] = b0
  498. c.writeBuf[framePos+1] = b1 | byte(length)
  499. }
  500. if !c.isServer {
  501. key := newMaskKey()
  502. copy(c.writeBuf[maxFrameHeaderSize-4:], key[:])
  503. maskBytes(key, 0, c.writeBuf[maxFrameHeaderSize:w.pos])
  504. if len(extra) > 0 {
  505. return c.writeFatal(errors.New("websocket: internal error, extra used in client mode"))
  506. }
  507. }
  508. // Write the buffers to the connection with best-effort detection of
  509. // concurrent writes. See the concurrency section in the package
  510. // documentation for more info.
  511. if c.isWriting {
  512. panic("concurrent write to websocket connection")
  513. }
  514. c.isWriting = true
  515. err := c.write(w.frameType, c.writeDeadline, c.writeBuf[framePos:w.pos], extra)
  516. if !c.isWriting {
  517. panic("concurrent write to websocket connection")
  518. }
  519. c.isWriting = false
  520. if err != nil {
  521. return w.fatal(err)
  522. }
  523. if final {
  524. c.writer = nil
  525. if c.writePool != nil {
  526. c.writePool.Put(writePoolData{buf: c.writeBuf})
  527. c.writeBuf = nil
  528. }
  529. return nil
  530. }
  531. // Setup for next frame.
  532. w.pos = maxFrameHeaderSize
  533. w.frameType = continuationFrame
  534. return nil
  535. }
  536. func (w *messageWriter) ncopy(max int) (int, error) {
  537. n := len(w.c.writeBuf) - w.pos
  538. if n <= 0 {
  539. if err := w.flushFrame(false, nil); err != nil {
  540. return 0, err
  541. }
  542. n = len(w.c.writeBuf) - w.pos
  543. }
  544. if n > max {
  545. n = max
  546. }
  547. return n, nil
  548. }
  549. func (w *messageWriter) Write(p []byte) (int, error) {
  550. if w.err != nil {
  551. return 0, w.err
  552. }
  553. if len(p) > 2*len(w.c.writeBuf) && w.c.isServer {
  554. // Don't buffer large messages.
  555. err := w.flushFrame(false, p)
  556. if err != nil {
  557. return 0, err
  558. }
  559. return len(p), nil
  560. }
  561. nn := len(p)
  562. for len(p) > 0 {
  563. n, err := w.ncopy(len(p))
  564. if err != nil {
  565. return 0, err
  566. }
  567. copy(w.c.writeBuf[w.pos:], p[:n])
  568. w.pos += n
  569. p = p[n:]
  570. }
  571. return nn, nil
  572. }
  573. func (w *messageWriter) WriteString(p string) (int, error) {
  574. if w.err != nil {
  575. return 0, w.err
  576. }
  577. nn := len(p)
  578. for len(p) > 0 {
  579. n, err := w.ncopy(len(p))
  580. if err != nil {
  581. return 0, err
  582. }
  583. copy(w.c.writeBuf[w.pos:], p[:n])
  584. w.pos += n
  585. p = p[n:]
  586. }
  587. return nn, nil
  588. }
  589. func (w *messageWriter) ReadFrom(r io.Reader) (nn int64, err error) {
  590. if w.err != nil {
  591. return 0, w.err
  592. }
  593. for {
  594. if w.pos == len(w.c.writeBuf) {
  595. err = w.flushFrame(false, nil)
  596. if err != nil {
  597. break
  598. }
  599. }
  600. var n int
  601. n, err = r.Read(w.c.writeBuf[w.pos:])
  602. w.pos += n
  603. nn += int64(n)
  604. if err != nil {
  605. if err == io.EOF {
  606. err = nil
  607. }
  608. break
  609. }
  610. }
  611. return nn, err
  612. }
  613. func (w *messageWriter) Close() error {
  614. if w.err != nil {
  615. return w.err
  616. }
  617. if err := w.flushFrame(true, nil); err != nil {
  618. return err
  619. }
  620. w.err = errWriteClosed
  621. return nil
  622. }
  623. // WritePreparedMessage writes prepared message into connection.
  624. func (c *Conn) WritePreparedMessage(pm *PreparedMessage) error {
  625. frameType, frameData, err := pm.frame(prepareKey{
  626. isServer: c.isServer,
  627. compress: c.newCompressionWriter != nil && c.enableWriteCompression && isData(pm.messageType),
  628. compressionLevel: c.compressionLevel,
  629. })
  630. if err != nil {
  631. return err
  632. }
  633. if c.isWriting {
  634. panic("concurrent write to websocket connection")
  635. }
  636. c.isWriting = true
  637. err = c.write(frameType, c.writeDeadline, frameData, nil)
  638. if !c.isWriting {
  639. panic("concurrent write to websocket connection")
  640. }
  641. c.isWriting = false
  642. return err
  643. }
  644. // WriteMessage is a helper method for getting a writer using NextWriter,
  645. // writing the message and closing the writer.
  646. func (c *Conn) WriteMessage(messageType int, data []byte) error {
  647. if c.isServer && (c.newCompressionWriter == nil || !c.enableWriteCompression) {
  648. // Fast path with no allocations and single frame.
  649. if err := c.prepWrite(messageType); err != nil {
  650. return err
  651. }
  652. mw := messageWriter{c: c, frameType: messageType, pos: maxFrameHeaderSize}
  653. n := copy(c.writeBuf[mw.pos:], data)
  654. mw.pos += n
  655. data = data[n:]
  656. return mw.flushFrame(true, data)
  657. }
  658. w, err := c.NextWriter(messageType)
  659. if err != nil {
  660. return err
  661. }
  662. if _, err = w.Write(data); err != nil {
  663. return err
  664. }
  665. return w.Close()
  666. }
  667. // SetWriteDeadline sets the write deadline on the underlying network
  668. // connection. After a write has timed out, the websocket state is corrupt and
  669. // all future writes will return an error. A zero value for t means writes will
  670. // not time out.
  671. func (c *Conn) SetWriteDeadline(t time.Time) error {
  672. c.writeDeadline = t
  673. return nil
  674. }
  675. // Read methods
  676. func (c *Conn) advanceFrame() (int, error) {
  677. // 1. Skip remainder of previous frame.
  678. if c.readRemaining > 0 {
  679. if _, err := io.CopyN(ioutil.Discard, c.br, c.readRemaining); err != nil {
  680. return noFrame, err
  681. }
  682. }
  683. // 2. Read and parse first two bytes of frame header.
  684. p, err := c.read(2)
  685. if err != nil {
  686. return noFrame, err
  687. }
  688. final := p[0]&finalBit != 0
  689. frameType := int(p[0] & 0xf)
  690. mask := p[1]&maskBit != 0
  691. c.readRemaining = int64(p[1] & 0x7f)
  692. c.readDecompress = false
  693. if c.newDecompressionReader != nil && (p[0]&rsv1Bit) != 0 {
  694. c.readDecompress = true
  695. p[0] &^= rsv1Bit
  696. }
  697. if rsv := p[0] & (rsv1Bit | rsv2Bit | rsv3Bit); rsv != 0 {
  698. return noFrame, c.handleProtocolError("unexpected reserved bits 0x" + strconv.FormatInt(int64(rsv), 16))
  699. }
  700. switch frameType {
  701. case CloseMessage, PingMessage, PongMessage:
  702. if c.readRemaining > maxControlFramePayloadSize {
  703. return noFrame, c.handleProtocolError("control frame length > 125")
  704. }
  705. if !final {
  706. return noFrame, c.handleProtocolError("control frame not final")
  707. }
  708. case TextMessage, BinaryMessage:
  709. if !c.readFinal {
  710. return noFrame, c.handleProtocolError("message start before final message frame")
  711. }
  712. c.readFinal = final
  713. case continuationFrame:
  714. if c.readFinal {
  715. return noFrame, c.handleProtocolError("continuation after final message frame")
  716. }
  717. c.readFinal = final
  718. default:
  719. return noFrame, c.handleProtocolError("unknown opcode " + strconv.Itoa(frameType))
  720. }
  721. // 3. Read and parse frame length.
  722. switch c.readRemaining {
  723. case 126:
  724. p, err := c.read(2)
  725. if err != nil {
  726. return noFrame, err
  727. }
  728. c.readRemaining = int64(binary.BigEndian.Uint16(p))
  729. case 127:
  730. p, err := c.read(8)
  731. if err != nil {
  732. return noFrame, err
  733. }
  734. c.readRemaining = int64(binary.BigEndian.Uint64(p))
  735. }
  736. // 4. Handle frame masking.
  737. if mask != c.isServer {
  738. return noFrame, c.handleProtocolError("incorrect mask flag")
  739. }
  740. if mask {
  741. c.readMaskPos = 0
  742. p, err := c.read(len(c.readMaskKey))
  743. if err != nil {
  744. return noFrame, err
  745. }
  746. copy(c.readMaskKey[:], p)
  747. }
  748. // 5. For text and binary messages, enforce read limit and return.
  749. if frameType == continuationFrame || frameType == TextMessage || frameType == BinaryMessage {
  750. c.readLength += c.readRemaining
  751. if c.readLimit > 0 && c.readLength > c.readLimit {
  752. c.WriteControl(CloseMessage, FormatCloseMessage(CloseMessageTooBig, ""), time.Now().Add(writeWait))
  753. return noFrame, ErrReadLimit
  754. }
  755. return frameType, nil
  756. }
  757. // 6. Read control frame payload.
  758. var payload []byte
  759. if c.readRemaining > 0 {
  760. payload, err = c.read(int(c.readRemaining))
  761. c.readRemaining = 0
  762. if err != nil {
  763. return noFrame, err
  764. }
  765. if c.isServer {
  766. maskBytes(c.readMaskKey, 0, payload)
  767. }
  768. }
  769. // 7. Process control frame payload.
  770. switch frameType {
  771. case PongMessage:
  772. if err := c.handlePong(string(payload)); err != nil {
  773. return noFrame, err
  774. }
  775. case PingMessage:
  776. if err := c.handlePing(string(payload)); err != nil {
  777. return noFrame, err
  778. }
  779. case CloseMessage:
  780. closeCode := CloseNoStatusReceived
  781. closeText := ""
  782. if len(payload) >= 2 {
  783. closeCode = int(binary.BigEndian.Uint16(payload))
  784. if !isValidReceivedCloseCode(closeCode) {
  785. return noFrame, c.handleProtocolError("invalid close code")
  786. }
  787. closeText = string(payload[2:])
  788. if !utf8.ValidString(closeText) {
  789. return noFrame, c.handleProtocolError("invalid utf8 payload in close frame")
  790. }
  791. }
  792. if err := c.handleClose(closeCode, closeText); err != nil {
  793. return noFrame, err
  794. }
  795. return noFrame, &CloseError{Code: closeCode, Text: closeText}
  796. }
  797. return frameType, nil
  798. }
  799. func (c *Conn) handleProtocolError(message string) error {
  800. c.WriteControl(CloseMessage, FormatCloseMessage(CloseProtocolError, message), time.Now().Add(writeWait))
  801. return errors.New("websocket: " + message)
  802. }
  803. // NextReader returns the next data message received from the peer. The
  804. // returned messageType is either TextMessage or BinaryMessage.
  805. //
  806. // There can be at most one open reader on a connection. NextReader discards
  807. // the previous message if the application has not already consumed it.
  808. //
  809. // Applications must break out of the application's read loop when this method
  810. // returns a non-nil error value. Errors returned from this method are
  811. // permanent. Once this method returns a non-nil error, all subsequent calls to
  812. // this method return the same error.
  813. func (c *Conn) NextReader() (messageType int, r io.Reader, err error) {
  814. // Close previous reader, only relevant for decompression.
  815. if c.reader != nil {
  816. c.reader.Close()
  817. c.reader = nil
  818. }
  819. c.messageReader = nil
  820. c.readLength = 0
  821. for c.readErr == nil {
  822. frameType, err := c.advanceFrame()
  823. if err != nil {
  824. c.readErr = hideTempErr(err)
  825. break
  826. }
  827. if frameType == TextMessage || frameType == BinaryMessage {
  828. c.messageReader = &messageReader{c}
  829. c.reader = c.messageReader
  830. if c.readDecompress {
  831. c.reader = c.newDecompressionReader(c.reader)
  832. }
  833. return frameType, c.reader, nil
  834. }
  835. }
  836. // Applications that do handle the error returned from this method spin in
  837. // tight loop on connection failure. To help application developers detect
  838. // this error, panic on repeated reads to the failed connection.
  839. c.readErrCount++
  840. if c.readErrCount >= 1000 {
  841. panic("repeated read on failed websocket connection")
  842. }
  843. return noFrame, nil, c.readErr
  844. }
  845. type messageReader struct{ c *Conn }
  846. func (r *messageReader) Read(b []byte) (int, error) {
  847. c := r.c
  848. if c.messageReader != r {
  849. return 0, io.EOF
  850. }
  851. for c.readErr == nil {
  852. if c.readRemaining > 0 {
  853. if int64(len(b)) > c.readRemaining {
  854. b = b[:c.readRemaining]
  855. }
  856. n, err := c.br.Read(b)
  857. c.readErr = hideTempErr(err)
  858. if c.isServer {
  859. c.readMaskPos = maskBytes(c.readMaskKey, c.readMaskPos, b[:n])
  860. }
  861. c.readRemaining -= int64(n)
  862. if c.readRemaining > 0 && c.readErr == io.EOF {
  863. c.readErr = errUnexpectedEOF
  864. }
  865. return n, c.readErr
  866. }
  867. if c.readFinal {
  868. c.messageReader = nil
  869. return 0, io.EOF
  870. }
  871. frameType, err := c.advanceFrame()
  872. switch {
  873. case err != nil:
  874. c.readErr = hideTempErr(err)
  875. case frameType == TextMessage || frameType == BinaryMessage:
  876. c.readErr = errors.New("websocket: internal error, unexpected text or binary in Reader")
  877. }
  878. }
  879. err := c.readErr
  880. if err == io.EOF && c.messageReader == r {
  881. err = errUnexpectedEOF
  882. }
  883. return 0, err
  884. }
  885. func (r *messageReader) Close() error {
  886. return nil
  887. }
  888. // ReadMessage is a helper method for getting a reader using NextReader and
  889. // reading from that reader to a buffer.
  890. func (c *Conn) ReadMessage() (messageType int, p []byte, err error) {
  891. var r io.Reader
  892. messageType, r, err = c.NextReader()
  893. if err != nil {
  894. return messageType, nil, err
  895. }
  896. p, err = ioutil.ReadAll(r)
  897. return messageType, p, err
  898. }
  899. // SetReadDeadline sets the read deadline on the underlying network connection.
  900. // After a read has timed out, the websocket connection state is corrupt and
  901. // all future reads will return an error. A zero value for t means reads will
  902. // not time out.
  903. func (c *Conn) SetReadDeadline(t time.Time) error {
  904. return c.conn.SetReadDeadline(t)
  905. }
  906. // SetReadLimit sets the maximum size for a message read from the peer. If a
  907. // message exceeds the limit, the connection sends a close message to the peer
  908. // and returns ErrReadLimit to the application.
  909. func (c *Conn) SetReadLimit(limit int64) {
  910. c.readLimit = limit
  911. }
  912. // CloseHandler returns the current close handler
  913. func (c *Conn) CloseHandler() func(code int, text string) error {
  914. return c.handleClose
  915. }
  916. // SetCloseHandler sets the handler for close messages received from the peer.
  917. // The code argument to h is the received close code or CloseNoStatusReceived
  918. // if the close message is empty. The default close handler sends a close
  919. // message back to the peer.
  920. //
  921. // The handler function is called from the NextReader, ReadMessage and message
  922. // reader Read methods. The application must read the connection to process
  923. // close messages as described in the section on Control Messages above.
  924. //
  925. // The connection read methods return a CloseError when a close message is
  926. // received. Most applications should handle close messages as part of their
  927. // normal error handling. Applications should only set a close handler when the
  928. // application must perform some action before sending a close message back to
  929. // the peer.
  930. func (c *Conn) SetCloseHandler(h func(code int, text string) error) {
  931. if h == nil {
  932. h = func(code int, text string) error {
  933. message := FormatCloseMessage(code, "")
  934. c.WriteControl(CloseMessage, message, time.Now().Add(writeWait))
  935. return nil
  936. }
  937. }
  938. c.handleClose = h
  939. }
  940. // PingHandler returns the current ping handler
  941. func (c *Conn) PingHandler() func(appData string) error {
  942. return c.handlePing
  943. }
  944. // SetPingHandler sets the handler for ping messages received from the peer.
  945. // The appData argument to h is the PING message application data. The default
  946. // ping handler sends a pong to the peer.
  947. //
  948. // The handler function is called from the NextReader, ReadMessage and message
  949. // reader Read methods. The application must read the connection to process
  950. // ping messages as described in the section on Control Messages above.
  951. func (c *Conn) SetPingHandler(h func(appData string) error) {
  952. if h == nil {
  953. h = func(message string) error {
  954. err := c.WriteControl(PongMessage, []byte(message), time.Now().Add(writeWait))
  955. if err == ErrCloseSent {
  956. return nil
  957. } else if e, ok := err.(net.Error); ok && e.Temporary() {
  958. return nil
  959. }
  960. return err
  961. }
  962. }
  963. c.handlePing = h
  964. }
  965. // PongHandler returns the current pong handler
  966. func (c *Conn) PongHandler() func(appData string) error {
  967. return c.handlePong
  968. }
  969. // SetPongHandler sets the handler for pong messages received from the peer.
  970. // The appData argument to h is the PONG message application data. The default
  971. // pong handler does nothing.
  972. //
  973. // The handler function is called from the NextReader, ReadMessage and message
  974. // reader Read methods. The application must read the connection to process
  975. // pong messages as described in the section on Control Messages above.
  976. func (c *Conn) SetPongHandler(h func(appData string) error) {
  977. if h == nil {
  978. h = func(string) error { return nil }
  979. }
  980. c.handlePong = h
  981. }
  982. // UnderlyingConn returns the internal net.Conn. This can be used to further
  983. // modifications to connection specific flags.
  984. func (c *Conn) UnderlyingConn() net.Conn {
  985. return c.conn
  986. }
  987. // EnableWriteCompression enables and disables write compression of
  988. // subsequent text and binary messages. This function is a noop if
  989. // compression was not negotiated with the peer.
  990. func (c *Conn) EnableWriteCompression(enable bool) {
  991. c.enableWriteCompression = enable
  992. }
  993. // SetCompressionLevel sets the flate compression level for subsequent text and
  994. // binary messages. This function is a noop if compression was not negotiated
  995. // with the peer. See the compress/flate package for a description of
  996. // compression levels.
  997. func (c *Conn) SetCompressionLevel(level int) error {
  998. if !isValidCompressionLevel(level) {
  999. return errors.New("websocket: invalid compression level")
  1000. }
  1001. c.compressionLevel = level
  1002. return nil
  1003. }
  1004. // FormatCloseMessage formats closeCode and text as a WebSocket close message.
  1005. // An empty message is returned for code CloseNoStatusReceived.
  1006. func FormatCloseMessage(closeCode int, text string) []byte {
  1007. if closeCode == CloseNoStatusReceived {
  1008. // Return empty message because it's illegal to send
  1009. // CloseNoStatusReceived. Return non-nil value in case application
  1010. // checks for nil.
  1011. return []byte{}
  1012. }
  1013. buf := make([]byte, 2+len(text))
  1014. binary.BigEndian.PutUint16(buf, uint16(closeCode))
  1015. copy(buf[2:], text)
  1016. return buf
  1017. }