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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. package com.dmdirc.ktirc.io
  2. import com.dmdirc.ktirc.util.logger
  3. import io.ktor.network.selector.ActorSelectorManager
  4. import io.ktor.network.sockets.Socket
  5. import io.ktor.network.sockets.aSocket
  6. import io.ktor.network.sockets.openReadChannel
  7. import io.ktor.network.sockets.openWriteChannel
  8. import io.ktor.network.tls.tls
  9. import io.ktor.util.KtorExperimentalAPI
  10. import kotlinx.coroutines.*
  11. import kotlinx.coroutines.channels.Channel
  12. import kotlinx.coroutines.channels.ReceiveChannel
  13. import kotlinx.coroutines.channels.SendChannel
  14. import kotlinx.coroutines.channels.produce
  15. import kotlinx.coroutines.io.ByteReadChannel
  16. import kotlinx.coroutines.io.ByteWriteChannel
  17. import java.net.InetSocketAddress
  18. import java.security.SecureRandom
  19. import javax.net.ssl.X509TrustManager
  20. internal interface LineBufferedSocket {
  21. fun connect()
  22. fun disconnect()
  23. val sendChannel: SendChannel<ByteArray>
  24. val receiveChannel: ReceiveChannel<ByteArray>
  25. }
  26. /**
  27. * Asynchronous socket that buffers incoming data and emits individual lines.
  28. */
  29. // TODO: Expose advanced TLS options
  30. @KtorExperimentalAPI
  31. @ExperimentalCoroutinesApi
  32. internal class KtorLineBufferedSocket(coroutineScope: CoroutineScope, private val host: String, private val port: Int, private val tls: Boolean = false) : CoroutineScope, LineBufferedSocket {
  33. companion object {
  34. const val CARRIAGE_RETURN = '\r'.toByte()
  35. const val LINE_FEED = '\n'.toByte()
  36. }
  37. override val coroutineContext = coroutineScope.newCoroutineContext(Dispatchers.IO)
  38. override val sendChannel: Channel<ByteArray> = Channel(Channel.UNLIMITED)
  39. var tlsTrustManager: X509TrustManager? = null
  40. private val log by logger()
  41. private lateinit var socket: Socket
  42. private lateinit var readChannel: ByteReadChannel
  43. private lateinit var writeChannel: ByteWriteChannel
  44. override fun connect() {
  45. runBlocking {
  46. log.info { "Connecting..." }
  47. socket = aSocket(ActorSelectorManager(Dispatchers.IO)).tcp().connect(InetSocketAddress(host, port))
  48. if (tls) {
  49. socket = socket.tls(
  50. coroutineContext = this@KtorLineBufferedSocket.coroutineContext,
  51. randomAlgorithm = SecureRandom.getInstanceStrong().algorithm,
  52. trustManager = tlsTrustManager)
  53. }
  54. readChannel = socket.openReadChannel()
  55. writeChannel = socket.openWriteChannel()
  56. }
  57. launch { writeLines() }
  58. }
  59. override fun disconnect() {
  60. log.info { "Disconnecting..." }
  61. socket.close()
  62. coroutineContext.cancel()
  63. }
  64. override val receiveChannel
  65. get() = produce {
  66. val lineBuffer = ByteArray(4096)
  67. var index = 0
  68. while (!readChannel.isClosedForRead) {
  69. var start = index
  70. val count = readChannel.readAvailable(lineBuffer, index, lineBuffer.size - index)
  71. for (i in index until index + count) {
  72. if (lineBuffer[i] == CARRIAGE_RETURN || lineBuffer[i] == LINE_FEED) {
  73. if (start < i) {
  74. val line = lineBuffer.sliceArray(start until i)
  75. log.fine { "<<< ${String(line)}" }
  76. send(line)
  77. }
  78. start = i + 1
  79. }
  80. }
  81. lineBuffer.copyInto(lineBuffer, 0, start)
  82. index = count + index - start
  83. }
  84. }
  85. private suspend fun writeLines() {
  86. for (line in sendChannel) {
  87. with(writeChannel) {
  88. log.fine { ">>> ${String(line)}" }
  89. writeAvailable(line, 0, line.size)
  90. writeByte(CARRIAGE_RETURN)
  91. writeByte(LINE_FEED)
  92. flush()
  93. }
  94. }
  95. }
  96. }