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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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. // Callers MUST be writing to the client's socket from the client's own goroutine;
  94. // other callers must use the nonblocking Write call instead. Otherwise, a client
  95. // with a slow/unreliable connection risks stalling the progress of the system as a whole.
  96. func (socket *Socket) BlockingWrite(data []byte) (err error) {
  97. if len(data) == 0 {
  98. return
  99. }
  100. // after releasing the semaphore, we must check for fresh data, same as `send`
  101. defer func() {
  102. if socket.readyToWrite() {
  103. socket.wakeWriter()
  104. }
  105. }()
  106. // blocking acquire of the trylock
  107. socket.writerSemaphore.Acquire()
  108. defer socket.writerSemaphore.Release()
  109. // first, flush any buffered data, to preserve the ordering guarantees
  110. closed := socket.performWrite()
  111. if closed {
  112. return io.EOF
  113. }
  114. err = socket.conn.WriteLine(data)
  115. if err != nil {
  116. socket.finalize()
  117. }
  118. return
  119. }
  120. // wakeWriter starts the goroutine that actually performs the write, without blocking
  121. func (socket *Socket) wakeWriter() {
  122. if socket.writerSemaphore.TryAcquire() {
  123. // acquired the trylock; send() will release it
  124. go socket.send()
  125. }
  126. // else: do nothing, the holder will check for more data after releasing it
  127. }
  128. // SetFinalData sets the final data to send when the SocketWriter closes.
  129. func (socket *Socket) SetFinalData(data []byte) {
  130. socket.Lock()
  131. defer socket.Unlock()
  132. socket.finalData = data
  133. }
  134. // IsClosed returns whether the socket is closed.
  135. func (socket *Socket) IsClosed() bool {
  136. socket.Lock()
  137. defer socket.Unlock()
  138. return socket.closed
  139. }
  140. // is there data to write?
  141. func (socket *Socket) readyToWrite() bool {
  142. socket.Lock()
  143. defer socket.Unlock()
  144. // on the first time observing socket.closed, we still have to write socket.finalData
  145. return !socket.finalized && (socket.totalLength > 0 || socket.closed)
  146. }
  147. // send actually writes messages to socket.Conn; it may block
  148. func (socket *Socket) send() {
  149. for {
  150. // we are holding the trylock: actually do the write
  151. socket.performWrite()
  152. // surrender the trylock, avoiding a race where a write comes in after we've
  153. // checked readyToWrite() and it returned false, but while we still hold the trylock:
  154. socket.writerSemaphore.Release()
  155. // check if more data came in while we held the trylock:
  156. if !socket.readyToWrite() {
  157. return
  158. }
  159. if !socket.writerSemaphore.TryAcquire() {
  160. // failed to acquire; exit and wait for the holder to observe readyToWrite()
  161. // after releasing it
  162. return
  163. }
  164. // got the lock again, loop back around and write
  165. }
  166. }
  167. // write the contents of the buffer, then see if we need to close
  168. // returns whether we closed
  169. func (socket *Socket) performWrite() (closed bool) {
  170. // retrieve the buffered data, clear the buffer
  171. socket.Lock()
  172. buffers := socket.buffers
  173. socket.buffers = nil
  174. socket.totalLength = 0
  175. closed = socket.closed
  176. socket.Unlock()
  177. var err error
  178. if 0 < len(buffers) {
  179. err = socket.conn.WriteLines(buffers)
  180. }
  181. closed = closed || err != nil
  182. if closed {
  183. socket.finalize()
  184. }
  185. return
  186. }
  187. // mark closed and send final data. you must be holding the semaphore to call this:
  188. func (socket *Socket) finalize() {
  189. // mark the socket closed (if someone hasn't already), then write error lines
  190. socket.Lock()
  191. socket.closed = true
  192. finalized := socket.finalized
  193. socket.finalized = true
  194. finalData := socket.finalData
  195. if socket.sendQExceeded {
  196. finalData = sendQExceededMessage
  197. }
  198. socket.Unlock()
  199. if finalized {
  200. return
  201. }
  202. if len(finalData) != 0 {
  203. socket.conn.WriteLine(finalData)
  204. }
  205. // close the connection
  206. socket.conn.Close()
  207. }