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.

ServerState.kt 8.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. package com.dmdirc.ktirc.model
  2. import com.dmdirc.ktirc.SaslConfig
  3. import com.dmdirc.ktirc.events.EventMetadata
  4. import com.dmdirc.ktirc.events.IrcEvent
  5. import com.dmdirc.ktirc.io.CaseMapping
  6. import com.dmdirc.ktirc.util.logger
  7. import kotlinx.coroutines.channels.SendChannel
  8. import java.util.concurrent.atomic.AtomicLong
  9. import kotlin.reflect.KClass
  10. /**
  11. * Contains the current state of a single IRC server.
  12. */
  13. class ServerState internal constructor(
  14. private val initialNickname: String,
  15. private val initialServerName: String,
  16. saslConfig: SaslConfig? = null) {
  17. private val log by logger()
  18. /** Whether we've received the 'Welcome to IRC' (001) message. */
  19. internal var receivedWelcome = false
  20. /** The current status of the server. */
  21. var status = ServerStatus.Disconnected
  22. internal set
  23. /**
  24. * What we believe our current nickname to be on the server.
  25. *
  26. * Initially this will be the nickname provided in the config. It will be updated to the actual nickname
  27. * in use when connecting. Once you have received a [com.dmdirc.ktirc.events.ServerWelcome] event you can
  28. * rely on this value being current.
  29. * */
  30. var localNickname: String = initialNickname
  31. internal set
  32. /**
  33. * The name of the server we are connected to.
  34. *
  35. * Initially this will be the hostname or IP address provided in the config. It will be updated to the server's
  36. * self-reported hostname when connecting. Once you have received a [com.dmdirc.ktirc.events.ServerWelcome] event
  37. * you can rely on this value being current.
  38. */
  39. var serverName: String = initialServerName
  40. internal set
  41. /** The features that the server has declared it supports (from the 005 header). */
  42. val features = ServerFeatureMap()
  43. /** The capabilities we have negotiated with the server (from IRCv3). */
  44. val capabilities = CapabilitiesState()
  45. /** The current state of SASL authentication. */
  46. internal val sasl = SaslState(saslConfig)
  47. /**
  48. * Convenience accessor for the [ServerFeature.ModePrefixes] feature, which will always have a value.
  49. */
  50. val channelModePrefixes
  51. get() = features[ServerFeature.ModePrefixes] ?: throw IllegalStateException("lost mode prefixes")
  52. /**
  53. * Convenience accessor for the [ServerFeature.ChannelTypes] feature, which will always have a value.
  54. */
  55. val channelTypes
  56. get() = features[ServerFeature.ChannelTypes] ?: throw IllegalStateException("lost channel types")
  57. /**
  58. * Batches that are currently in progress.
  59. */
  60. internal val batches = mutableMapOf<String, Batch>()
  61. /**
  62. * Counter for ensuring sent labels are unique.
  63. */
  64. internal val labelCounter = AtomicLong(0)
  65. /**
  66. * Whether or not the server supports labeled responses.
  67. */
  68. internal val supportsLabeledResponses: Boolean
  69. get() = Capability.LabeledResponse in capabilities.enabledCapabilities
  70. /**
  71. * Channels waiting for a label to be received.
  72. */
  73. internal val labelChannels = mutableMapOf<String, SendChannel<IrcEvent>>()
  74. /**
  75. * Determines if the given mode is one applied to a user of a channel, such as 'o' for operator.
  76. */
  77. fun isChannelUserMode(mode: Char) = channelModePrefixes.isMode(mode)
  78. /**
  79. * Determines what type of channel mode the given character is, based on the server features.
  80. *
  81. * If the mode isn't found, or the server hasn't provided modes, it is presumed to be [ChannelModeType.NoParameter].
  82. */
  83. fun channelModeType(mode: Char): ChannelModeType {
  84. features[ServerFeature.ChannelModes]?.forEachIndexed { index, modes ->
  85. if (mode in modes) {
  86. return ChannelModeType.values()[index]
  87. }
  88. }
  89. log.warning { "Unknown channel mode $mode, assuming it's boolean" }
  90. return ChannelModeType.NoParameter
  91. }
  92. internal fun reset() {
  93. receivedWelcome = false
  94. status = ServerStatus.Disconnected
  95. localNickname = initialNickname
  96. serverName = initialServerName
  97. features.clear()
  98. capabilities.reset()
  99. sasl.reset()
  100. batches.clear()
  101. labelCounter.set(0)
  102. labelChannels.clear()
  103. }
  104. }
  105. /**
  106. * Maps known features onto their values, enforcing type safety.
  107. */
  108. class ServerFeatureMap {
  109. private val features = HashMap<ServerFeature<*>, Any?>()
  110. /**
  111. * Gets the value, or the default value, of the given feature.
  112. */
  113. @Suppress("UNCHECKED_CAST")
  114. operator fun <T : Any> get(feature: ServerFeature<T>) = features.getOrDefault(feature, feature.default) as? T?
  115. ?: feature.default
  116. internal operator fun set(feature: ServerFeature<*>, value: Any) {
  117. require(feature.type.isInstance(value)) {
  118. "Value given for feature ${feature::class} must be type ${feature.type} but was ${value::class}"
  119. }
  120. features[feature] = value
  121. }
  122. internal fun setAll(featureMap: ServerFeatureMap) = featureMap.features.forEach { feature, value -> features[feature] = value }
  123. internal fun reset(feature: ServerFeature<*>) = features.put(feature, null)
  124. internal fun clear() = features.clear()
  125. internal fun isEmpty() = features.isEmpty()
  126. }
  127. /**
  128. * Stores the mapping of mode prefixes received from the server.
  129. */
  130. data class ModePrefixMapping(val modes: String, val prefixes: String) {
  131. /** Determines whether the given character is a mode prefix (e.g. "@", "+"). */
  132. fun isPrefix(char: Char) = prefixes.contains(char)
  133. /** Determines whether the given character is a channel user mode (e.g. "o", "v"). */
  134. fun isMode(char: Char) = modes.contains(char)
  135. /** Gets the mode corresponding to the given prefix (e.g. "@" -> "o"). */
  136. fun getMode(prefix: Char) = modes[prefixes.indexOf(prefix)]
  137. /** Gets the modes corresponding to the given prefixes (e.g. "@+" -> "ov"). */
  138. fun getModes(prefixes: String) = String(prefixes.map(this::getMode).toCharArray())
  139. }
  140. /**
  141. * Describes a server feature determined from the 005 response.
  142. */
  143. sealed class ServerFeature<T : Any>(val name: String, val type: KClass<T>, val default: T? = null) {
  144. /** The network the server says it belongs to. */
  145. object Network : ServerFeature<String>("NETWORK", String::class)
  146. /** The case mapping the server uses, defaulting to RFC. */
  147. object ServerCaseMapping : ServerFeature<CaseMapping>("CASEMAPPING", CaseMapping::class, CaseMapping.Rfc)
  148. /** The mode prefixes the server uses, defaulting to ov/@+. */
  149. object ModePrefixes : ServerFeature<ModePrefixMapping>("PREFIX", ModePrefixMapping::class, ModePrefixMapping("ov", "@+"))
  150. /** The maximum number of channels a client may join. */
  151. object MaximumChannels : ServerFeature<Int>("MAXCHANNELS", Int::class) // TODO: CHANLIMIT also exists
  152. /** The modes supported in channels. */
  153. object ChannelModes : ServerFeature<Array<String>>("CHANMODES", Array<String>::class)
  154. /** The types of channels supported. */
  155. object ChannelTypes : ServerFeature<String>("CHANTYPES", String::class, "#&")
  156. /** The maximum length of a channel name, defaulting to 200. */
  157. object MaximumChannelNameLength : ServerFeature<Int>("CHANNELLEN", Int::class, 200)
  158. /** Whether or not the server supports extended who. */
  159. object WhoxSupport : ServerFeature<Boolean>("WHOX", Boolean::class, false)
  160. }
  161. /**
  162. * Enumeration of the possible states of a server.
  163. */
  164. enum class ServerStatus {
  165. /** The server is not connected. */
  166. Disconnected,
  167. /** We are attempting to connect to the server. It is not yet ready for use. */
  168. Connecting,
  169. /** We are logging in, dealing with capabilities, etc. The server is not yet ready for use. */
  170. Negotiating,
  171. /** We are connected and commands can be sent. */
  172. Ready,
  173. }
  174. /**
  175. * Represents an in-progress batch.
  176. */
  177. internal data class Batch(val type: String, val arguments: List<String>, val metadata: EventMetadata, val events: MutableList<IrcEvent> = mutableListOf())
  178. internal val serverFeatures: Map<String, ServerFeature<*>> by lazy {
  179. ServerFeature::class.nestedClasses.map { it.objectInstance as ServerFeature<*> }.associateBy { it.name }
  180. }