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.2KB

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