You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

socket.go 6.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. // Copyright (c) 2012-2014 Jeremy Latt
  2. // Copyright (c) 2016-2017 Daniel Oaks <daniel@danieloaks.net>
  3. // released under the MIT license
  4. package irc
  5. import (
  6. "errors"
  7. "io"
  8. "sync"
  9. )
  10. var (
  11. errSendQExceeded = errors.New("SendQ exceeded")
  12. sendQExceededMessage = []byte("\r\nERROR :SendQ Exceeded\r\n")
  13. )
  14. // Socket represents an IRC socket.
  15. type Socket struct {
  16. sync.Mutex
  17. conn IRCConn
  18. maxSendQBytes int
  19. // this is a trylock enforcing that only one goroutine can write to `conn` at a time
  20. writeLock sync.Mutex
  21. buffers [][]byte
  22. totalLength int
  23. closed bool
  24. sendQExceeded bool
  25. finalData []byte // what to send when we die
  26. finalized bool
  27. }
  28. // NewSocket returns a new Socket.
  29. func NewSocket(conn IRCConn, maxSendQBytes int) *Socket {
  30. result := Socket{
  31. conn: conn,
  32. maxSendQBytes: maxSendQBytes,
  33. }
  34. return &result
  35. }
  36. // Close stops a Socket from being able to send/receive any more data.
  37. func (socket *Socket) Close() {
  38. socket.Lock()
  39. socket.closed = true
  40. socket.Unlock()
  41. socket.wakeWriter()
  42. }
  43. // Read returns a single IRC line from a Socket.
  44. func (socket *Socket) Read() (string, error) {
  45. // immediately fail if Close() has been called, even if there's
  46. // still data in a bufio.Reader or websocket buffer:
  47. if socket.IsClosed() {
  48. return "", io.EOF
  49. }
  50. lineBytes, err := socket.conn.ReadLine()
  51. line := string(lineBytes)
  52. if err == io.EOF {
  53. socket.Close()
  54. }
  55. return line, err
  56. }
  57. // Write sends the given string out of Socket. Requirements:
  58. // 1. MUST NOT block for macroscopic amounts of time
  59. // 2. MUST NOT reorder messages
  60. // 3. MUST provide mutual exclusion for socket.conn.Write
  61. // 4. SHOULD NOT tie up additional goroutines, beyond the one blocked on socket.conn.Write
  62. func (socket *Socket) Write(data []byte) (err error) {
  63. if len(data) == 0 {
  64. return
  65. }
  66. socket.Lock()
  67. if socket.closed {
  68. err = io.EOF
  69. } else {
  70. prospectiveLen := socket.totalLength + len(data)
  71. if prospectiveLen > socket.maxSendQBytes {
  72. socket.sendQExceeded = true
  73. socket.closed = true
  74. err = errSendQExceeded
  75. } else {
  76. socket.buffers = append(socket.buffers, data)
  77. socket.totalLength = prospectiveLen
  78. }
  79. }
  80. socket.Unlock()
  81. socket.wakeWriter()
  82. return
  83. }
  84. // BlockingWrite sends the given string out of Socket. Requirements:
  85. // 1. MUST block until the message is sent
  86. // 2. MUST bypass sendq (calls to BlockingWrite cannot, on their own, cause a sendq overflow)
  87. // 3. MUST provide mutual exclusion for socket.conn.Write
  88. // 4. MUST respect the same ordering guarantees as Write (i.e., if a call to Write that sends
  89. // message m1 happens-before a call to BlockingWrite that sends message m2,
  90. // m1 must be sent on the wire before m2
  91. //
  92. // Callers MUST be writing to the client's socket from the client's own goroutine;
  93. // other callers must use the nonblocking Write call instead. Otherwise, a client
  94. // with a slow/unreliable connection risks stalling the progress of the system as a whole.
  95. func (socket *Socket) BlockingWrite(data []byte) (err error) {
  96. if len(data) == 0 {
  97. return
  98. }
  99. // after releasing the semaphore, we must check for fresh data, same as `send`
  100. defer func() {
  101. if socket.readyToWrite() {
  102. socket.wakeWriter()
  103. }
  104. }()
  105. // blocking acquire of the trylock
  106. socket.writeLock.Lock()
  107. defer socket.writeLock.Unlock()
  108. // first, flush any buffered data, to preserve the ordering guarantees
  109. closed := socket.performWrite()
  110. if closed {
  111. return io.EOF
  112. }
  113. err = socket.conn.WriteLine(data)
  114. if err != nil {
  115. socket.finalize()
  116. }
  117. return
  118. }
  119. // wakeWriter starts the goroutine that actually performs the write, without blocking
  120. func (socket *Socket) wakeWriter() {
  121. if socket.writeLock.TryLock() {
  122. // acquired the trylock; send() will release it
  123. go socket.send()
  124. }
  125. // else: do nothing, the holder will check for more data after releasing it
  126. }
  127. // SetFinalData sets the final data to send when the SocketWriter closes.
  128. func (socket *Socket) SetFinalData(data []byte) {
  129. socket.Lock()
  130. defer socket.Unlock()
  131. socket.finalData = data
  132. }
  133. // IsClosed returns whether the socket is closed.
  134. func (socket *Socket) IsClosed() bool {
  135. socket.Lock()
  136. defer socket.Unlock()
  137. return socket.closed
  138. }
  139. // is there data to write?
  140. func (socket *Socket) readyToWrite() bool {
  141. socket.Lock()
  142. defer socket.Unlock()
  143. // on the first time observing socket.closed, we still have to write socket.finalData
  144. return !socket.finalized && (socket.totalLength > 0 || socket.closed)
  145. }
  146. // send actually writes messages to socket.Conn; it may block
  147. func (socket *Socket) send() {
  148. for {
  149. // we are holding the trylock: actually do the write
  150. socket.performWrite()
  151. // surrender the trylock, avoiding a race where a write comes in after we've
  152. // checked readyToWrite() and it returned false, but while we still hold the trylock:
  153. socket.writeLock.Unlock()
  154. // check if more data came in while we held the trylock:
  155. if !socket.readyToWrite() {
  156. return
  157. }
  158. if !socket.writeLock.TryLock() {
  159. // failed to acquire; exit and wait for the holder to observe readyToWrite()
  160. // after releasing it
  161. return
  162. }
  163. // got the lock again, loop back around and write
  164. }
  165. }
  166. // write the contents of the buffer, then see if we need to close
  167. // returns whether we closed
  168. func (socket *Socket) performWrite() (closed bool) {
  169. // retrieve the buffered data, clear the buffer
  170. socket.Lock()
  171. buffers := socket.buffers
  172. socket.buffers = nil
  173. socket.totalLength = 0
  174. closed = socket.closed
  175. socket.Unlock()
  176. var err error
  177. if 0 < len(buffers) {
  178. err = socket.conn.WriteLines(buffers)
  179. }
  180. closed = closed || err != nil
  181. if closed {
  182. socket.finalize()
  183. }
  184. return
  185. }
  186. // mark closed and send final data. you must be holding the semaphore to call this:
  187. func (socket *Socket) finalize() {
  188. // mark the socket closed (if someone hasn't already), then write error lines
  189. socket.Lock()
  190. socket.closed = true
  191. finalized := socket.finalized
  192. socket.finalized = true
  193. finalData := socket.finalData
  194. if socket.sendQExceeded {
  195. finalData = sendQExceededMessage
  196. }
  197. socket.Unlock()
  198. if finalized {
  199. return
  200. }
  201. if len(finalData) != 0 {
  202. socket.conn.WriteLine(finalData)
  203. }
  204. // close the connection
  205. socket.conn.Close()
  206. }