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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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. socket.closed = true
  113. err = errSendQExceeded
  114. } else {
  115. socket.buffers = append(socket.buffers, data)
  116. socket.totalLength = prospectiveLen
  117. }
  118. }
  119. socket.Unlock()
  120. socket.wakeWriter()
  121. return
  122. }
  123. // BlockingWrite sends the given string out of Socket. Requirements:
  124. // 1. MUST block until the message is sent
  125. // 2. MUST bypass sendq (calls to BlockingWrite cannot, on their own, cause a sendq overflow)
  126. // 3. MUST provide mutual exclusion for socket.conn.Write
  127. // 4. MUST respect the same ordering guarantees as Write (i.e., if a call to Write that sends
  128. // message m1 happens-before a call to BlockingWrite that sends message m2,
  129. // m1 must be sent on the wire before m2
  130. // Callers MUST be writing to the client's socket from the client's own goroutine;
  131. // other callers must use the nonblocking Write call instead. Otherwise, a client
  132. // with a slow/unreliable connection risks stalling the progress of the system as a whole.
  133. func (socket *Socket) BlockingWrite(data []byte) (err error) {
  134. if len(data) == 0 {
  135. return
  136. }
  137. // after releasing the semaphore, we must check for fresh data, same as `send`
  138. defer func() {
  139. if socket.readyToWrite() {
  140. socket.wakeWriter()
  141. }
  142. }()
  143. // blocking acquire of the trylock
  144. socket.writerSemaphore.Acquire()
  145. defer socket.writerSemaphore.Release()
  146. // first, flush any buffered data, to preserve the ordering guarantees
  147. closed := socket.performWrite()
  148. if closed {
  149. return io.EOF
  150. }
  151. _, err = socket.conn.Write(data)
  152. if err != nil {
  153. socket.finalize()
  154. }
  155. return
  156. }
  157. // wakeWriter starts the goroutine that actually performs the write, without blocking
  158. func (socket *Socket) wakeWriter() {
  159. if socket.writerSemaphore.TryAcquire() {
  160. // acquired the trylock; send() will release it
  161. go socket.send()
  162. }
  163. // else: do nothing, the holder will check for more data after releasing it
  164. }
  165. // SetFinalData sets the final data to send when the SocketWriter closes.
  166. func (socket *Socket) SetFinalData(data string) {
  167. socket.Lock()
  168. defer socket.Unlock()
  169. socket.finalData = data
  170. }
  171. // IsClosed returns whether the socket is closed.
  172. func (socket *Socket) IsClosed() bool {
  173. socket.Lock()
  174. defer socket.Unlock()
  175. return socket.closed
  176. }
  177. // is there data to write?
  178. func (socket *Socket) readyToWrite() bool {
  179. socket.Lock()
  180. defer socket.Unlock()
  181. // on the first time observing socket.closed, we still have to write socket.finalData
  182. return !socket.finalized && (socket.totalLength > 0 || socket.closed)
  183. }
  184. // send actually writes messages to socket.Conn; it may block
  185. func (socket *Socket) send() {
  186. for {
  187. // we are holding the trylock: actually do the write
  188. socket.performWrite()
  189. // surrender the trylock, avoiding a race where a write comes in after we've
  190. // checked readyToWrite() and it returned false, but while we still hold the trylock:
  191. socket.writerSemaphore.Release()
  192. // check if more data came in while we held the trylock:
  193. if !socket.readyToWrite() {
  194. return
  195. }
  196. if !socket.writerSemaphore.TryAcquire() {
  197. // failed to acquire; exit and wait for the holder to observe readyToWrite()
  198. // after releasing it
  199. return
  200. }
  201. // got the lock again, loop back around and write
  202. }
  203. }
  204. // write the contents of the buffer, then see if we need to close
  205. // returns whether we closed
  206. func (socket *Socket) performWrite() (closed bool) {
  207. // retrieve the buffered data, clear the buffer
  208. socket.Lock()
  209. buffers := socket.buffers
  210. socket.buffers = nil
  211. socket.totalLength = 0
  212. closed = socket.closed
  213. socket.Unlock()
  214. var err error
  215. if !closed && len(buffers) > 0 {
  216. // on Linux, the runtime will optimize this into a single writev(2) call:
  217. _, err = (*net.Buffers)(&buffers).WriteTo(socket.conn)
  218. }
  219. closed = closed || err != nil
  220. if closed {
  221. socket.finalize()
  222. }
  223. return
  224. }
  225. // mark closed and send final data. you must be holding the semaphore to call this:
  226. func (socket *Socket) finalize() {
  227. // mark the socket closed (if someone hasn't already), then write error lines
  228. socket.Lock()
  229. socket.closed = true
  230. finalized := socket.finalized
  231. socket.finalized = true
  232. finalData := socket.finalData
  233. if socket.sendQExceeded {
  234. finalData = "\r\nERROR :SendQ Exceeded\r\n"
  235. }
  236. socket.Unlock()
  237. if finalized {
  238. return
  239. }
  240. if finalData != "" {
  241. socket.conn.Write([]byte(finalData))
  242. }
  243. // close the connection
  244. socket.conn.Close()
  245. }