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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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. "fmt"
  12. "io"
  13. "net"
  14. "strings"
  15. "sync"
  16. "time"
  17. )
  18. var (
  19. errNotTLS = errors.New("Not a TLS connection")
  20. errNoPeerCerts = errors.New("Client did not provide a certificate")
  21. handshakeTimeout, _ = time.ParseDuration("5s")
  22. )
  23. // Socket represents an IRC socket.
  24. type Socket struct {
  25. Closed bool
  26. conn net.Conn
  27. reader *bufio.Reader
  28. MaxSendQBytes uint64
  29. lineToSendExists chan bool
  30. linesToSend []string
  31. linesToSendMutex sync.Mutex
  32. }
  33. // NewSocket returns a new Socket.
  34. func NewSocket(conn net.Conn, maxSendQBytes uint64) Socket {
  35. return Socket{
  36. conn: conn,
  37. reader: bufio.NewReader(conn),
  38. MaxSendQBytes: maxSendQBytes,
  39. lineToSendExists: make(chan bool),
  40. }
  41. }
  42. // Close stops a Socket from being able to send/receive any more data.
  43. func (socket *Socket) Close() {
  44. socket.Closed = true
  45. // 'send data' to force close loop to happen
  46. socket.linesToSendMutex.Lock()
  47. socket.linesToSend = append(socket.linesToSend, "")
  48. socket.linesToSendMutex.Unlock()
  49. go socket.fillLineToSendExists()
  50. }
  51. // CertFP returns the fingerprint of the certificate provided by the client.
  52. func (socket *Socket) CertFP() (string, error) {
  53. var tlsConn, isTLS = socket.conn.(*tls.Conn)
  54. if !isTLS {
  55. return "", errNotTLS
  56. }
  57. // ensure handehake is performed, and timeout after a few seconds
  58. tlsConn.SetDeadline(time.Now().Add(handshakeTimeout))
  59. err := tlsConn.Handshake()
  60. tlsConn.SetDeadline(time.Time{})
  61. if err != nil {
  62. return "", err
  63. }
  64. peerCerts := tlsConn.ConnectionState().PeerCertificates
  65. if len(peerCerts) < 1 {
  66. return "", errNoPeerCerts
  67. }
  68. rawCert := sha256.Sum256(peerCerts[0].Raw)
  69. fingerprint := hex.EncodeToString(rawCert[:])
  70. return fingerprint, nil
  71. }
  72. // Read returns a single IRC line from a Socket.
  73. func (socket *Socket) Read() (string, error) {
  74. if socket.Closed {
  75. return "", io.EOF
  76. }
  77. lineBytes, err := socket.reader.ReadBytes('\n')
  78. // convert bytes to string
  79. line := string(lineBytes[:])
  80. // read last message properly (such as ERROR/QUIT/etc), just fail next reads/writes
  81. if err == io.EOF {
  82. socket.Close()
  83. }
  84. if err == io.EOF && strings.TrimSpace(line) != "" {
  85. // don't do anything
  86. } else if err != nil {
  87. return "", err
  88. }
  89. return strings.TrimRight(line, "\r\n"), nil
  90. }
  91. // Write sends the given string out of Socket.
  92. func (socket *Socket) Write(data string) error {
  93. if socket.Closed {
  94. return io.EOF
  95. }
  96. socket.linesToSendMutex.Lock()
  97. socket.linesToSend = append(socket.linesToSend, data)
  98. socket.linesToSendMutex.Unlock()
  99. go socket.fillLineToSendExists()
  100. return nil
  101. }
  102. // fillLineToSendExists only exists because you can't goroutine single statements.
  103. func (socket *Socket) fillLineToSendExists() {
  104. socket.lineToSendExists <- true
  105. }
  106. // RunSocketWriter starts writing messages to the outgoing socket.
  107. func (socket *Socket) RunSocketWriter() {
  108. var errOut bool
  109. for {
  110. // wait for new lines
  111. select {
  112. case <-socket.lineToSendExists:
  113. socket.linesToSendMutex.Lock()
  114. // check sendq
  115. var sendQBytes uint64
  116. for _, line := range socket.linesToSend {
  117. sendQBytes += uint64(len(line))
  118. if socket.MaxSendQBytes < sendQBytes {
  119. break
  120. }
  121. }
  122. if socket.MaxSendQBytes < sendQBytes {
  123. socket.conn.Write([]byte("\r\nERROR :SendQ Exceeded\r\n"))
  124. fmt.Println("SendQ exceeded, disconnected client")
  125. break
  126. }
  127. // get data
  128. data := socket.linesToSend[0]
  129. if len(socket.linesToSend) > 1 {
  130. socket.linesToSend = socket.linesToSend[1:]
  131. } else {
  132. socket.linesToSend = []string{}
  133. }
  134. socket.linesToSendMutex.Unlock()
  135. // write data
  136. if 0 < len(data) {
  137. _, err := socket.conn.Write([]byte(data))
  138. if err != nil {
  139. errOut = true
  140. fmt.Println(err.Error())
  141. break
  142. }
  143. }
  144. // check if we're closed
  145. if socket.Closed {
  146. break
  147. }
  148. }
  149. if errOut {
  150. // error out, bad stuff happened
  151. break
  152. }
  153. }
  154. //TODO(dan): empty socket.lineToSendExists queue
  155. socket.conn.Close()
  156. if !socket.Closed {
  157. socket.Closed = true
  158. }
  159. }
  160. // WriteLine writes the given line out of Socket.
  161. func (socket *Socket) WriteLine(line string) error {
  162. return socket.Write(line + "\r\n")
  163. }