Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
package org.siloserver.silo.common.network

import org.siloserver.silo.network.AndroidServerRegistry
import java.net.URI

/*
* The typed server address on the phone and TV setup screens, with the
* protocol and port from Advanced options, as silo-apple's
* `ServerSetupViewModel` builds it.
*/

enum class ServerSetupScheme(val label: String, val urlScheme: String?) {
Auto("Auto", null),
Https("HTTPS", "https"),
Http("HTTP", "http"),
}

class ServerSetupValidationException(message: String) : IllegalArgumentException(message)

/**
* True when the address WILL connect over plaintext HTTP: an explicit `http`
* scheme selection, or an `http://` prefix in the input. Auto mode is not
* flagged pre-connect — it tries HTTPS first and only falls back to HTTP.
* Informational only (does not block connecting to LAN/IP servers).
*/
fun serverSetupUsesCleartext(
rawInput: String,
selectedScheme: ServerSetupScheme,
port: String,
): Boolean {
if (rawInput.isBlank()) return false
if (selectedScheme == ServerSetupScheme.Http) return true
if (selectedScheme == ServerSetupScheme.Https) return false
return runCatching {
buildServerSetupCandidateUrls(rawInput, selectedScheme, port)
}.getOrNull()?.let { candidates ->
// Auto with an explicit http:// input resolves to a single http
// candidate; a bare host yields https first, so no pre-warning.
candidates.size == 1 && candidates.first().startsWith("http://")
} ?: false
}

fun buildServerSetupCandidateUrls(
rawInput: String,
selectedScheme: ServerSetupScheme,
port: String,
): List<String> {
val input = rawInput.trim()
if (input.isBlank()) {
throw ServerSetupValidationException("Please enter a server host.")
}

val parsed = parseServerSetupInput(input)
val explicitPort = parsed.port ?: parsePort(port)
val schemes = when {
selectedScheme.urlScheme != null -> listOf(selectedScheme.urlScheme)
parsed.scheme != null -> listOf(parsed.scheme)
else -> listOf("https", "http")
}

val candidates = schemes.map { scheme ->
buildServerSetupUrl(
scheme = scheme,
host = parsed.host,
port = explicitPort,
path = parsed.path,
)
}.toMutableList()

if (selectedScheme == ServerSetupScheme.Auto && parsed.scheme == null && explicitPort == null) {
candidates += buildServerSetupUrl(
scheme = "http",
host = parsed.host,
port = DefaultSiloServerPort,
path = parsed.path,
)
}

return candidates.distinct()
}

private const val DefaultSiloServerPort = 8090

private data class ParsedServerSetupInput(
val scheme: String?,
val host: String,
val port: Int?,
val path: String,
)

private fun parseServerSetupInput(input: String): ParsedServerSetupInput {
val hasScheme = input.contains("://")
val parseTarget = if (hasScheme) input else "https://$input"
val uri = runCatching { URI(parseTarget) }.getOrElse {
throw ServerSetupValidationException("Enter a valid server address.")
}
val host = uri.host?.takeIf { it.isNotBlank() }
?: throw ServerSetupValidationException("Enter a valid server address.")
// -1 is URI's "no port"; anything else was typed, so `:0` is rejected, not dropped.
val parsedPort = uri.port.takeIf { it != -1 }?.also { validatePort(it) }
val rawPath = uri.rawPath.orEmpty().trimEnd('/')
val path = rawPath.takeUnless { it.isBlank() || it == "/" }.orEmpty()
return ParsedServerSetupInput(
scheme = if (hasScheme) uri.scheme?.lowercase() else null,
host = host,
port = parsedPort,
path = path,
)
}

private fun parsePort(port: String): Int? {
val trimmed = port.trim()
if (trimmed.isBlank()) return null
val parsed = trimmed.toIntOrNull()
?: throw ServerSetupValidationException("Port must be a number between 1 and 65535.")
validatePort(parsed)
return parsed
}

private fun validatePort(port: Int) {
if (port !in 1..65535) {
throw ServerSetupValidationException("Port must be a number between 1 and 65535.")
}
}

