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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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/oragono/oragono/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. }
  35. result.writerSemaphore.Initialize(1)
  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. // process last message properly (such as ERROR/QUIT/etc), just fail next reads/writes
  57. if line != "" {
  58. err = nil
  59. }
  60. }
  61. return line, err
  62. }
  63. // Write sends the given string out of Socket. Requirements:
  64. // 1. MUST NOT block for macroscopic amounts of time
  65. // 2. MUST NOT reorder messages
  66. // 3. MUST provide mutual exclusion for socket.conn.Write
  67. // 4. SHOULD NOT tie up additional goroutines, beyond the one blocked on socket.conn.Write
  68. func (socket *Socket) Write(data []byte) (err error) {
  69. if len(data) == 0 {
  70. return
  71. }
  72. socket.Lock()
  73. if socket.closed {
  74. err = io.EOF
  75. } else {
  76. prospectiveLen := socket.totalLength + len(data)
  77. if prospectiveLen > socket.maxSendQBytes {
  78. socket.sendQExceeded = true
  79. socket.closed = true
  80. err = errSendQExceeded
  81. } else {
  82. socket.buffers = append(socket.buffers, data)
  83. socket.totalLength = prospectiveLen
  84. }
  85. }
  86. socket.Unlock()
  87. socket.wakeWriter()
  88. return
  89. }
  90. // BlockingWrite sends the given string out of Socket. Requirements:
  91. // 1. MUST block until the message is sent
  92. // 2. MUST bypass sendq (calls to BlockingWrite cannot, on their own, cause a sendq overflow)
  93. // 3. MUST provide mutual exclusion for socket.conn.Write
  94. // 4. MUST respect the same ordering guarantees as Write (i.e., if a call to Write that sends
  95. // message m1 happens-before a call to BlockingWrite that sends message m2,
  96. // m1 must be sent on the wire before m2
  97. // Callers MUST be writing to the client's socket from the client's own goroutine;
  98. // other callers must use the nonblocking Write call instead. Otherwise, a client
  99. // with a slow/unreliable connection risks stalling the progress of the system as a whole.
  100. func (socket *Socket) BlockingWrite(data []byte) (err error) {
  101. if len(data) == 0 {
  102. return
  103. }
  104. // after releasing the semaphore, we must check for fresh data, same as `send`
  105. defer func() {
  106. if socket.readyToWrite() {
  107. socket.wakeWriter()
  108. }
  109. }()
  110. // blocking acquire of the trylock
  111. socket.writerSemaphore.Acquire()
  112. defer socket.writerSemaphore.Release()
  113. // first, flush any buffered data, to preserve the ordering guarantees
  114. closed := socket.performWrite()
  115. if closed {
  116. return io.EOF
  117. }
  118. err = socket.conn.WriteLine(data)
  119. if err != nil {
  120. socket.finalize()
  121. }
  122. return
  123. }
  124. // wakeWriter starts the goroutine that actually performs the write, without blocking
  125. func (socket *Socket) wakeWriter() {
  126. if socket.writerSemaphore.TryAcquire() {
  127. // acquired the trylock; send() will release it
  128. go socket.send()
  129. }
  130. // else: do nothing, the holder will check for more data after releasing it
  131. }
  132. // SetFinalData sets the final data to send when the SocketWriter closes.
  133. func (socket *Socket) SetFinalData(data []byte) {
  134. socket.Lock()
  135. defer socket.Unlock()
  136. socket.finalData = data
  137. }
  138. // IsClosed returns whether the socket is closed.
  139. func (socket *Socket) IsClosed() bool {
  140. socket.Lock()
  141. defer socket.Unlock()
  142. return socket.closed
  143. }
  144. // is there data to write?
  145. func (socket *Socket) readyToWrite() bool {
  146. socket.Lock()
  147. defer socket.Unlock()
  148. // on the first time observing socket.closed, we still have to write socket.finalData
  149. return !socket.finalized && (socket.totalLength > 0 || socket.closed)
  150. }
  151. // send actually writes messages to socket.Conn; it may block
  152. func (socket *Socket) send() {
  153. for {
  154. // we are holding the trylock: actually do the write
  155. socket.performWrite()
  156. // surrender the trylock, avoiding a race where a write comes in after we've
  157. // checked readyToWrite() and it returned false, but while we still hold the trylock:
  158. socket.writerSemaphore.Release()
  159. // check if more data came in while we held the trylock:
  160. if !socket.readyToWrite() {
  161. return
  162. }
  163. if !socket.writerSemaphore.TryAcquire() {
  164. // failed to acquire; exit and wait for the holder to observe readyToWrite()
  165. // after releasing it
  166. return
  167. }
  168. // got the lock again, loop back around and write
  169. }
  170. }
  171. // write the contents of the buffer, then see if we need to close
  172. // returns whether we closed
  173. func (socket *Socket) performWrite() (closed bool) {
  174. // retrieve the buffered data, clear the buffer
  175. socket.Lock()
  176. buffers := socket.buffers
  177. socket.buffers = nil
  178. socket.totalLength = 0
  179. closed = socket.closed
  180. socket.Unlock()
  181. var err error
  182. if 0 < len(buffers) {
  183. err = socket.conn.WriteLines(buffers)
  184. }
  185. closed = closed || err != nil
  186. if closed {
  187. socket.finalize()
  188. }
  189. return
  190. }
  191. // mark closed and send final data. you must be holding the semaphore to call this:
  192. func (socket *Socket) finalize() {
  193. // mark the socket closed (if someone hasn't already), then write error lines
  194. socket.Lock()
  195. socket.closed = true
  196. finalized := socket.finalized
  197. socket.finalized = true
  198. finalData := socket.finalData
  199. if socket.sendQExceeded {
  200. finalData = sendQExceededMessage
  201. }
  202. socket.Unlock()
  203. if finalized {
  204. return
  205. }
  206. if len(finalData) != 0 {
  207. socket.conn.WriteLine(finalData)
  208. }
  209. // close the connection
  210. socket.conn.Close()
  211. }