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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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. writerSlotOpen chan bool
  29. buffer []byte
  30. closed bool
  31. sendQExceeded bool
  32. finalData string // what to send when we die
  33. finalized bool
  34. }
  35. // NewSocket returns a new Socket.
  36. func NewSocket(conn net.Conn, maxReadQBytes int, maxSendQBytes int) *Socket {
  37. result := Socket{
  38. conn: conn,
  39. reader: bufio.NewReaderSize(conn, maxReadQBytes),
  40. maxSendQBytes: maxSendQBytes,
  41. writerSlotOpen: make(chan bool, 1),
  42. }
  43. result.writerSlotOpen <- true
  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 string) (err error) {
  102. socket.Lock()
  103. if socket.closed {
  104. err = io.EOF
  105. } else if len(data)+len(socket.buffer) > socket.maxSendQBytes {
  106. socket.sendQExceeded = true
  107. err = errSendQExceeded
  108. } else {
  109. socket.buffer = append(socket.buffer, data...)
  110. }
  111. socket.Unlock()
  112. socket.wakeWriter()
  113. return
  114. }
  115. // wakeWriter starts the goroutine that actually performs the write, without blocking
  116. func (socket *Socket) wakeWriter() {
  117. // attempt to acquire the trylock
  118. select {
  119. case <-socket.writerSlotOpen:
  120. // acquired the trylock; send() will release it
  121. go socket.send()
  122. default:
  123. // failed to acquire; the holder will check for more data after releasing it
  124. }
  125. }
  126. // SetFinalData sets the final data to send when the SocketWriter closes.
  127. func (socket *Socket) SetFinalData(data string) {
  128. socket.Lock()
  129. defer socket.Unlock()
  130. socket.finalData = data
  131. }
  132. // IsClosed returns whether the socket is closed.
  133. func (socket *Socket) IsClosed() bool {
  134. socket.Lock()
  135. defer socket.Unlock()
  136. return socket.closed
  137. }
  138. // is there data to write?
  139. func (socket *Socket) readyToWrite() bool {
  140. socket.Lock()
  141. defer socket.Unlock()
  142. // on the first time observing socket.closed, we still have to write socket.finalData
  143. return !socket.finalized && (len(socket.buffer) > 0 || socket.closed || socket.sendQExceeded)
  144. }
  145. // send actually writes messages to socket.Conn; it may block
  146. func (socket *Socket) send() {
  147. for {
  148. // we are holding the trylock: actually do the write
  149. socket.performWrite()
  150. // surrender the trylock, avoiding a race where a write comes in after we've
  151. // checked readyToWrite() and it returned false, but while we still hold the trylock:
  152. socket.writerSlotOpen <- true
  153. // check if more data came in while we held the trylock:
  154. if !socket.readyToWrite() {
  155. return
  156. }
  157. select {
  158. case <-socket.writerSlotOpen:
  159. // got the trylock, loop back around and write
  160. default:
  161. // failed to acquire; exit and wait for the holder to observe readyToWrite()
  162. // after releasing it
  163. return
  164. }
  165. }
  166. }
  167. // write the contents of the buffer, then see if we need to close
  168. func (socket *Socket) performWrite() {
  169. // retrieve the buffered data, clear the buffer
  170. socket.Lock()
  171. buffer := socket.buffer
  172. socket.buffer = nil
  173. socket.Unlock()
  174. _, err := socket.conn.Write(buffer)
  175. socket.Lock()
  176. shouldClose := (err != nil) || socket.closed || socket.sendQExceeded
  177. socket.Unlock()
  178. if !shouldClose {
  179. return
  180. }
  181. // mark the socket closed (if someone hasn't already), then write error lines
  182. socket.Lock()
  183. socket.closed = true
  184. socket.finalized = true
  185. finalData := socket.finalData
  186. if socket.sendQExceeded {
  187. finalData = "\r\nERROR :SendQ Exceeded\r\n"
  188. }
  189. socket.Unlock()
  190. if finalData != "" {
  191. socket.conn.Write([]byte(finalData))
  192. }
  193. // close the connection
  194. socket.conn.Close()
  195. }