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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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. "github.com/oragono/oragono/irc/utils"
  17. )
  18. var (
  19. handshakeTimeout = RegisterTimeout
  20. errSendQExceeded = errors.New("SendQ exceeded")
  21. sendQExceededMessage = []byte("\r\nERROR :SendQ Exceeded\r\n")
  22. )
  23. // Socket represents an IRC socket.
  24. type Socket struct {
  25. sync.Mutex
  26. conn net.Conn
  27. reader *bufio.Reader
  28. maxSendQBytes int
  29. // this is a trylock enforcing that only one goroutine can write to `conn` at a time
  30. writerSemaphore utils.Semaphore
  31. buffers [][]byte
  32. totalLength int
  33. closed bool
  34. sendQExceeded bool
  35. finalData []byte // what to send when we die
  36. finalized bool
  37. }
  38. // NewSocket returns a new Socket.
  39. func NewSocket(conn net.Conn, maxReadQBytes int, maxSendQBytes int) *Socket {
  40. result := Socket{
  41. conn: conn,
  42. reader: bufio.NewReaderSize(conn, maxReadQBytes),
  43. maxSendQBytes: maxSendQBytes,
  44. }
  45. result.writerSemaphore.Initialize(1)
  46. return &result
  47. }
  48. // Close stops a Socket from being able to send/receive any more data.
  49. func (socket *Socket) Close() {
  50. socket.Lock()
  51. socket.closed = true
  52. socket.Unlock()
  53. socket.wakeWriter()
  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, isPrefix, err := socket.reader.ReadLine()
  82. if isPrefix {
  83. return "", errReadQ
  84. }
  85. // convert bytes to string
  86. line := string(lineBytes)
  87. // read last message properly (such as ERROR/QUIT/etc), just fail next reads/writes
  88. if err == io.EOF {
  89. socket.Close()
  90. }
  91. if err == io.EOF && strings.TrimSpace(line) != "" {
  92. // don't do anything
  93. } else if err != nil {
  94. return "", err
  95. }
  96. return line, nil
  97. }
  98. // Write sends the given string out of Socket. Requirements:
  99. // 1. MUST NOT block for macroscopic amounts of time
  100. // 2. MUST NOT reorder messages
  101. // 3. MUST provide mutual exclusion for socket.conn.Write
  102. // 4. SHOULD NOT tie up additional goroutines, beyond the one blocked on socket.conn.Write
  103. func (socket *Socket) Write(data []byte) (err error) {
  104. if len(data) == 0 {
  105. return
  106. }
  107. socket.Lock()
  108. if socket.closed {
  109. err = io.EOF
  110. } else {
  111. prospectiveLen := socket.totalLength + len(data)
  112. if prospectiveLen > socket.maxSendQBytes {
  113. socket.sendQExceeded = true
  114. socket.closed = true
  115. err = errSendQExceeded
  116. } else {
  117. socket.buffers = append(socket.buffers, data)
  118. socket.totalLength = prospectiveLen
  119. }
  120. }
  121. socket.Unlock()
  122. socket.wakeWriter()
  123. return
  124. }
  125. // BlockingWrite sends the given string out of Socket. Requirements:
  126. // 1. MUST block until the message is sent
  127. // 2. MUST bypass sendq (calls to BlockingWrite cannot, on their own, cause a sendq overflow)
  128. // 3. MUST provide mutual exclusion for socket.conn.Write
  129. // 4. MUST respect the same ordering guarantees as Write (i.e., if a call to Write that sends
  130. // message m1 happens-before a call to BlockingWrite that sends message m2,
  131. // m1 must be sent on the wire before m2
  132. // Callers MUST be writing to the client's socket from the client's own goroutine;
  133. // other callers must use the nonblocking Write call instead. Otherwise, a client
  134. // with a slow/unreliable connection risks stalling the progress of the system as a whole.
  135. func (socket *Socket) BlockingWrite(data []byte) (err error) {
  136. if len(data) == 0 {
  137. return
  138. }
  139. // after releasing the semaphore, we must check for fresh data, same as `send`
  140. defer func() {
  141. if socket.readyToWrite() {
  142. socket.wakeWriter()
  143. }
  144. }()
  145. // blocking acquire of the trylock
  146. socket.writerSemaphore.Acquire()
  147. defer socket.writerSemaphore.Release()
  148. // first, flush any buffered data, to preserve the ordering guarantees
  149. closed := socket.performWrite()
  150. if closed {
  151. return io.EOF
  152. }
  153. _, err = socket.conn.Write(data)
  154. if err != nil {
  155. socket.finalize()
  156. }
  157. return
  158. }
  159. // wakeWriter starts the goroutine that actually performs the write, without blocking
  160. func (socket *Socket) wakeWriter() {
  161. if socket.writerSemaphore.TryAcquire() {
  162. // acquired the trylock; send() will release it
  163. go socket.send()
  164. }
  165. // else: do nothing, the holder will check for more data after releasing it
  166. }
  167. // SetFinalData sets the final data to send when the SocketWriter closes.
  168. func (socket *Socket) SetFinalData(data []byte) {
  169. socket.Lock()
  170. defer socket.Unlock()
  171. socket.finalData = data
  172. }
  173. // IsClosed returns whether the socket is closed.
  174. func (socket *Socket) IsClosed() bool {
  175. socket.Lock()
  176. defer socket.Unlock()
  177. return socket.closed
  178. }
  179. // is there data to write?
  180. func (socket *Socket) readyToWrite() bool {
  181. socket.Lock()
  182. defer socket.Unlock()
  183. // on the first time observing socket.closed, we still have to write socket.finalData
  184. return !socket.finalized && (socket.totalLength > 0 || socket.closed)
  185. }
  186. // send actually writes messages to socket.Conn; it may block
  187. func (socket *Socket) send() {
  188. for {
  189. // we are holding the trylock: actually do the write
  190. socket.performWrite()
  191. // surrender the trylock, avoiding a race where a write comes in after we've
  192. // checked readyToWrite() and it returned false, but while we still hold the trylock:
  193. socket.writerSemaphore.Release()
  194. // check if more data came in while we held the trylock:
  195. if !socket.readyToWrite() {
  196. return
  197. }
  198. if !socket.writerSemaphore.TryAcquire() {
  199. // failed to acquire; exit and wait for the holder to observe readyToWrite()
  200. // after releasing it
  201. return
  202. }
  203. // got the lock again, loop back around and write
  204. }
  205. }
  206. // write the contents of the buffer, then see if we need to close
  207. // returns whether we closed
  208. func (socket *Socket) performWrite() (closed bool) {
  209. // retrieve the buffered data, clear the buffer
  210. socket.Lock()
  211. buffers := socket.buffers
  212. socket.buffers = nil
  213. socket.totalLength = 0
  214. closed = socket.closed
  215. socket.Unlock()
  216. var err error
  217. if 0 < len(buffers) {
  218. // on Linux, the runtime will optimize this into a single writev(2) call:
  219. _, err = (*net.Buffers)(&buffers).WriteTo(socket.conn)
  220. }
  221. closed = closed || err != nil
  222. if closed {
  223. socket.finalize()
  224. }
  225. return
  226. }
  227. // mark closed and send final data. you must be holding the semaphore to call this:
  228. func (socket *Socket) finalize() {
  229. // mark the socket closed (if someone hasn't already), then write error lines
  230. socket.Lock()
  231. socket.closed = true
  232. finalized := socket.finalized
  233. socket.finalized = true
  234. finalData := socket.finalData
  235. if socket.sendQExceeded {
  236. finalData = sendQExceededMessage
  237. }
  238. socket.Unlock()
  239. if finalized {
  240. return
  241. }
  242. if len(finalData) != 0 {
  243. socket.conn.Write(finalData)
  244. }
  245. // close the connection
  246. socket.conn.Close()
  247. }