private fun buildServerSetupUrl(
scheme: String,
host: String,
port: Int?,
path: String,
): String {
val authority = if (host.contains(":") && !host.startsWith("[")) "[$host]" else host
val portSuffix = port?.let { ":$it" }.orEmpty()
return AndroidServerRegistry.normalizeUrl("$scheme://$authority$portSuffix$path")
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package org.siloserver.silo.android.ui.screens.auth
package org.siloserver.silo.common.network

import kotlin.test.Test
import kotlin.test.assertEquals
Expand Down Expand Up @@ -47,14 +47,16 @@ class ServerSetupCandidateUrlsTest {

@Test
fun invalidPortIsRejectedBeforeConnecting() {
val error = assertFailsWith<ServerSetupValidationException> {
buildServerSetupCandidateUrls(
rawInput = "media.example.com",
selectedScheme = ServerSetupScheme.Https,
port = "99999",
)
// The Port field, and a port typed into the address (`:0` is a port, not "none").
listOf(
Triple("media.example.com", ServerSetupScheme.Https, "99999"),
Triple("http://media.example.com:0", ServerSetupScheme.Auto, ""),
).forEach { (rawInput, scheme, port) ->
val error = assertFailsWith<ServerSetupValidationException>(rawInput) {
buildServerSetupCandidateUrls(rawInput = rawInput, selectedScheme = scheme, port = port)
}

assertEquals("Port must be a number between 1 and 65535.", error.message)
}

assertEquals("Port must be a number between 1 and 65535.", error.message)
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package org.siloserver.silo.android.ui.screens.auth
package org.siloserver.silo.common.network

import kotlin.test.Test
import kotlin.test.assertFalse
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ import org.siloserver.silo.android.ui.components.marquee.MarqueeStage
import org.siloserver.silo.android.ui.components.marquee.MarqueeTextField
import org.siloserver.silo.android.ui.components.marquee.MarqueeWordmark
import org.siloserver.silo.android.ui.components.marquee.marqueePressHaptic
import org.siloserver.silo.common.network.ServerSetupScheme
import org.siloserver.silo.common.discovery.DiscoveredServer
import org.siloserver.silo.common.discovery.LanServerDiscovery
import org.siloserver.silo.common.ui.marquee.MarqueeColors
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,18 @@ import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import org.siloserver.silo.common.discovery.DiscoveredServer
import org.siloserver.silo.common.network.CleartextConsentStore
import org.siloserver.silo.common.network.ServerSetupScheme
import org.siloserver.silo.common.network.ServerSetupValidationException
import org.siloserver.silo.common.network.buildServerSetupCandidateUrls
import org.siloserver.silo.common.network.serverSetupUsesCleartext
import org.siloserver.silo.common.network.cleartextOrigin
import org.siloserver.silo.model.auth.SetupStatusResponse
import org.siloserver.silo.model.auth.SignupStatusResponse
import org.siloserver.silo.model.server.ServerContract
import org.siloserver.silo.network.apiv2.ApiV2ProbeResult
import org.siloserver.silo.network.AndroidServerRegistry
import org.siloserver.silo.network.ApiResult
import org.siloserver.silo.repository.AuthRepository
import org.siloserver.silo.repository.CONTRACT_PROVEN_BY_V2_RESPONSE
import java.net.URI
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
Expand All @@ -40,14 +42,6 @@ data class ServerSetupUiState(
get() = serverSetupUsesCleartext(serverUrl, selectedScheme, port)
}

enum class ServerSetupScheme(val label: String, val urlScheme: String?) {
Auto("Auto", null),
Https("HTTPS", "https"),
Http("HTTP", "http"),
}

class ServerSetupValidationException(message: String) : IllegalArgumentException(message)

sealed class ServerSetupDestination {
/** Server needs first-time setup (admin creation). */
data object Setup : ServerSetupDestination()
Expand Down Expand Up @@ -325,119 +319,3 @@ private data class PendingCleartextConnection(
val destination: ServerSetupDestination,
val contract: ServerContract?,
)

/**
* True when the address WILL connect over plaintext HTTP: an explicit `http`
* scheme selection, or an `http://` prefix in the input. Auto mode is not
* flagged pre-connect — it tries HTTPS first and only falls back to HTTP.
* Informational only (does not block connecting to LAN/IP servers).
*/
internal fun serverSetupUsesCleartext(
rawInput: String,
selectedScheme: ServerSetupScheme,
port: String,
): Boolean {
if (rawInput.isBlank()) return false
if (selectedScheme == ServerSetupScheme.Http) return true
if (selectedScheme == ServerSetupScheme.Https) return false
return runCatching {
buildServerSetupCandidateUrls(rawInput, selectedScheme, port)
}.getOrNull()?.let { candidates ->
// Auto with an explicit http:// input resolves to a single http
// candidate; a bare host yields https first, so no pre-warning.
candidates.size == 1 && candidates.first().startsWith("http://")
} ?: false
}

internal fun buildServerSetupCandidateUrls(
rawInput: String,
selectedScheme: ServerSetupScheme,
port: String,
): List<String> {
val input = rawInput.trim()
if (input.isBlank()) {
throw ServerSetupValidationException("Please enter a server host.")
}

val parsed = parseServerSetupInput(input)
val explicitPort = parsed.port ?: parsePort(port)
val schemes = when {
selectedScheme.urlScheme != null -> listOf(selectedScheme.urlScheme)
parsed.scheme != null -> listOf(parsed.scheme)
else -> listOf("https", "http")
}

val candidates = schemes.map { scheme ->
buildServerSetupUrl(
scheme = scheme,
host = parsed.host,
port = explicitPort,
path = parsed.path,
)
}.toMutableList()

if (selectedScheme == ServerSetupScheme.Auto && parsed.scheme == null && explicitPort == null) {
candidates += buildServerSetupUrl(
scheme = "http",
host = parsed.host,
port = DefaultSiloServerPort,
path = parsed.path,
)
}

return candidates.distinct()
}

private const val DefaultSiloServerPort = 8090

private data class ParsedServerSetupInput(
val scheme: String?,
val host: String,
val port: Int?,
val path: String,
)

private fun parseServerSetupInput(input: String): ParsedServerSetupInput {
val hasScheme = input.contains("://")
val parseTarget = if (hasScheme) input else "https://$input"
val uri = runCatching { URI(parseTarget) }.getOrElse {
throw ServerSetupValidationException("Enter a valid server address.")
}
val host = uri.host?.takeIf { it.isNotBlank() }
?: throw ServerSetupValidationException("Enter a valid server address.")
val parsedPort = uri.port.takeIf { it > 0 }?.also { validatePort(it) }
val rawPath = uri.rawPath.orEmpty().trimEnd('/')
val path = rawPath.takeUnless { it.isBlank() || it == "/" }.orEmpty()
return ParsedServerSetupInput(
scheme = if (hasScheme) uri.scheme?.lowercase() else null,
host = host,
port = parsedPort,
path = path,
)
}

private fun parsePort(port: String): Int? {
val trimmed = port.trim()
if (trimmed.isBlank()) return null
val parsed = trimmed.toIntOrNull()
?: throw ServerSetupValidationException("Port must be a number between 1 and 65535.")
validatePort(parsed)
return parsed
}

private fun validatePort(port: Int) {
if (port !in 1..65535) {
throw ServerSetupValidationException("Port must be a number between 1 and 65535.")
}
}

private fun buildServerSetupUrl(
scheme: String,
host: String,
port: Int?,
path: String,
): String {
val authority = if (host.contains(":") && !host.startsWith("[")) "[$host]" else host
val portSuffix = port?.let { ":$it" }.orEmpty()
return AndroidServerRegistry.normalizeUrl("$scheme://$authority$portSuffix$path")
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,3 @@ internal fun canSubmitTvCredentialLogin(
isLoading: Boolean,
): Boolean =
!isLoading && username.isNotBlank() && password.isNotBlank()

internal fun canSubmitTvServerUrl(value: String, isLoading: Boolean): Boolean =
!isLoading && value.isNotBlank()
Loading
Loading