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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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. errNotTLS = errors.New("Not a TLS connection")
  19. errNoPeerCerts = errors.New("Client did not provide a certificate")
  20. handshakeTimeout, _ = time.ParseDuration("5s")
  21. )
  22. // Socket represents an IRC socket.
  23. type Socket struct {
  24. conn net.Conn
  25. reader *bufio.Reader
  26. MaxSendQBytes uint64
  27. closed bool
  28. closedMutex sync.Mutex
  29. finalData string // what to send when we die
  30. finalDataMutex sync.Mutex
  31. lineToSendExists chan bool
  32. linesToSend []string
  33. linesToSendMutex sync.Mutex
  34. }
  35. // NewSocket returns a new Socket.
  36. func NewSocket(conn net.Conn, maxSendQBytes uint64) Socket {
  37. return Socket{
  38. conn: conn,
  39. reader: bufio.NewReader(conn),
  40. MaxSendQBytes: maxSendQBytes,
  41. lineToSendExists: make(chan bool),
  42. }
  43. }
  44. // Close stops a Socket from being able to send/receive any more data.
  45. func (socket *Socket) Close() {
  46. socket.closedMutex.Lock()
  47. defer socket.closedMutex.Unlock()
  48. if socket.closed {
  49. return
  50. }
  51. socket.closed = true
  52. // force close loop to happen if it hasn't already
  53. go socket.timedFillLineToSendExists(200 * time.Millisecond)
  54. }
  55. // CertFP returns the fingerprint of the certificate provided by the client.
  56. func (socket *Socket) CertFP() (string, error) {
  57. var tlsConn, isTLS = socket.conn.(*tls.Conn)
  58. if !isTLS {
  59. return "", errNotTLS
  60. }
  61. // ensure handehake is performed, and timeout after a few seconds
  62. tlsConn.SetDeadline(time.Now().Add(handshakeTimeout))
  63. err := tlsConn.Handshake()
  64. tlsConn.SetDeadline(time.Time{})
  65. if err != nil {
  66. return "", err
  67. }
  68. peerCerts := tlsConn.ConnectionState().PeerCertificates
  69. if len(peerCerts) < 1 {
  70. return "", errNoPeerCerts
  71. }
  72. rawCert := sha256.Sum256(peerCerts[0].Raw)
  73. fingerprint := hex.EncodeToString(rawCert[:])
  74. return fingerprint, nil
  75. }
  76. // Read returns a single IRC line from a Socket.
  77. func (socket *Socket) Read() (string, error) {
  78. if socket.IsClosed() {
  79. return "", io.EOF
  80. }
  81. lineBytes, err := socket.reader.ReadBytes('\n')
  82. // convert bytes to string
  83. line := string(lineBytes[:])
  84. // read last message properly (such as ERROR/QUIT/etc), just fail next reads/writes
  85. if err == io.EOF {
  86. socket.Close()
  87. }
  88. if err == io.EOF && strings.TrimSpace(line) != "" {
  89. // don't do anything
  90. } else if err != nil {
  91. return "", err
  92. }
  93. return strings.TrimRight(line, "\r\n"), nil
  94. }
  95. // Write sends the given string out of Socket.
  96. func (socket *Socket) Write(data string) error {
  97. if socket.IsClosed() {
  98. return io.EOF
  99. }
  100. socket.linesToSendMutex.Lock()
  101. socket.linesToSend = append(socket.linesToSend, data)
  102. socket.linesToSendMutex.Unlock()
  103. go socket.timedFillLineToSendExists(15 * time.Second)
  104. return nil
  105. }
  106. // timedFillLineToSendExists either sends the note or times out.
  107. func (socket *Socket) timedFillLineToSendExists(duration time.Duration) {
  108. lineToSendTimeout := time.NewTimer(duration)
  109. defer lineToSendTimeout.Stop()
  110. select {
  111. case socket.lineToSendExists <- true:
  112. // passed data successfully
  113. case <-lineToSendTimeout.C:
  114. // timed out send
  115. }
  116. }
  117. // SetFinalData sets the final data to send when the SocketWriter closes.
  118. func (socket *Socket) SetFinalData(data string) {
  119. socket.finalDataMutex.Lock()
  120. socket.finalData = data
  121. socket.finalDataMutex.Unlock()
  122. }
  123. // IsClosed returns whether the socket is closed.
  124. func (socket *Socket) IsClosed() bool {
  125. socket.closedMutex.Lock()
  126. defer socket.closedMutex.Unlock()
  127. return socket.closed
  128. }
  129. // RunSocketWriter starts writing messages to the outgoing socket.
  130. func (socket *Socket) RunSocketWriter() {
  131. for {
  132. // wait for new lines
  133. select {
  134. case <-socket.lineToSendExists:
  135. socket.linesToSendMutex.Lock()
  136. // check if we're closed
  137. if socket.IsClosed() {
  138. socket.linesToSendMutex.Unlock()
  139. break
  140. }
  141. // check whether new lines actually exist or not
  142. if len(socket.linesToSend) < 1 {
  143. socket.linesToSendMutex.Unlock()
  144. continue
  145. }
  146. // check sendq
  147. var sendQBytes uint64
  148. for _, line := range socket.linesToSend {
  149. sendQBytes += uint64(len(line))
  150. if socket.MaxSendQBytes < sendQBytes {
  151. // don't unlock mutex because this break is just to escape this for loop
  152. break
  153. }
  154. }
  155. if socket.MaxSendQBytes < sendQBytes {
  156. socket.SetFinalData("\r\nERROR :SendQ Exceeded\r\n")
  157. socket.linesToSendMutex.Unlock()
  158. break
  159. }
  160. // get all existing data
  161. data := strings.Join(socket.linesToSend, "")
  162. socket.linesToSend = []string{}
  163. socket.linesToSendMutex.Unlock()
  164. // write data
  165. if 0 < len(data) {
  166. _, err := socket.conn.Write([]byte(data))
  167. if err != nil {
  168. break
  169. }
  170. }
  171. }
  172. if socket.IsClosed() {
  173. // error out or we've been closed
  174. break
  175. }
  176. }
  177. // force closure of socket
  178. socket.closedMutex.Lock()
  179. if !socket.closed {
  180. socket.closed = true
  181. }
  182. socket.closedMutex.Unlock()
  183. // write error lines
  184. socket.finalDataMutex.Lock()
  185. if 0 < len(socket.finalData) {
  186. socket.conn.Write([]byte(socket.finalData))
  187. }
  188. socket.finalDataMutex.Unlock()
  189. // close the connection
  190. socket.conn.Close()
  191. // empty the lineToSendExists channel
  192. for 0 < len(socket.lineToSendExists) {
  193. <-socket.lineToSendExists
  194. }
  195. }
  196. // WriteLine writes the given line out of Socket.
  197. func (socket *Socket) WriteLine(line string) error {
  198. return socket.Write(line + "\r\n")
  199. }