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 7.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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. "bufio"
  7. "crypto/sha256"
  8. "crypto/tls"
  9. "encoding/hex"
  10. "errors"
  11. "io"
  12. "net"
  13. "strings"
  14. "sync"
  15. "time"
  16. )
  17. var (
  18. handshakeTimeout, _ = time.ParseDuration("5s")
  19. errSendQExceeded = errors.New("SendQ exceeded")
  20. sendQExceededMessage = []byte("\r\nERROR :SendQ Exceeded\r\n")
  21. )
  22. // Socket represents an IRC socket.
  23. type Socket struct {
  24. sync.Mutex
  25. conn net.Conn
  26. reader *bufio.Reader
  27. maxSendQBytes int
  28. // this is a trylock enforcing that only one goroutine can write to `conn` at a time
  29. writerSemaphore Semaphore
  30. buffers [][]byte
  31. totalLength int
  32. closed bool
  33. sendQExceeded bool
  34. finalData []byte // what to send when we die
  35. finalized bool
  36. }
  37. // NewSocket returns a new Socket.
  38. func NewSocket(conn net.Conn, maxReadQBytes int, maxSendQBytes int) *Socket {
  39. result := Socket{
  40. conn: conn,
  41. reader: bufio.NewReaderSize(conn, maxReadQBytes),
  42. maxSendQBytes: maxSendQBytes,
  43. }
  44. result.writerSemaphore.Initialize(1)
  45. return &result
  46. }
  47. // Close stops a Socket from being able to send/receive any more data.
  48. func (socket *Socket) Close() {
  49. socket.Lock()
  50. socket.closed = true
  51. socket.Unlock()
  52. socket.wakeWriter()
  53. }
  54. // CertFP returns the fingerprint of the certificate provided by the client.
  55. func (socket *Socket) CertFP() (string, error) {
  56. var tlsConn, isTLS = socket.conn.(*tls.Conn)
  57. if !isTLS {
  58. return "", errNotTLS
  59. }
  60. // ensure handehake is performed, and timeout after a few seconds
  61. tlsConn.SetDeadline(time.Now().Add(handshakeTimeout))
  62. err := tlsConn.Handshake()
  63. tlsConn.SetDeadline(time.Time{})
  64. if err != nil {
  65. return "", err
  66. }
  67. peerCerts := tlsConn.ConnectionState().PeerCertificates
  68. if len(peerCerts) < 1 {
  69. return "", errNoPeerCerts
  70. }
  71. rawCert := sha256.Sum256(peerCerts[0].Raw)
  72. fingerprint := hex.EncodeToString(rawCert[:])
  73. return fingerprint, nil
  74. }
  75. // Read returns a single IRC line from a Socket.
  76. func (socket *Socket) Read() (string, error) {
  77. if socket.IsClosed() {
  78. return "", io.EOF
  79. }
  80. lineBytes, isPrefix, err := socket.reader.ReadLine()
  81. if isPrefix {
  82. return "", errReadQ
  83. }
  84. // convert bytes to string
  85. line := string(lineBytes)
  86. // read last message properly (such as ERROR/QUIT/etc), just fail next reads/writes
  87. if err == io.EOF {
  88. socket.Close()
  89. }
  90. if err == io.EOF && strings.TrimSpace(line) != "" {
  91. // don't do anything
  92. } else if err != nil {
  93. return "", err
  94. }
  95. return line, nil
  96. }
  97. // Write sends the given string out of Socket. Requirements:
  98. // 1. MUST NOT block for macroscopic amounts of time
  99. // 2. MUST NOT reorder messages
  100. // 3. MUST provide mutual exclusion for socket.conn.Write
  101. // 4. SHOULD NOT tie up additional goroutines, beyond the one blocked on socket.conn.Write
  102. func (socket *Socket) Write(data []byte) (err error) {
  103. if len(data) == 0 {
  104. return
  105. }
  106. socket.Lock()
  107. if socket.closed {
  108. err = io.EOF
  109. } else {
  110. prospectiveLen := socket.totalLength + len(data)
  111. if prospectiveLen > socket.maxSendQBytes {
  112. socket.sendQExceeded = true
  113. socket.closed = true
  114. err = errSendQExceeded
  115. } else {
  116. socket.buffers = append(socket.buffers, data)
  117. socket.totalLength = prospectiveLen
  118. }
  119. }
  120. socket.Unlock()
  121. socket.wakeWriter()
  122. return
  123. }
  124. // BlockingWrite sends the given string out of Socket. Requirements:
  125. // 1. MUST block until the message is sent
  126. // 2. MUST bypass sendq (calls to BlockingWrite cannot, on their own, cause a sendq overflow)
  127. // 3. MUST provide mutual exclusion for socket.conn.Write
  128. // 4. MUST respect the same ordering guarantees as Write (i.e., if a call to Write that sends
  129. // message m1 happens-before a call to BlockingWrite that sends message m2,
  130. // m1 must be sent on the wire before m2
  131. // Callers MUST be writing to the client's socket from the client's own goroutine;
  132. // other callers must use the nonblocking Write call instead. Otherwise, a client
  133. // with a slow/unreliable connection risks stalling the progress of the system as a whole.
  134. func (socket *Socket) BlockingWrite(data []byte) (err error) {
  135. if len(data) == 0 {
  136. return
  137. }
  138. // after releasing the semaphore, we must check for fresh data, same as `send`
  139. defer func() {
  140. if socket.readyToWrite() {
  141. socket.wakeWriter()
  142. }
  143. }()
  144. // blocking acquire of the trylock
  145. socket.writerSemaphore.Acquire()
  146. defer socket.writerSemaphore.Release()
  147. // first, flush any buffered data, to preserve the ordering guarantees
  148. closed := socket.performWrite()
  149. if closed {
  150. return io.EOF
  151. }
  152. _, err = socket.conn.Write(data)
  153. if err != nil {
  154. socket.finalize()
  155. }
  156. return
  157. }
  158. // wakeWriter starts the goroutine that actually performs the write, without blocking
  159. func (socket *Socket) wakeWriter() {
  160. if socket.writerSemaphore.TryAcquire() {
  161. // acquired the trylock; send() will release it
  162. go socket.send()
  163. }
  164. // else: do nothing, the holder will check for more data after releasing it
  165. }
  166. // SetFinalData sets the final data to send when the SocketWriter closes.
  167. func (socket *Socket) SetFinalData(data []byte) {
  168. socket.Lock()
  169. defer socket.Unlock()
  170. socket.finalData = data
  171. }
  172. // IsClosed returns whether the socket is closed.
  173. func (socket *Socket) IsClosed() bool {
  174. socket.Lock()
  175. defer socket.Unlock()
  176. return socket.closed
  177. }
  178. // is there data to write?
  179. func (socket *Socket) readyToWrite() bool {
  180. socket.Lock()
  181. defer socket.Unlock()
  182. // on the first time observing socket.closed, we still have to write socket.finalData
  183. return !socket.finalized && (socket.totalLength > 0 || socket.closed)
  184. }
  185. // send actually writes messages to socket.Conn; it may block
  186. func (socket *Socket) send() {
  187. for {
  188. // we are holding the trylock: actually do the write
  189. socket.performWrite()
  190. // surrender the trylock, avoiding a race where a write comes in after we've
  191. // checked readyToWrite() and it returned false, but while we still hold the trylock:
  192. socket.writerSemaphore.Release()
  193. // check if more data came in while we held the trylock:
  194. if !socket.readyToWrite() {
  195. return
  196. }
  197. if !socket.writerSemaphore.TryAcquire() {
  198. // failed to acquire; exit and wait for the holder to observe readyToWrite()
  199. // after releasing it
  200. return
  201. }
  202. // got the lock again, loop back around and write
  203. }
  204. }
  205. // write the contents of the buffer, then see if we need to close
  206. // returns whether we closed
  207. func (socket *Socket) performWrite() (closed bool) {
  208. // retrieve the buffered data, clear the buffer
  209. socket.Lock()
  210. buffers := socket.buffers
  211. socket.buffers = nil
  212. socket.totalLength = 0
  213. closed = socket.closed
  214. socket.Unlock()
  215. var err error
  216. if !closed && len(buffers) > 0 {
  217. // on Linux, the runtime will optimize this into a single writev(2) call:
  218. _, err = (*net.Buffers)(&buffers).WriteTo(socket.conn)
  219. }
  220. closed = closed || err != nil
  221. if closed {
  222. socket.finalize()
  223. }
  224. return
  225. }
  226. // mark closed and send final data. you must be holding the semaphore to call this:
  227. func (socket *Socket) finalize() {
  228. // mark the socket closed (if someone hasn't already), then write error lines
  229. socket.Lock()
  230. socket.closed = true
  231. finalized := socket.finalized
  232. socket.finalized = true
  233. finalData := socket.finalData
  234. if socket.sendQExceeded {
  235. finalData = sendQExceededMessage
  236. }
  237. socket.Unlock()
  238. if finalized {
  239. return
  240. }
  241. if len(finalData) != 0 {
  242. socket.conn.Write(finalData)
  243. }
  244. // close the connection
  245. socket.conn.Close()
  246. }