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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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. )
  21. // Socket represents an IRC socket.
  22. type Socket struct {
  23. sync.Mutex
  24. conn net.Conn
  25. reader *bufio.Reader
  26. maxSendQBytes int
  27. // this is a trylock enforcing that only one goroutine can write to `conn` at a time
  28. writerSemaphore Semaphore
  29. buffers [][]byte
  30. totalLength int
  31. closed bool
  32. sendQExceeded bool
  33. finalData string // what to send when we die
  34. finalized bool
  35. }
  36. // NewSocket returns a new Socket.
  37. func NewSocket(conn net.Conn, maxReadQBytes int, maxSendQBytes int) *Socket {
  38. result := Socket{
  39. conn: conn,
  40. reader: bufio.NewReaderSize(conn, maxReadQBytes),
  41. maxSendQBytes: maxSendQBytes,
  42. }
  43. result.writerSemaphore.Initialize(1)
  44. return &result
  45. }
  46. // Close stops a Socket from being able to send/receive any more data.
  47. func (socket *Socket) Close() {
  48. socket.Lock()
  49. socket.closed = true
  50. socket.Unlock()
  51. socket.wakeWriter()
  52. }
  53. // CertFP returns the fingerprint of the certificate provided by the client.
  54. func (socket *Socket) CertFP() (string, error) {
  55. var tlsConn, isTLS = socket.conn.(*tls.Conn)
  56. if !isTLS {
  57. return "", errNotTLS
  58. }
  59. // ensure handehake is performed, and timeout after a few seconds
  60. tlsConn.SetDeadline(time.Now().Add(handshakeTimeout))
  61. err := tlsConn.Handshake()
  62. tlsConn.SetDeadline(time.Time{})
  63. if err != nil {
  64. return "", err
  65. }
  66. peerCerts := tlsConn.ConnectionState().PeerCertificates
  67. if len(peerCerts) < 1 {
  68. return "", errNoPeerCerts
  69. }
  70. rawCert := sha256.Sum256(peerCerts[0].Raw)
  71. fingerprint := hex.EncodeToString(rawCert[:])
  72. return fingerprint, nil
  73. }
  74. // Read returns a single IRC line from a Socket.
  75. func (socket *Socket) Read() (string, error) {
  76. if socket.IsClosed() {
  77. return "", io.EOF
  78. }
  79. lineBytes, isPrefix, err := socket.reader.ReadLine()
  80. if isPrefix {
  81. return "", errReadQ
  82. }
  83. // convert bytes to string
  84. line := string(lineBytes)
  85. // read last message properly (such as ERROR/QUIT/etc), just fail next reads/writes
  86. if err == io.EOF {
  87. socket.Close()
  88. }
  89. if err == io.EOF && strings.TrimSpace(line) != "" {
  90. // don't do anything
  91. } else if err != nil {
  92. return "", err
  93. }
  94. return line, nil
  95. }
  96. // Write sends the given string out of Socket. Requirements:
  97. // 1. MUST NOT block for macroscopic amounts of time
  98. // 2. MUST NOT reorder messages
  99. // 3. MUST provide mutual exclusion for socket.conn.Write
  100. // 4. SHOULD NOT tie up additional goroutines, beyond the one blocked on socket.conn.Write
  101. func (socket *Socket) Write(data []byte) (err error) {
  102. if len(data) == 0 {
  103. return
  104. }
  105. socket.Lock()
  106. if socket.closed {
  107. err = io.EOF
  108. } else {
  109. prospectiveLen := socket.totalLength + len(data)
  110. if prospectiveLen > socket.maxSendQBytes {
  111. socket.sendQExceeded = true
  112. err = errSendQExceeded
  113. } else {
  114. socket.buffers = append(socket.buffers, data)
  115. socket.totalLength = prospectiveLen
  116. }
  117. }
  118. socket.Unlock()
  119. socket.wakeWriter()
  120. return
  121. }
  122. // wakeWriter starts the goroutine that actually performs the write, without blocking
  123. func (socket *Socket) wakeWriter() {
  124. if socket.writerSemaphore.TryAcquire() {
  125. // acquired the trylock; send() will release it
  126. go socket.send()
  127. }
  128. // else: do nothing, the holder will check for more data after releasing it
  129. }
  130. // SetFinalData sets the final data to send when the SocketWriter closes.
  131. func (socket *Socket) SetFinalData(data string) {
  132. socket.Lock()
  133. defer socket.Unlock()
  134. socket.finalData = data
  135. }
  136. // IsClosed returns whether the socket is closed.
  137. func (socket *Socket) IsClosed() bool {
  138. socket.Lock()
  139. defer socket.Unlock()
  140. return socket.closed
  141. }
  142. // is there data to write?
  143. func (socket *Socket) readyToWrite() bool {
  144. socket.Lock()
  145. defer socket.Unlock()
  146. // on the first time observing socket.closed, we still have to write socket.finalData
  147. return !socket.finalized && (socket.totalLength > 0 || socket.closed || socket.sendQExceeded)
  148. }
  149. // send actually writes messages to socket.Conn; it may block
  150. func (socket *Socket) send() {
  151. for {
  152. // we are holding the trylock: actually do the write
  153. socket.performWrite()
  154. // surrender the trylock, avoiding a race where a write comes in after we've
  155. // checked readyToWrite() and it returned false, but while we still hold the trylock:
  156. socket.writerSemaphore.Release()
  157. // check if more data came in while we held the trylock:
  158. if !socket.readyToWrite() {
  159. return
  160. }
  161. if !socket.writerSemaphore.TryAcquire() {
  162. // failed to acquire; exit and wait for the holder to observe readyToWrite()
  163. // after releasing it
  164. return
  165. }
  166. // got the lock again, loop back around and write
  167. }
  168. }
  169. // write the contents of the buffer, then see if we need to close
  170. func (socket *Socket) performWrite() {
  171. // retrieve the buffered data, clear the buffer
  172. socket.Lock()
  173. buffers := socket.buffers
  174. socket.buffers = nil
  175. socket.totalLength = 0
  176. socket.Unlock()
  177. // on Linux, the runtime will optimize this into a single writev(2) call:
  178. _, err := (*net.Buffers)(&buffers).WriteTo(socket.conn)
  179. socket.Lock()
  180. shouldClose := (err != nil) || socket.closed || socket.sendQExceeded
  181. socket.Unlock()
  182. if !shouldClose {
  183. return
  184. }
  185. // mark the socket closed (if someone hasn't already), then write error lines
  186. socket.Lock()
  187. socket.closed = true
  188. socket.finalized = true
  189. finalData := socket.finalData
  190. if socket.sendQExceeded {
  191. finalData = "\r\nERROR :SendQ Exceeded\r\n"
  192. }
  193. socket.Unlock()
  194. if finalData != "" {
  195. socket.conn.Write([]byte(finalData))
  196. }
  197. // close the connection
  198. socket.conn.Close()
  199. }