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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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. // coordination system for asynchronous writes
  28. buffer []byte
  29. lineToSendExists chan bool
  30. closed bool
  31. sendQExceeded bool
  32. finalData string // what to send when we die
  33. }
  34. // NewSocket returns a new Socket.
  35. func NewSocket(conn net.Conn, maxReadQBytes int, maxSendQBytes int) Socket {
  36. return Socket{
  37. conn: conn,
  38. reader: bufio.NewReaderSize(conn, maxReadQBytes),
  39. maxSendQBytes: maxSendQBytes,
  40. lineToSendExists: make(chan bool, 1),
  41. }
  42. }
  43. // Close stops a Socket from being able to send/receive any more data.
  44. func (socket *Socket) Close() {
  45. socket.Lock()
  46. socket.closed = true
  47. socket.Unlock()
  48. socket.wakeWriter()
  49. }
  50. // CertFP returns the fingerprint of the certificate provided by the client.
  51. func (socket *Socket) CertFP() (string, error) {
  52. var tlsConn, isTLS = socket.conn.(*tls.Conn)
  53. if !isTLS {
  54. return "", errNotTLS
  55. }
  56. // ensure handehake is performed, and timeout after a few seconds
  57. tlsConn.SetDeadline(time.Now().Add(handshakeTimeout))
  58. err := tlsConn.Handshake()
  59. tlsConn.SetDeadline(time.Time{})
  60. if err != nil {
  61. return "", err
  62. }
  63. peerCerts := tlsConn.ConnectionState().PeerCertificates
  64. if len(peerCerts) < 1 {
  65. return "", errNoPeerCerts
  66. }
  67. rawCert := sha256.Sum256(peerCerts[0].Raw)
  68. fingerprint := hex.EncodeToString(rawCert[:])
  69. return fingerprint, nil
  70. }
  71. // Read returns a single IRC line from a Socket.
  72. func (socket *Socket) Read() (string, error) {
  73. if socket.IsClosed() {
  74. return "", io.EOF
  75. }
  76. lineBytes, isPrefix, err := socket.reader.ReadLine()
  77. if isPrefix {
  78. return "", errReadQ
  79. }
  80. // convert bytes to string
  81. line := string(lineBytes)
  82. // read last message properly (such as ERROR/QUIT/etc), just fail next reads/writes
  83. if err == io.EOF {
  84. socket.Close()
  85. }
  86. if err == io.EOF && strings.TrimSpace(line) != "" {
  87. // don't do anything
  88. } else if err != nil {
  89. return "", err
  90. }
  91. return line, nil
  92. }
  93. // Write sends the given string out of Socket.
  94. func (socket *Socket) Write(data string) (err error) {
  95. socket.Lock()
  96. if socket.closed {
  97. err = io.EOF
  98. } else if len(data)+len(socket.buffer) > socket.maxSendQBytes {
  99. socket.sendQExceeded = true
  100. err = errSendQExceeded
  101. } else {
  102. socket.buffer = append(socket.buffer, data...)
  103. }
  104. socket.Unlock()
  105. socket.wakeWriter()
  106. return
  107. }
  108. // wakeWriter wakes up the goroutine that actually performs the write, without blocking
  109. func (socket *Socket) wakeWriter() {
  110. // nonblocking send to the channel, no-op if it's full
  111. select {
  112. case socket.lineToSendExists <- true:
  113. default:
  114. }
  115. }
  116. // SetFinalData sets the final data to send when the SocketWriter closes.
  117. func (socket *Socket) SetFinalData(data string) {
  118. socket.Lock()
  119. defer socket.Unlock()
  120. socket.finalData = data
  121. }
  122. // IsClosed returns whether the socket is closed.
  123. func (socket *Socket) IsClosed() bool {
  124. socket.Lock()
  125. defer socket.Unlock()
  126. return socket.closed
  127. }
  128. // RunSocketWriter starts writing messages to the outgoing socket.
  129. func (socket *Socket) RunSocketWriter() {
  130. localBuffer := make([]byte, 0)
  131. shouldStop := false
  132. for !shouldStop {
  133. // wait for new lines
  134. select {
  135. case <-socket.lineToSendExists:
  136. // retrieve the buffered data, clear the buffer
  137. socket.Lock()
  138. localBuffer = append(localBuffer, socket.buffer...)
  139. socket.buffer = socket.buffer[:0]
  140. socket.Unlock()
  141. _, err := socket.conn.Write(localBuffer)
  142. localBuffer = localBuffer[:0]
  143. socket.Lock()
  144. shouldStop = (err != nil) || socket.closed || socket.sendQExceeded
  145. socket.Unlock()
  146. }
  147. }
  148. // mark the socket closed (if someone hasn't already), then write error lines
  149. socket.Lock()
  150. socket.closed = true
  151. finalData := socket.finalData
  152. if socket.sendQExceeded {
  153. finalData = "\r\nERROR :SendQ Exceeded\r\n"
  154. }
  155. socket.Unlock()
  156. if finalData != "" {
  157. socket.conn.Write([]byte(finalData))
  158. }
  159. // close the connection
  160. socket.conn.Close()
  161. }