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.

LineBufferedSocket.kt 3.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package com.dmdirc.ktirc.io
  2. import com.dmdirc.ktirc.util.logger
  3. import kotlinx.coroutines.*
  4. import kotlinx.coroutines.channels.Channel
  5. import kotlinx.coroutines.channels.ReceiveChannel
  6. import kotlinx.coroutines.channels.SendChannel
  7. import kotlinx.coroutines.channels.produce
  8. import kotlinx.coroutines.io.ByteWriteChannel
  9. import java.net.InetSocketAddress
  10. import java.nio.ByteBuffer
  11. import java.security.SecureRandom
  12. import java.security.cert.CertificateException
  13. import javax.net.ssl.SSLContext
  14. import javax.net.ssl.X509TrustManager
  15. internal interface LineBufferedSocket {
  16. @Throws(CertificateException::class)
  17. fun connect()
  18. fun disconnect()
  19. val sendChannel: SendChannel<ByteArray>
  20. val receiveChannel: ReceiveChannel<ByteArray>
  21. }
  22. /**
  23. * Asynchronous socket that buffers incoming data and emits individual lines.
  24. */
  25. // TODO: Expose advanced TLS options
  26. @ExperimentalCoroutinesApi
  27. internal class LineBufferedSocketImpl(coroutineScope: CoroutineScope, private val host: String, private val ip: String, private val port: Int, private val tls: Boolean = false) : CoroutineScope, LineBufferedSocket {
  28. companion object {
  29. const val CARRIAGE_RETURN = '\r'.toByte()
  30. const val LINE_FEED = '\n'.toByte()
  31. }
  32. override val coroutineContext = coroutineScope.newCoroutineContext(Dispatchers.IO)
  33. override val sendChannel: Channel<ByteArray> = Channel(Channel.UNLIMITED)
  34. var tlsTrustManager: X509TrustManager? = null
  35. private val log by logger()
  36. private lateinit var socket: Socket
  37. private lateinit var writeChannel: ByteWriteChannel
  38. override fun connect() {
  39. log.info { "Connecting..." }
  40. socket = PlainTextSocket(this)
  41. runBlocking {
  42. if (tls) {
  43. with (SSLContext.getInstance("TLSv1.2")) {
  44. init(null, tlsTrustManager?.let { arrayOf(it) }, SecureRandom.getInstanceStrong())
  45. socket = TlsSocket(this@LineBufferedSocketImpl, socket, this, host)
  46. }
  47. }
  48. socket.connect(InetSocketAddress(ip, port))
  49. writeChannel = socket.write
  50. }
  51. launch { writeLines() }
  52. }
  53. override fun disconnect() {
  54. log.info { "Disconnecting..." }
  55. socket.close()
  56. coroutineContext.cancel()
  57. }
  58. override val receiveChannel
  59. get() = produce {
  60. val lineBuffer = ByteArray(16384)
  61. var nextByteOffset = 0
  62. while (socket.isOpen) {
  63. var lineStart = 0
  64. val bytesRead = socket.read(ByteBuffer.wrap(lineBuffer).apply { position(nextByteOffset) })
  65. for (i in nextByteOffset until nextByteOffset + bytesRead) {
  66. if (lineBuffer[i] == CARRIAGE_RETURN || lineBuffer[i] == LINE_FEED) {
  67. if (lineStart < i) {
  68. val line = lineBuffer.sliceArray(lineStart until i)
  69. log.fine { "<<< ${String(line)}" }
  70. send(line)
  71. }
  72. lineStart = i + 1
  73. }
  74. }
  75. lineBuffer.copyInto(lineBuffer, 0, lineStart)
  76. nextByteOffset += bytesRead - lineStart
  77. }
  78. }
  79. private suspend fun writeLines() {
  80. for (line in sendChannel) {
  81. with(writeChannel) {
  82. log.fine { ">>> ${String(line)}" }
  83. writeAvailable(line, 0, line.size)
  84. writeByte(CARRIAGE_RETURN)
  85. writeByte(LINE_FEED)
  86. flush()
  87. }
  88. }
  89. }
  90. }