diff --git a/core/build.gradle.kts b/core/build.gradle.kts index b6c1792ce..70449efa3 100644 --- a/core/build.gradle.kts +++ b/core/build.gradle.kts @@ -121,15 +121,23 @@ kotlin { implementation(kotlin("test")) implementation(libs.tests.mockk) implementation(libs.tests.coroutines) + // Prints what kdriver logs (warnings and errors only, see simplelogger.properties), + // such as why a browser failed to start, instead of dropping it. + runtimeOnly(libs.tests.slf4jSimple) } } + val posixTest by creating { + dependsOn(commonTest.get()) + } val macosTest by getting { + dependsOn(posixTest) dependencies { implementation(kotlin("test")) implementation(libs.tests.coroutines) } } val linuxTest by getting { + dependsOn(posixTest) dependencies { implementation(kotlin("test")) implementation(libs.tests.coroutines) diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/Browser.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/Browser.kt index c97eae16c..f07b1275e 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/browser/Browser.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/Browser.kt @@ -103,6 +103,10 @@ interface Browser { /** * Launches the actual browser + * + * If the browser process this instance launched has died, a new browser is started on the same + * configuration and profile and returned: use that instance from then on. It owns the process and + * the temporary profile, so [stop] it rather than this one. */ suspend fun start(): Browser @@ -134,10 +138,27 @@ interface Browser { * through [Config.browserUrl]; use [stop] to shut the browser down. * * A browser process launched by this instance is left running too; [stop] will no longer reach - * it. This instance cannot be used anymore afterwards. + * it, and the shutdown hook will not stop it either. This instance cannot be used anymore + * afterwards. + * + * Its temporary profile (when no [Config.userDataDir] was given) is kept on disk, since the + * browser still runs on it. It is deleted only if [cleanupTemporaryProfile] is called once that + * browser has exited; otherwise whoever shuts the browser down owns the directory, found in + * [Config.userDataDir]. */ suspend fun detach() + /** + * Deletes the temporary profile this browser created, when no [Config.userDataDir] was given. + * + * A profile passed as [Config.userDataDir] is never deleted. Nor is the temporary one while the + * browser process still runs: this waits a few seconds for it to exit, then gives up and leaves + * the profile in place. Calling it again, or after the profile is gone, does nothing. + * + * [stop] already calls it, and so does the shutdown hook that stops the browsers still running + * when the host process exits (on the JVM). There is usually no need to call it yourself, except + * after [detach], which keeps the profile. + */ suspend fun cleanupTemporaryProfile() /** diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/Config.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/Config.kt index a0eed7272..347723990 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/browser/Config.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/Config.kt @@ -55,6 +55,18 @@ class Config( private var _userDataDir: Path? = null private var _customDataDir: Boolean = false + /** + * True when [userDataDir] is a temporary profile kdriver created (no directory was given), and it + * has been created already. + * + * Carried over by [copy], like [userDataDir] itself: the browser kdriver launches on such a + * profile deletes it when it stops, whichever copy of the configuration created it. Otherwise a profile + * created before the browser copied its configuration (for instance by reading [userDataDir] + * first) would never be deleted. + */ + internal val createdTemporaryProfile: Boolean + get() = _userDataDir != null && !_customDataDir + private val _browserArgs: MutableList = browserArgs?.toMutableList() ?: mutableListOf() internal val _extensions: MutableList = mutableListOf() @@ -76,6 +88,12 @@ class Config( } } + /** + * The browser profile directory. + * + * When none is given, the first read creates a temporary `kdriver_*` directory, which the browser + * kdriver launches on it deletes when it stops. A directory given here is never deleted. + */ var userDataDir: Path get() { if (_userDataDir == null) { @@ -146,6 +164,9 @@ class Config( * * The copy is deep where it matters: the argument and extension lists are duplicated, so * mutating one config never affects the other. + * + * A temporary profile this config already created is shared with the copy, not duplicated: the + * browser kdriver launches on it deletes it when it stops (see [Browser.cleanupTemporaryProfile]). */ fun copy(): Config = Config( // Pass the already-resolved executable so the copy does not re-run the disk search. diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt index 87b506102..3dff70381 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt @@ -8,6 +8,7 @@ import dev.kdriver.core.connection.Connection import dev.kdriver.core.connection.DefaultConnection import dev.kdriver.core.connection.OwnedConnection import dev.kdriver.core.exceptions.BrowserExecutableNotFoundException +import dev.kdriver.core.exceptions.ConnectionClosedException import dev.kdriver.core.exceptions.FailedToConnectToBrowserException import dev.kdriver.core.tab.DefaultTab import dev.kdriver.core.tab.Tab @@ -15,6 +16,8 @@ import io.ktor.util.logging.* import kotlinx.coroutines.* import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock +import kotlinx.io.IOException +import kotlinx.io.files.Path import kotlin.concurrent.Volatile import kotlin.time.Duration.Companion.seconds @@ -37,10 +40,38 @@ open class DefaultBrowser( */ override val config: Config = config.copy() - private val logger = KtorSimpleLogger("Browser") + /** Internal so tests can observe what is logged, such as a profile left on disk. */ + internal var logger: Logger = KtorSimpleLogger("Browser") private val updateTargetInfoMutex = Mutex() private var process: Process? = null + + /** + * The temporary profile this browser created and must delete, or null if it uses a custom + * [Config.userDataDir], has not launched a process, or already deleted it. + */ + private var temporaryProfile: Path? = null + + /** + * The process that runs on [temporaryProfile]. Unlike [process], it is kept after [stop] and + * [detach]: the profile may only be deleted once this process has exited. + */ + private var temporaryProfileUser: Process? = null + + /** + * Whether this instance launched a browser process (rather than connecting to one), even if it + * has been stopped since: a failed start may have stopped it already, and must not then be + * treated as a browser it only connected to. + */ + internal var launchedProcess: Boolean = false + private set + private val temporaryProfileMutex = Mutex() + + /** How long [cleanupTemporaryProfile] waits for the browser process to exit; shortened by tests. */ + internal var profileReleaseTimeoutMillis: Long = PROFILE_RELEASE_TIMEOUT_MS + + /** Deletes the temporary profile, with retries; replaced by tests to simulate a locked profile. */ + internal var deleteProfile: suspend (Path) -> Boolean = { deleteTemporaryProfile(it) } private var http: HTTPApi? = null private var _cookies: CookieJar? = null @@ -93,6 +124,13 @@ open class DefaultBrowser( private const val TARGET_WAIT_TIMEOUT_MS = 10_000L private const val TARGET_POLL_INTERVAL_MS = 50L + /** + * How long [cleanupTemporaryProfile] waits for the browser process to exit before giving up on + * deleting its profile. [stop] has already waited for it by then; this bounds the wait when + * [cleanupTemporaryProfile] is called on its own. + */ + private const val PROFILE_RELEASE_TIMEOUT_MS = 5_000L + /** * The entry point for creating a new Browser instance. * @@ -105,13 +143,59 @@ open class DefaultBrowser( * * @return A new instance of the Browser class. */ - suspend fun create(coroutineScope: CoroutineScope, config: Config): Browser { + suspend fun create(coroutineScope: CoroutineScope, config: Config): Browser = + create(coroutineScope, config, ::DefaultBrowser) + + /** + * Runs [cleanup] after [cause] made an operation fail, without being cancelled. A failure of + * the cleanup itself is attached to [cause] as suppressed, so it never replaces the root cause. + */ + @Suppress("TooGenericExceptionCaught") + private suspend fun cleanUpAfter(cause: Throwable, cleanup: suspend () -> Unit) { + try { + withContext(NonCancellable) { cleanup() } + } catch (e: Throwable) { + cause.addSuppressed(e) + } + } + + /** + * Runs every one of [steps], even after one of them fails. The first failure is rethrown once + * they have all run, with the later ones attached to it as suppressed. + */ + @Suppress("TooGenericExceptionCaught") // collects every failure, then rethrows the first one + private suspend fun runEach(vararg steps: suspend () -> Unit) { + var failure: Throwable? = null + for (step in steps) { + try { + step() + } catch (e: Throwable) { + val first = failure + if (first == null) failure = e else first.addSuppressed(e) + } + } + failure?.let { throw it } + } + + /** [create], with the instance built by [factory]: tests use it to make the start fail. */ + @Suppress("TooGenericExceptionCaught") // cleans up whatever made the start fail, then rethrows it + internal suspend fun create( + coroutineScope: CoroutineScope, + config: Config, + factory: (CoroutineScope, Config) -> DefaultBrowser, + ): DefaultBrowser { val browserScope = CoroutineScope(coroutineScope.coroutineContext + SupervisorJob()) - val instance = DefaultBrowser(browserScope, config) - instance.start() - addShutdownHook { - if (!instance.stopped) instance.stop() - instance.cleanupTemporaryProfile() + val instance = factory(browserScope, config) + // start() registers the browser with StartedBrowsers, whose shutdown hook stops it and + // deletes its temporary profile if the host process exits without calling stop(). + try { + instance.start() + } catch (e: Throwable) { + // On failure the caller never gets this instance, so it could never stop the browser + // it launched. A browser it only connected to (connect-existing) is not ours to close: + // it may be shared, so only the client side is torn down. + cleanUpAfter(e) { if (instance.launchedProcess) instance.stop() else instance.detach() } + throw e } return instance } @@ -232,7 +316,7 @@ open class DefaultBrowser( override suspend fun start(): Browser { process?.let { - if (process?.isAlive() == false) return create(coroutineScope, config) + if (process?.isAlive() == false) return restart() logger.warn("Ignored! Browser is already running.") return this } @@ -264,7 +348,21 @@ open class DefaultBrowser( logger.info("starting\n\texecutable :$exe\n\narguments:\n${params.joinToString("\n\t")}") - process = startProcess(exe, params) + // config() above created the temporary profile, if any: from here on it is ours to delete. + if (config.createdTemporaryProfile) temporaryProfile = config.userDataDir + @Suppress("TooGenericExceptionCaught") // cleans up whatever made the launch fail, then rethrows it + val launched = try { + startProcess(exe, params) + } catch (e: Throwable) { + cleanUpAfter(e) { cleanupTemporaryProfile() } + throw e + } + process = launched + temporaryProfileUser = launched + launchedProcess = true + // Only a browser kdriver launched: one it merely connected to (browserUrl, or host and + // port) may be shared or owned by something else, so the exit hook must not close it. + StartedBrowsers.register(this) } logger.info("Browser process started with PID: ${process?.pid()}") @@ -331,6 +429,39 @@ open class DefaultBrowser( return this } + /** + * Starts a new browser on the same configuration, because this one's process has died. + * + * The new browser runs on the same profile, so it takes over deleting it (its configuration, a + * copy of this one, says the profile is a temporary one kdriver created): this one must no longer + * delete it, nor be stopped on exit. + */ + @Suppress("TooGenericExceptionCaught") // cleans up whatever made the relaunch fail, then rethrows it + private suspend fun restart(): Browser { + val inherited = temporaryProfile + temporaryProfile = null + temporaryProfileUser = null + StartedBrowsers.unregister(this) + val restarted = try { + relaunch(config.copy().apply { + // The host and port start() assigned to the dead process: the new browser gets its own. + // Kept, they would make it connect to that dead port instead of launching a browser. + host = null + port = null + }) + } catch (e: Throwable) { + // Nothing runs on the profile anymore: this browser's process is dead and the new one failed. + temporaryProfile = inherited + cleanUpAfter(e) { cleanupTemporaryProfile() } + throw e + } + return restarted + } + + /** Launches the browser that replaces this one in [restart]; overridden by tests to make it fail. */ + internal open suspend fun relaunch(config: Config): DefaultBrowser = + create(coroutineScope, config, ::DefaultBrowser) + private suspend fun handleTargetUpdate(event: Any) = updateTargetInfoMutex.withLock { when (event) { // Both create and info-changed go through the same dedupe-by-targetId upsert, so an @@ -374,33 +505,76 @@ open class DefaultBrowser( override suspend fun stop() { logger.info("Stopping browser process with PID: ${process?.pid()}") + // Each step runs even if an earlier one failed or was cancelled: a graceful close that throws + // must not leave the process running nor its profile on disk. The first failure is rethrown. + runEach( + { closeGracefully() }, + { + // Not cancellable, so a stop() called from the `finally` of a cancelled coroutine still + // kills the process and deletes the profile. + withContext(NonCancellable) { + runEach( + { killProcess() }, + { connection?.also { connection = null }?.close() }, + { http?.also { http = null }?.close() }, + { deleteProfileOnStop() }, + ) + } + }, + { + // Last, since it may be the caller's own scope. + logger.debug("Canceling coroutine scope...") + coroutineScope.cancel() + }, + ) + logger.info("Browser process stopped") + } + + private suspend fun closeGracefully() { logger.debug("Closing browser gracefully...") - withTimeoutOrNull(5.seconds) { connection?.browser?.close() } + try { + withTimeoutOrNull(5.seconds) { connection?.browser?.close() } + } catch (e: IOException) { + // Nothing answers: the browser already died (crashed, or killed from outside). Its process + // and its profile are still dealt with afterwards. + logger.debug("Could not close the browser gracefully: ${e.message}") + } catch (e: ConnectionClosedException) { + // The same, once the connection has given up on every send attempt. + logger.debug("Could not close the browser gracefully: ${e.message}") + } + } + + private suspend fun killProcess() { logger.debug("Killing browser process...") // Wait for it to actually be gone, don't just ask. destroy() returns immediately and does not - // reach the browser's child processes, which keep open handles on the profile directory — - // a browser started on the same --user-data-dir right after would hang before opening its - // debug port, and the start would time out for no visible reason. - process?.let { - if (!it.destroyAndAwaitExit()) logger.warn("Browser process ${it.pid()} still alive after kill") + // reach the browser's child processes, which keep open handles on the profile directory — a + // browser started on the same --user-data-dir right after would hang before opening its debug + // port, and the start would time out for no visible reason. + val process = process ?: return + if (!process.destroyAndAwaitExit()) { + // Kept, so that a later stop() (the exit hook's, since the browser stays registered with + // its profile) tries to kill it again. + logger.warn("Browser process ${process.pid()} still alive after kill") + return } - process = null - logger.debug("Closing connection...") - connection?.close() - connection = null - logger.debug("Closing HTTP API client...") - http?.close() - http = null - logger.debug("Canceling coroutine scope...") - coroutineScope.cancel() - logger.info("Browser process stopped") + this.process = null + } + + private suspend fun deleteProfileOnStop() { + // No further wait: the process has just been waited for, and killed if it lingered. If the + // kill failed, the profile is kept, since the process may still be writing to it. + cleanupTemporaryProfile(releaseTimeoutMillis = 0) + // Still registered if the profile could not be deleted, so the exit hook tries again. + if (temporaryProfile == null) StartedBrowsers.unregister(this) } override suspend fun detach() { logger.info("Detaching from browser at ${info?.webSocketDebuggerUrl}") // Only client-side teardown: no Browser.close, no process kill. Forgetting the process also - // keeps the shutdown hook from stopping a browser we chose to leave running. + // keeps the shutdown hook from stopping a browser we chose to leave running. Its temporary + // profile is kept too, since the browser still runs on it. process = null + StartedBrowsers.unregister(this) val targets = updateTargetInfoMutex.withLock { detached = true mutableTargets.toList().also { @@ -417,8 +591,24 @@ open class DefaultBrowser( logger.info("Detached from browser") } - override suspend fun cleanupTemporaryProfile() { - // TODO: Implement cleanup of temporary profile files (nothing on JVM but maybe for other platforms) + override suspend fun cleanupTemporaryProfile() = cleanupTemporaryProfile(profileReleaseTimeoutMillis) + + private suspend fun cleanupTemporaryProfile(releaseTimeoutMillis: Long) = temporaryProfileMutex.withLock { + val profile = temporaryProfile ?: return@withLock + // The browser keeps writing to its profile while it shuts down: deleting it earlier would race + // those writes, and leave files (or recreated directories) behind. + val user = temporaryProfileUser + if (user != null && !user.awaitExit(releaseTimeoutMillis)) { + logger.warn("Not deleting temporary profile $profile: browser process ${user.pid()} is still running") + return@withLock + } + if (deleteProfile(profile)) { + logger.debug("Deleted temporary profile $profile") + temporaryProfile = null + temporaryProfileUser = null + } else { + logger.warn("Could not delete temporary profile $profile") + } } private suspend fun getTargets(): List { diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/ProcessExit.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/ProcessExit.kt index 8101d3dce..28139a1d4 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/browser/ProcessExit.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/ProcessExit.kt @@ -37,7 +37,12 @@ suspend fun Process.destroyAndAwaitExit( } } -private suspend fun Process.awaitExit(timeoutMillis: Long): Boolean { +/** + * Waits up to [timeoutMillis] for the process to exit, without asking it to. + * + * @return true if the process has exited. + */ +internal suspend fun Process.awaitExit(timeoutMillis: Long): Boolean { var waited = 0L while (waited < timeoutMillis) { if (!isAlive()) return true diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/StartedBrowsers.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/StartedBrowsers.kt new file mode 100644 index 000000000..50f36436a --- /dev/null +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/StartedBrowsers.kt @@ -0,0 +1,65 @@ +package dev.kdriver.core.browser + +import io.ktor.util.logging.* +import kotlinx.coroutines.CoroutineExceptionHandler +import kotlinx.coroutines.launch +import kotlinx.coroutines.supervisorScope +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock + +/** + * The browsers this process launched and has not stopped (nor detached) yet. A browser it only + * connected to (through [Config.browserUrl], or a host and port) is never in it: it may be shared, or + * owned by something else, so it is not closed on exit. + * + * When the host process exits without calling [Browser.stop], they are stopped from a single + * shutdown hook (see [addShutdownHook]), which also deletes their temporary profiles. Without it, a + * program that simply returns from `main` leaves a `kdriver_*` profile behind on every run. + * + * Only the JVM has such a hook: [addShutdownHook] does nothing on the native and JS targets, where + * a browser that is never stopped keeps its profile on disk. + * + * One hook for the whole process rather than one per browser: a hook cannot be removed once added, + * so a hook per browser would keep every browser ever created reachable until the process exits. + * A browser leaves this registry as soon as it is stopped or detached. + */ +internal object StartedBrowsers { + + private val logger = KtorSimpleLogger("StartedBrowsers") + private val mutex = Mutex() + private val browsers = LinkedHashSet() + private var hookInstalled = false + + suspend fun register(browser: Browser) = mutex.withLock { + if (!hookInstalled) { + addShutdownHook { stopAll() } + hookInstalled = true + } + browsers += browser + } + + suspend fun unregister(browser: Browser) = mutex.withLock { + browsers -= browser + } + + suspend operator fun contains(browser: Browser): Boolean = mutex.withLock { browser in browsers } + + /** + * Stops every browser still registered, concurrently, so their grace periods overlap. + * + * A browser that fails to stop is logged and does not keep the others from stopping: each runs in + * its own child of a supervisor scope, whose failure goes to a handler rather than to its siblings. + */ + internal suspend fun stopAll() { + val remaining = mutex.withLock { browsers.toList() } + supervisorScope { + remaining.forEach { browser -> + val onFailure = CoroutineExceptionHandler { _, e -> + logger.warn("Could not stop browser ${browser.pid} on exit: ${e.message}") + } + launch(onFailure) { browser.stop() } + } + } + } + +} diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.kt new file mode 100644 index 000000000..f95bf2fbb --- /dev/null +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.kt @@ -0,0 +1,54 @@ +package dev.kdriver.core.browser + +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.delay +import kotlinx.coroutines.withContext +import kotlinx.io.files.Path + +/** + * Deletes [path] and everything below it, without following symbolic links (or, on Windows, + * junctions): a link inside the profile is removed, never what it points to. + * + * Best effort: keeps going past an entry it cannot delete, so one locked file does not keep the + * rest of the profile on disk. + * + * @return true if [path] no longer exists afterwards (including when it never existed). + */ +internal expect fun deleteRecursively(path: Path): Boolean + +/** + * Where the blocking file system calls of a profile deletion run, so that a [Browser.stop] called + * from a small dispatcher (a UI thread, a single-threaded loop) does not block it during the walk. + */ +internal expect val fileSystemDispatcher: CoroutineDispatcher + +/** + * Deletes a temporary profile, retrying for a short while if it cannot be removed at once. + * + * Even after the browser process has exited, a file of the profile can stay locked for a moment + * (on Windows by a child process that is still winding down, or by an antivirus scanning it), so a + * single attempt is not enough. + * + * @param path the profile directory. + * @param attempts how many times to try at most. + * @param retryDelayMillis how long to wait between two attempts. + * @param delete one attempt, [deleteRecursively] outside of tests. + * @return true if the profile is gone. + */ +internal suspend fun deleteTemporaryProfile( + path: Path, + attempts: Int = PROFILE_DELETE_ATTEMPTS, + retryDelayMillis: Long = PROFILE_DELETE_RETRY_DELAY_MILLIS, + delete: (Path) -> Boolean = ::deleteRecursively, +): Boolean { + repeat(attempts) { attempt -> + if (withContext(fileSystemDispatcher) { delete(path) }) return true + if (attempt < attempts - 1) delay(retryDelayMillis) + } + return false +} + +// About 5 seconds in all: a profile Chrome has only just written (a browser stopped right after its +// start) can stay locked on Windows for more than 2 seconds. +private const val PROFILE_DELETE_ATTEMPTS = 26 +private const val PROFILE_DELETE_RETRY_DELAY_MILLIS = 200L diff --git a/core/src/jsMain/kotlin/dev/kdriver/core/browser/FileSystemDispatcher.js.kt b/core/src/jsMain/kotlin/dev/kdriver/core/browser/FileSystemDispatcher.js.kt new file mode 100644 index 000000000..5f4011e2f --- /dev/null +++ b/core/src/jsMain/kotlin/dev/kdriver/core/browser/FileSystemDispatcher.js.kt @@ -0,0 +1,7 @@ +package dev.kdriver.core.browser + +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers + +/** JS cannot launch a browser, so it never deletes a profile: there is no I/O dispatcher there anyway. */ +internal actual val fileSystemDispatcher: CoroutineDispatcher = Dispatchers.Default diff --git a/core/src/jsMain/kotlin/dev/kdriver/core/browser/Process.js.kt b/core/src/jsMain/kotlin/dev/kdriver/core/browser/Process.js.kt index 3c9c224d2..4bf8caa8c 100644 --- a/core/src/jsMain/kotlin/dev/kdriver/core/browser/Process.js.kt +++ b/core/src/jsMain/kotlin/dev/kdriver/core/browser/Process.js.kt @@ -64,3 +64,7 @@ actual fun freePort(): Int? { actual fun defaultBrowserSearchConfig(): BrowserSearchConfig { throw UnsupportedOperationException() } + +internal actual fun deleteRecursively(path: Path): Boolean { + throw UnsupportedOperationException() +} diff --git a/core/src/jvmMain/kotlin/dev/kdriver/core/browser/FileSystemDispatcher.jvm.kt b/core/src/jvmMain/kotlin/dev/kdriver/core/browser/FileSystemDispatcher.jvm.kt new file mode 100644 index 000000000..db7d9be61 --- /dev/null +++ b/core/src/jvmMain/kotlin/dev/kdriver/core/browser/FileSystemDispatcher.jvm.kt @@ -0,0 +1,6 @@ +package dev.kdriver.core.browser + +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers + +internal actual val fileSystemDispatcher: CoroutineDispatcher = Dispatchers.IO diff --git a/core/src/jvmMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.jvm.kt b/core/src/jvmMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.jvm.kt new file mode 100644 index 000000000..45326b6a2 --- /dev/null +++ b/core/src/jvmMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.jvm.kt @@ -0,0 +1,24 @@ +package dev.kdriver.core.browser + +import kotlinx.io.files.Path +import java.io.IOException +import java.nio.file.LinkOption +import java.nio.file.Paths +import kotlin.io.path.ExperimentalPathApi +import kotlin.io.path.deleteRecursively +import kotlin.io.path.exists + +/** + * `Path.deleteRecursively` does not follow symbolic links, and keeps going past an entry it cannot + * delete before throwing: the end state is what tells whether the profile is gone. + */ +@OptIn(ExperimentalPathApi::class) +internal actual fun deleteRecursively(path: Path): Boolean { + val target = Paths.get(path.toString()) + try { + target.deleteRecursively() + } catch (_: IOException) { + // Reported below, through whether the directory is still there. + } + return !target.exists(LinkOption.NOFOLLOW_LINKS) +} diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/BrowserTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/BrowserTest.kt index c92296ed1..7c99c7422 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/BrowserTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/BrowserTest.kt @@ -3,6 +3,7 @@ package dev.kdriver.core.browser import dev.kdriver.cdp.domain.Network import dev.kdriver.core.sampleFile import dev.kdriver.core.tab.ReadyState +import dev.kdriver.core.tab.evaluate import kotlinx.coroutines.runBlocking import kotlinx.io.files.Path import kotlin.io.path.deleteIfExists @@ -143,6 +144,8 @@ class BrowserTest { fun testGetContentGetsHtmlContent() = runBlocking { val browser = createBrowser(this, headless = true, sandbox = false) val tab = browser.get("https://example.com") + // get() returns once the navigation has started: read the document once it has loaded. + tab.waitForReadyState(ReadyState.COMPLETE) val content = tab.getContent() assertTrue(content.lowercase().startsWith("")) browser.stop() @@ -185,20 +188,23 @@ class BrowserTest { ) assertEquals(3, userDataDirs.size) - val page1 = browser1.get("https://example.com/one") - page1.wait() + val page1 = browser1.get(sampleFile("groceries.html")) + // Local pages: the test is about the browsers, not about how fast a remote site answers. Read once + // loaded, from the document: get() returns once the navigation has started, and the target's title + // can still be its URL for a while after the load. + page1.waitForReadyState(ReadyState.COMPLETE) assertNotNull(page1.targetInfo) - assertEquals("Example Domain", page1.targetInfo?.title) + assertEquals("Grocery List", page1.evaluate("document.title")) - val page2 = browser2.get("https://example.com/two") - page2.wait() + val page2 = browser2.get(sampleFile("lookup-test.html")) + page2.waitForReadyState(ReadyState.COMPLETE) assertNotNull(page2.targetInfo) - assertEquals("Example Domain", page2.targetInfo?.title) + assertEquals("Lookup", page2.evaluate("document.title")) - val page3 = browser3.get("https://example.com/three") - page3.wait() + val page3 = browser3.get(sampleFile("profile.html")) + page3.waitForReadyState(ReadyState.COMPLETE) assertNotNull(page3.targetInfo) - assertEquals("Example Domain", page3.targetInfo?.title) + assertEquals("Fetch Example", page3.evaluate("document.title")) browser1.stop() browser2.stop() diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt new file mode 100644 index 000000000..11d4051b7 --- /dev/null +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt @@ -0,0 +1,644 @@ +package dev.kdriver.core.browser + +import dev.kdriver.cdp.domain.browser +import dev.kdriver.core.connection.Connection +import dev.kdriver.core.exceptions.ConnectionClosedException +import io.ktor.util.logging.Logger +import io.mockk.coEvery +import io.mockk.coVerify +import io.mockk.every +import io.mockk.mockk +import io.mockk.verify +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.delay +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.currentTime +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.withTimeoutOrNull +import kotlinx.io.files.Path +import java.io.File +import java.io.IOException +import java.nio.file.Files +import kotlin.io.path.createTempDirectory +import kotlin.io.path.createTempFile +import kotlin.io.path.deleteRecursively +import kotlin.io.path.ExperimentalPathApi +import kotlin.io.path.exists +import kotlin.io.path.writeText +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNotSame +import kotlin.test.assertTrue +import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Duration.Companion.seconds +import kotlin.time.measureTime + +/** + * The temporary profile kdriver creates when no `userDataDir` is given must be deleted once the + * browser is stopped; a profile the caller supplied must never be. + */ +@OptIn(ExperimentalPathApi::class, ExperimentalCoroutinesApi::class) +class TemporaryProfileTest { + + @Test + fun stop_deletesTheTemporaryProfile() = runBlocking { + val browser = createBrowser(this, headless = true, sandbox = false) + val profile = File(browser.config.userDataDir.toString()) + assertFalse(browser.config.usesCustomDataDir) + assertTrue(profile.isDirectory, "the browser runs on a temporary profile") + assertTrue(profile.name.startsWith("kdriver_")) + + browser.stop() + + assertFalse(profile.exists(), "the temporary profile must be deleted by stop()") + assertFalse(browser in StartedBrowsers, "a stopped browser is no longer stopped on exit") + } + + @Test + fun stop_keepsACustomUserDataDir() = runBlocking { + val custom = createTempDirectory(prefix = "kdriver_custom_test_") + try { + val browser = createBrowser(this, userDataDir = Path(custom.toString()), headless = true, sandbox = false) + assertTrue(browser.config.usesCustomDataDir) + + browser.stop() + browser.cleanupTemporaryProfile() + + assertTrue(custom.exists(), "a userDataDir given by the caller must never be deleted") + assertTrue(custom.toFile().list().orEmpty().isNotEmpty(), "the browser's files in it are kept too") + } finally { + // With retries: on Windows the browser's children may hold its files for a moment more. + deleteTemporaryProfile(Path(custom.toString())) + } + } + + @Test + fun secondStopAndCleanupAreHarmless() = runBlocking { + val browser = createBrowser(this, headless = true, sandbox = false) + val profile = File(browser.config.userDataDir.toString()) + + browser.stop() + browser.stop() + browser.cleanupTemporaryProfile() + browser.cleanupTemporaryProfile() + + assertFalse(profile.exists()) + assertTrue(browser.stopped) + } + + @Test + fun cleanup_keepsTheProfileWhileTheBrowserStillRuns() = runBlocking { + val browser = createBrowser(this, headless = true, sandbox = false) as DefaultBrowser + val profile = File(browser.config.userDataDir.toString()) + val logger = mockk(relaxed = true) + browser.logger = logger + browser.profileReleaseTimeoutMillis = 300 + try { + // Not stopped: the browser keeps writing to its profile, which must not be deleted under it. + val waited = measureTime { browser.cleanupTemporaryProfile() } + + assertTrue(profile.isDirectory, "a running browser's profile must be kept") + assertTrue(waited >= 300.milliseconds, "it waits for the process to exit first, waited $waited") + verify { logger.warn(match { "is still running" in it && profile.path in it }) } + } finally { + browser.stop() + } + assertFalse(profile.exists(), "stop() deletes it once the browser is gone") + } + + @Test + fun stop_deletesATemporaryProfileCreatedBeforeTheBrowserCopiedItsConfig() = runBlocking { + val config = Config(headless = true, sandbox = false) + // Reading it creates the temporary profile on this config, before the browser copies it. + val profile = File(config.userDataDir.toString()) + val browser = createBrowser(this, config) + assertEquals(config.userDataDir, browser.config.userDataDir, "the browser runs on that profile") + assertTrue(browser.config.createdTemporaryProfile) + + browser.stop() + + assertFalse(profile.exists(), "a temporary profile kdriver created must not leak, whichever copy created it") + assertFalse(browser in StartedBrowsers) + } + + @Test + fun start_deletesTheProfileWhenTheProcessCannotBeLaunched() = runBlocking { + // An existing file that is not an executable: launching it fails on every platform. + val notABrowser = createTempFile(prefix = "kdriver_not_a_browser_", suffix = ".txt") + notABrowser.writeText("not a browser") + try { + val browser = DefaultBrowser(this, Config(browserExecutablePath = Path(notABrowser.toString()))) + + assertFailsWith { browser.start() } + + val profile = File(browser.config.userDataDir.toString()) + assertTrue(profile.name.startsWith("kdriver_"), "the start created a temporary profile") + assertFalse(profile.exists(), "a profile no browser ever ran on is deleted at once") + assertFalse(browser in StartedBrowsers) + } finally { + Files.deleteIfExists(notABrowser) + } + } + + @Test + fun create_stopsTheBrowserItLaunchedWhenTheStartFailsAfterTheLaunch() = runBlocking { + var launched: DefaultBrowser? = null + val failure = assertFailsWith { + DefaultBrowser.create(this, Config(headless = true, sandbox = false)) { scope, config -> + object : DefaultBrowser(scope, config) { + override suspend fun start(): Browser { + super.start() + error("target discovery failed") + } + }.also { launched = it } + } + } + assertEquals("target discovery failed", failure.message) + + // The caller never got this instance, so create() had to stop it. + val browser = assertNotNull(launched) + assertTrue(browser.stopped, "the browser process must be stopped") + val profile = File(browser.config.userDataDir.toString()) + assertFalse(profile.exists(), "and its profile deleted, left: ${profile.walk().take(20).toList()}") + assertFalse(browser in StartedBrowsers) + } + + @Test + fun create_keepsForTheExitHookABrowserItsFailedStartAlreadyStopped() = runBlocking { + var launched: DefaultBrowser? = null + assertFailsWith { + DefaultBrowser.create(this, Config(headless = true, sandbox = false)) { scope, config -> + object : DefaultBrowser(scope, config) { + // As start() does when the browser never answers: it stops the browser, then throws. + override suspend fun start(): Browser { + super.start() + deleteProfile = { false } + stop() + error("failed to connect") + } + }.also { launched = it } + } + } + + val browser = assertNotNull(launched) + val profile = File(browser.config.userDataDir.toString()) + try { + assertTrue(profile.isDirectory, "the profile could not be deleted…") + assertTrue(browser in StartedBrowsers, "…so the browser stays for the exit hook, not detached") + } finally { + browser.deleteProfile = { deleteTemporaryProfile(it) } + browser.stop() + } + assertFalse(profile.exists()) + } + + @Test + fun create_keepsTheOriginalFailureWhenTheCleanupFailsToo() = runBlocking { + val failure = assertFailsWith { + DefaultBrowser.create(this, Config(headless = true, sandbox = false)) { scope, config -> + object : DefaultBrowser(scope, config) { + override suspend fun start(): Browser { + super.start() + error("target discovery failed") + } + + override suspend fun stop() { + try { + error("stop failed") + } finally { + super.stop() + } + } + } + } + } + assertEquals("target discovery failed", failure.message) + assertEquals(listOf("stop failed"), failure.suppressed.map { it.message }) + } + + @Test + fun create_doesNotStopABrowserItOnlyConnectedTo() = runBlocking { + var stopped = false + var detached = false + val failure = assertFailsWith { + DefaultBrowser.create(this, Config(headless = true, sandbox = false)) { scope, config -> + object : DefaultBrowser(scope, config) { + // Fails without having launched a process, as a connect-existing start would. + override suspend fun start(): Browser = error("no such browser") + + override suspend fun stop() { + stopped = true + } + + override suspend fun detach() { + detached = true + } + } + } + } + assertEquals("no such browser", failure.message) + assertFalse(stopped, "Browser.close must not reach a browser kdriver did not launch") + assertTrue(detached) + } + + @Test + fun start_afterTheProcessDied_relaunchesOnTheSameProfileAndHandsItsDeletionOver() = runBlocking { + val browser = createBrowser(this, headless = true, sandbox = false) + val profile = File(browser.config.userDataDir.toString()) + killFromOutside(browser) + + val restarted = browser.start() + try { + assertNotSame(browser, restarted) + assertFalse(restarted.stopped, "a new browser process runs") + assertEquals(browser.config.userDataDir, restarted.config.userDataDir, "on the same profile") + assertNotNull(restarted.pid, "it launched a process, rather than connecting to the dead one's port") + assertFalse(browser in StartedBrowsers, "the dead browser is no longer stopped on exit") + assertTrue(restarted in StartedBrowsers) + + browser.cleanupTemporaryProfile() + assertTrue(profile.isDirectory, "the dead browser no longer deletes the profile the new one runs on") + } finally { + restarted.stop() + browser.stop() + } + assertFalse(profile.exists(), "the new browser deletes it when it stops") + } + + @Test + fun start_afterTheProcessDied_keepsACustomUserDataDirOnRelaunch() = runBlocking { + val custom = createTempDirectory(prefix = "kdriver_custom_test_") + try { + val browser = createBrowser(this, userDataDir = Path(custom.toString()), headless = true, sandbox = false) + killFromOutside(browser) + + val restarted = browser.start() + try { + assertNotSame(browser, restarted) + assertEquals(browser.config.userDataDir, restarted.config.userDataDir) + } finally { + restarted.stop() + browser.stop() + } + assertTrue(custom.exists(), "a userDataDir given by the caller must never be deleted") + } finally { + deleteTemporaryProfile(Path(custom.toString())) + } + } + + @Test + fun stop_onABrowserThatNeverStartedDoesNothing() = runBlocking { + val scope = CoroutineScope(coroutineContext + SupervisorJob()) + val browser = DefaultBrowser(scope, Config(headless = true, sandbox = false)) + + browser.stop() + browser.cleanupTemporaryProfile() + + assertTrue(browser.stopped) + assertFalse(browser in StartedBrowsers) + } + + @Test + fun stop_afterTheProcessDied_stillDeletesTheProfile() = runBlocking { + val browser = createBrowser(this, headless = true, sandbox = false) + val profile = File(browser.config.userDataDir.toString()) + killFromOutside(browser) + + // Nothing answers the graceful close anymore: that must not keep stop() from cleaning up. + browser.stop() + + assertFalse(profile.exists(), "a crashed browser's profile is deleted by stop() too") + assertFalse(browser in StartedBrowsers) + } + + @Test + fun stop_goesOnWhenTheGracefulCloseFindsTheConnectionClosed() = runBlocking { + assertStopGoesOnAfterAFailedClose(ConnectionClosedException()) + } + + @Test + fun stop_goesOnWhenTheGracefulCloseCannotReachTheBrowser() = runBlocking { + assertStopGoesOnAfterAFailedClose(IOException("Connection refused")) + } + + private suspend fun assertStopGoesOnAfterAFailedClose(failure: Exception) { + val connection = mockk(relaxed = true) + every { connection.generatedDomains } returns mutableMapOf() + coEvery { connection.callCommand("Browser.close", any(), any()) } throws failure + // A scope of its own: stop() cancels it. + val browser = DefaultBrowser(CoroutineScope(Job()), Config(browserExecutablePath = Path("unused"))) + browser.connection = connection + + browser.stop() + + coVerify { connection.close() } + assertEquals(null, browser.connection, "stop() went on past the failed close") + } + + @Test + fun start_afterTheProcessDied_deletesTheProfileWhenTheRelaunchFails() = runBlocking { + val browser = DefaultBrowser.create(this, Config(headless = true, sandbox = false)) { scope, config -> + object : DefaultBrowser(scope, config) { + override suspend fun relaunch(config: Config): DefaultBrowser = throw IOException("no browser") + } + } + val profile = File(browser.config.userDataDir.toString()) + try { + killFromOutside(browser) + + assertFailsWith { browser.start() } + + assertFalse(profile.exists(), "nothing runs on the profile anymore: it is deleted") + assertFalse(browser in StartedBrowsers) + } finally { + browser.stop() + } + } + + @Test + fun stop_whenTheProfileCannotBeDeleted_keepsTheBrowserForTheExitHook() = runBlocking { + val browser = createBrowser(this, headless = true, sandbox = false) as DefaultBrowser + val profile = File(browser.config.userDataDir.toString()) + val logger = mockk(relaxed = true) + browser.logger = logger + var attempts = 0 + browser.deleteProfile = { + attempts++ + false + } + + browser.stop() + + assertTrue(browser.stopped) + assertEquals(1, attempts) + assertTrue(profile.isDirectory, "a profile that could not be deleted stays on disk") + verify { logger.warn(match { "Could not delete temporary profile" in it && profile.path in it }) } + assertTrue(browser in StartedBrowsers, "the exit hook must try again") + + // The lock is gone by the time the host process exits. + browser.deleteProfile = { deleteTemporaryProfile(it) } + StartedBrowsers.stopAll() + + assertFalse(profile.exists(), "the exit hook deletes it") + assertFalse(browser in StartedBrowsers) + } + + @Test + fun exitHook_stopsRunningBrowsersAndDeletesTheirProfiles() = runBlocking { + val browser = createBrowser(this, headless = true, sandbox = false) + val profile = File(browser.config.userDataDir.toString()) + assertTrue(browser in StartedBrowsers, "a launched browser is stopped on exit") + + // What the shutdown hook runs when the host process exits without calling stop(). + StartedBrowsers.stopAll() + + assertTrue(browser.stopped) + assertFalse(profile.exists(), "the temporary profile must be deleted on exit") + } + + @Test + fun copyOfAConfigKeepsItsTemporaryProfileATemporaryOne() { + val original = Config(browserExecutablePath = Path("/usr/bin/chromium")) + assertFalse(original.createdTemporaryProfile, "nothing is created before the profile is read") + assertFalse(original.copy().createdTemporaryProfile) + val profile = original.userDataDir + try { + assertTrue(original.createdTemporaryProfile) + val copy = original.copy() + assertEquals(profile, copy.userDataDir, "the copy shares the profile…") + assertTrue(copy.createdTemporaryProfile, "…and the browser that runs on it deletes it") + assertFalse(copy.usesCustomDataDir) + } finally { + deleteRecursively(profile) + } + } + + @Test + fun copyOfAConfigWithACustomUserDataDirNeverOwnsIt() { + val custom = Config(browserExecutablePath = Path("/usr/bin/chromium"), userDataDir = Path("/tmp/mine")) + + assertFalse(custom.createdTemporaryProfile) + assertFalse(custom.copy().createdTemporaryProfile) + assertTrue(custom.copy().usesCustomDataDir) + } + + @Test + fun stop_deletesTheProfileEvenWhenTheGracefulCloseFails() = runBlocking { + val browser = createBrowser(this, headless = true, sandbox = false) as DefaultBrowser + val profile = File(browser.config.userDataDir.toString()) + val real = assertNotNull(browser.connection) + val failing = mockk(relaxed = true) + every { failing.generatedDomains } returns mutableMapOf() + coEvery { failing.callCommand("Browser.close", any(), any()) } throws IllegalStateException("close failed") + browser.connection = failing + try { + val failure = assertFailsWith { browser.stop() } + + assertEquals("close failed", failure.message, "the failure is still reported") + assertTrue(browser.stopped, "the process is killed all the same") + assertFalse(profile.exists(), "and its profile deleted") + assertFalse(browser in StartedBrowsers) + coVerify { failing.close() } + } finally { + real.close() + } + } + + @Test + fun stop_deletesTheProfileEvenWhenClosingTheConnectionFails() = runBlocking { + val browser = createBrowser(this, headless = true, sandbox = false) as DefaultBrowser + val profile = File(browser.config.userDataDir.toString()) + val real = assertNotNull(browser.connection) + val failing = mockk(relaxed = true) + every { failing.generatedDomains } returns mutableMapOf() + coEvery { failing.close() } throws IllegalStateException("connection close failed") + browser.connection = failing + try { + val failure = assertFailsWith { browser.stop() } + + assertEquals("connection close failed", failure.message) + assertTrue(browser.stopped) + assertFalse(profile.exists(), "the profile is deleted after a failed step") + assertEquals(null, browser.connection) + } finally { + real.close() + } + } + + @Test + fun exitHook_leavesABrowserItOnlyConnectedTo() = runBlocking { + val owner = createBrowser(this, headless = true, sandbox = false) + val connected = createBrowser(this, Config(host = owner.config.host, port = owner.config.port)) + try { + assertEquals(null, connected.pid, "it connected to the running browser, launched nothing") + assertFalse(connected in StartedBrowsers, "a browser kdriver did not launch is not closed on exit") + assertTrue(owner in StartedBrowsers) + } finally { + connected.detach() + owner.stop() + } + } + + @Test + fun detach_keepsTheProfileTheBrowserStillRunsOn() = runBlocking { + val browser = createBrowser(this, headless = true, sandbox = false) + val profile = File(browser.config.userDataDir.toString()) + val pid = assertNotNull(browser.pid) + val process = assertNotNull(ProcessHandle.of(pid).orElse(null)) + try { + browser.detach() + + assertTrue(process.isAlive, "detach leaves the browser running…") + assertTrue(profile.isDirectory, "…so its profile is kept") + assertFalse(browser in StartedBrowsers, "and the exit hook leaves both alone") + } finally { + // What the owner of a detached browser does: shut it down, then delete its profile. + (process.descendants().toList() + process).forEach { it.destroyForcibly() } + process.onExit().get() + browser.cleanupTemporaryProfile() + } + assertFalse(profile.exists(), "cleanupTemporaryProfile deletes it once the browser has exited") + } + + @Test + fun deleteRecursively_removesNestedContent() { + val root = createTempDirectory(prefix = "kdriver_delete_test_") + Files.createDirectories(root.resolve("Default/Cache")) + root.resolve("Default/Cache/data").writeText("x") + root.resolve("Local State").writeText("{}") + + assertTrue(deleteRecursively(Path(root.toString()))) + assertFalse(root.exists()) + } + + @Test + fun deleteRecursively_doesNotFollowSymbolicLinks() { + val outside = createTempDirectory(prefix = "kdriver_outside_test_") + val kept = outside.resolve("kept").also { it.writeText("keep me") } + val root = createTempDirectory(prefix = "kdriver_delete_test_") + try { + val linked = runCatching { Files.createSymbolicLink(root.resolve("link"), outside) } + // Creating a symbolic link needs a privilege Windows does not grant by default. + if (linked.isFailure) return + + assertTrue(deleteRecursively(Path(root.toString()))) + + assertFalse(root.exists()) + assertTrue(kept.exists(), "what a link points to must never be deleted") + } finally { + root.deleteRecursively() + outside.deleteRecursively() + } + } + + @Test + fun deleteTemporaryProfile_givesUpOnAnEntryItCannotDelete() = runBlocking { + // A read-only directory protects its entries on POSIX only, and never from root. + if (!isPosix() || isRoot()) return@runBlocking + val root = createTempDirectory(prefix = "kdriver_delete_test_") + val locked = Files.createDirectories(root.resolve("locked")) + locked.resolve("file").writeText("x") + locked.toFile().setWritable(false) + try { + assertFalse(deleteTemporaryProfile(Path(root.toString()), attempts = 2, retryDelayMillis = 10)) + assertTrue(locked.resolve("file").exists()) + } finally { + locked.toFile().setWritable(true) + root.deleteRecursively() + } + } + + @Test + fun deleteRecursively_isTrueForAMissingDirectory() { + val missing = createTempDirectory(prefix = "kdriver_missing_test_").also { Files.delete(it) } + + assertTrue(deleteRecursively(Path(missing.toString()))) + } + + @Test + fun deleteTemporaryProfile_retriesUntilTheProfileIsGone() = runTest { + val profile = Path("kdriver_profile") + val seen = mutableListOf() + + val gone = deleteTemporaryProfile(profile, attempts = 5, retryDelayMillis = 200) { + seen += it + seen.size == 3 + } + + assertTrue(gone) + assertEquals(listOf(profile, profile, profile), seen, "stops at the first attempt that succeeds") + assertEquals(400, currentTime, "waits between two attempts") + } + + @Test + fun deleteTemporaryProfile_givesUpAfterItsLastAttempt() = runTest { + var attempts = 0 + + val gone = deleteTemporaryProfile(Path("kdriver_profile"), attempts = 4, retryDelayMillis = 200) { + attempts++ + false + } + + assertFalse(gone) + assertEquals(4, attempts) + assertEquals(600, currentTime, "no wait after the last attempt") + } + + @Test + fun deleteTemporaryProfile_triesForAboutFiveSecondsByDefault() = runTest { + var attempts = 0 + + assertFalse(deleteTemporaryProfile(Path("kdriver_profile")) { attempts++; false }) + + assertEquals(26, attempts) + assertEquals(5_000, currentTime) + } + + @Test + fun exitHook_stopsTheOtherBrowsersWhenOneFailsToStop() = runBlocking { + val scope = this + val unused = Config(browserExecutablePath = Path("unused")) + val failing = object : DefaultBrowser(scope, unused) { + override suspend fun stop() { + error("cannot stop") + } + } + val stopped = mutableListOf() + val others = List(2) { + object : DefaultBrowser(scope, unused) { + override suspend fun stop() { + stopped += this + } + } + } + val all = listOf(failing) + others + all.forEach { StartedBrowsers.register(it) } + try { + StartedBrowsers.stopAll() + + assertEquals(others.toSet(), stopped.toSet(), "a failure must not keep the other browsers running") + } finally { + all.forEach { StartedBrowsers.unregister(it) } + } + } + + /** Ends the browser process behind kdriver's back, as a crash would, and waits until it is gone. */ + private suspend fun killFromOutside(browser: Browser) { + try { + withTimeoutOrNull(5.seconds) { browser.connection?.browser?.close() } + } catch (_: IOException) { + // The browser may drop the connection before it answers: its exit is what is awaited below. + } + withTimeout(10.seconds) { + while (!browser.stopped) delay(50) + } + } + +} diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupBehaviourTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupBehaviourTest.kt index 23d7a4d26..02e686f82 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupBehaviourTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupBehaviourTest.kt @@ -26,7 +26,11 @@ class LookupBehaviourTest { private fun withPage(block: suspend Tab.() -> Unit) = runBlocking { val browser: Browser = createBrowser(this as CoroutineScope, headless = true, sandbox = false) try { - browser.get(sampleFile("lookup-test.html")).block() + // get() returns once the navigation has started: a lookup before the page has loaded would + // find nothing (and time out) rather than reach the document. + val tab = browser.get(sampleFile("lookup-test.html")) + tab.waitForReadyState(ReadyState.COMPLETE) + tab.block() } finally { browser.stop() } diff --git a/core/src/jvmTest/resources/simplelogger.properties b/core/src/jvmTest/resources/simplelogger.properties new file mode 100644 index 000000000..f0acbc7e9 --- /dev/null +++ b/core/src/jvmTest/resources/simplelogger.properties @@ -0,0 +1,3 @@ +org.slf4j.simpleLogger.defaultLogLevel=warn +org.slf4j.simpleLogger.showDateTime=true +org.slf4j.simpleLogger.dateTimeFormat=HH:mm:ss.SSS diff --git a/core/src/linuxMain/kotlin/dev/kdriver/core/browser/DirectoryAccess.linux.kt b/core/src/linuxMain/kotlin/dev/kdriver/core/browser/DirectoryAccess.linux.kt new file mode 100644 index 000000000..cccfaf7fc --- /dev/null +++ b/core/src/linuxMain/kotlin/dev/kdriver/core/browser/DirectoryAccess.linux.kt @@ -0,0 +1,55 @@ +// One actual per POSIX target, named after the expect object it implements. +@file:Suppress("MatchingDeclarationName") + +package dev.kdriver.core.browser + +import kotlinx.cinterop.ExperimentalForeignApi +import kotlinx.cinterop.UnsafeNumber +import kotlinx.cinterop.convert +import platform.posix.* + +/** + * Kotlin/Native exposes none of the `*at` functions on Linux, so they go through `/proc/self/fd`: + * `/proc/self/fd//` resolves `` to exactly the directory that descriptor is + * open on, then looks `` up in it, which is what `openat`, `unlinkat` and `fchmodat` do (glibc + * implements `fchmodat` this way too). + * + * Without `/proc` (some minimal containers), the entry's full path is used instead. A path is only + * as safe as its parents then; the profile directory is created with owner-only permissions, so + * only its owner could change them during the walk. + */ +@OptIn(ExperimentalForeignApi::class, UnsafeNumber::class) +internal actual object DirectoryAccess { + + actual fun openDirectory(entry: Entry): Int = + open(entry.resolved(), O_RDONLY or O_DIRECTORY or O_NOFOLLOW or O_CLOEXEC) + + actual fun grantOwnerAccess(entry: Entry): Boolean { + // A descriptor that only designates the directory (O_PATH needs no permission on it); with + // O_NOFOLLOW and O_DIRECTORY, a link that replaced it is refused. Its /proc link then names + // exactly that directory, whatever happens to the path. + val fd = open(entry.resolved(), O_PATH or O_DIRECTORY or O_NOFOLLOW or O_CLOEXEC) + if (fd < 0) return false + return try { + chmod("$PROC_FDS/$fd", S_IRWXU.convert()) == 0 + } finally { + close(fd) + } + } + + actual fun remove(entry: Entry, directory: Boolean) { + // unlink and rmdir never follow a link in place of the last component. + if (directory) rmdir(entry.resolved()) else unlink(entry.resolved()) + } + + private fun Entry.resolved(): String = + if (parentFd == NO_PARENT || !procAvailable) path else "$PROC_FDS/$parentFd/$name" + + private val procAvailable: Boolean by lazy { access("$PROC_FDS/", F_OK) == 0 } + + private const val PROC_FDS = "/proc/self/fd" + + /** From the kernel's `fcntl.h`, the same on x86-64 and arm64; glibc's headers hide it here. */ + private const val O_PATH = 0x200000 + +} diff --git a/core/src/linuxMain/kotlin/dev/kdriver/core/browser/Process.linux.kt b/core/src/linuxMain/kotlin/dev/kdriver/core/browser/Process.linux.kt index 077cd35b9..bee364153 100644 --- a/core/src/linuxMain/kotlin/dev/kdriver/core/browser/Process.linux.kt +++ b/core/src/linuxMain/kotlin/dev/kdriver/core/browser/Process.linux.kt @@ -6,8 +6,27 @@ import kotlinx.coroutines.IO import kotlinx.coroutines.withContext import kotlinx.io.files.Path import platform.posix.* +import kotlin.concurrent.Volatile private class PosixProcess(override val processIdentifier: Int) : Process() { + @Volatile + private var reaped = false + + /** + * Reaps the child once it has exited. Nothing else waits for it here, so without this it stays a + * zombie and [isAlive] never turns false. Remembered, because the pid may be reused afterwards. + * + * Only ever set to true: when two threads race, the loser gets `ECHILD` (already reaped), which + * means exited too. + */ + @OptIn(ExperimentalForeignApi::class) + override fun hasExited(): Boolean { + if (reaped) return true + val result = waitpid(processIdentifier, null, WNOHANG) + if (result == processIdentifier || (result == -1 && errno == ECHILD)) reaped = true + return reaped + } + override fun destroy() { if (isAlive()) { kill(processIdentifier, SIGTERM) diff --git a/core/src/linuxTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt b/core/src/linuxTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt new file mode 100644 index 000000000..400105b68 --- /dev/null +++ b/core/src/linuxTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt @@ -0,0 +1,30 @@ +package dev.kdriver.core.browser + +import kotlinx.coroutines.runBlocking +import kotlinx.io.files.SystemFileSystem +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * The temporary profile is deleted by this platform's own recursive delete once the browser stops. + */ +class TemporaryProfileTest { + + /** The profile is gone after `stop()`; stopping or cleaning up again is harmless. */ + @Test + fun stopDeletesTheTemporaryProfile() = runBlocking { + val browser = createBrowser(this, headless = true, sandbox = false) + val profile = browser.config.userDataDir + assertTrue(SystemFileSystem.exists(profile), "the browser runs on a temporary profile") + + browser.stop() + assertFalse(SystemFileSystem.exists(profile), "the temporary profile must be deleted by stop()") + + // Stopping or cleaning up again is harmless. + browser.stop() + browser.cleanupTemporaryProfile() + assertFalse(SystemFileSystem.exists(profile)) + } + +} diff --git a/core/src/macosMain/kotlin/dev/kdriver/core/browser/DirectoryAccess.macos.kt b/core/src/macosMain/kotlin/dev/kdriver/core/browser/DirectoryAccess.macos.kt new file mode 100644 index 000000000..98075e1b4 --- /dev/null +++ b/core/src/macosMain/kotlin/dev/kdriver/core/browser/DirectoryAccess.macos.kt @@ -0,0 +1,35 @@ +// One actual per POSIX target, named after the expect object it implements. +@file:Suppress("MatchingDeclarationName") + +package dev.kdriver.core.browser + +import kotlinx.cinterop.ExperimentalForeignApi +import kotlinx.cinterop.UnsafeNumber +import kotlinx.cinterop.convert +import platform.posix.* + +/** + * The `*at` functions, except `openat`, which Kotlin/Native does not expose on macOS: a directory is + * opened through its whole path instead, with `O_NOFOLLOW_ANY`, which refuses a symbolic link in any + * component of the path and so keeps the walk inside the profile just as well. The walk starts from a + * path whose parent is canonical, free of links (`$TMPDIR` itself is under `/var`, a link). + * + * `O_NOFOLLOW_ANY` alone: it already covers the last component, and macOS refuses it combined with + * `O_NOFOLLOW` (`EINVAL`). + */ +@OptIn(ExperimentalForeignApi::class, UnsafeNumber::class) +internal actual object DirectoryAccess { + + actual fun openDirectory(entry: Entry): Int = + open(entry.path, O_RDONLY or O_DIRECTORY or O_NOFOLLOW_ANY or O_CLOEXEC) + + actual fun grantOwnerAccess(entry: Entry): Boolean = + fchmodat(entry.dirFd(), entry.name, S_IRWXU.convert(), AT_SYMLINK_NOFOLLOW) == 0 + + actual fun remove(entry: Entry, directory: Boolean) { + unlinkat(entry.dirFd(), entry.name, if (directory) AT_REMOVEDIR else 0) + } + + private fun Entry.dirFd(): Int = if (parentFd == NO_PARENT) AT_FDCWD else parentFd + +} diff --git a/core/src/macosMain/kotlin/dev/kdriver/core/browser/Process.macos.kt b/core/src/macosMain/kotlin/dev/kdriver/core/browser/Process.macos.kt index 9421248ba..ffda98045 100644 --- a/core/src/macosMain/kotlin/dev/kdriver/core/browser/Process.macos.kt +++ b/core/src/macosMain/kotlin/dev/kdriver/core/browser/Process.macos.kt @@ -13,6 +13,9 @@ private class NSTaskProcess(private val task: NSTask) : Process() { override val processIdentifier: Int get() = task.processIdentifier + /** NSTask reaps its own child, and knows when it has exited. */ + override fun hasExited(): Boolean = !task.isRunning() + override fun destroy() { if (task.isRunning()) { task.terminate() diff --git a/core/src/macosTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt b/core/src/macosTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt new file mode 100644 index 000000000..400105b68 --- /dev/null +++ b/core/src/macosTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt @@ -0,0 +1,30 @@ +package dev.kdriver.core.browser + +import kotlinx.coroutines.runBlocking +import kotlinx.io.files.SystemFileSystem +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * The temporary profile is deleted by this platform's own recursive delete once the browser stops. + */ +class TemporaryProfileTest { + + /** The profile is gone after `stop()`; stopping or cleaning up again is harmless. */ + @Test + fun stopDeletesTheTemporaryProfile() = runBlocking { + val browser = createBrowser(this, headless = true, sandbox = false) + val profile = browser.config.userDataDir + assertTrue(SystemFileSystem.exists(profile), "the browser runs on a temporary profile") + + browser.stop() + assertFalse(SystemFileSystem.exists(profile), "the temporary profile must be deleted by stop()") + + // Stopping or cleaning up again is harmless. + browser.stop() + browser.cleanupTemporaryProfile() + assertFalse(SystemFileSystem.exists(profile)) + } + +} diff --git a/core/src/macosTest/kotlin/dev/kdriver/core/tab/TabTest.kt b/core/src/macosTest/kotlin/dev/kdriver/core/tab/TabTest.kt deleted file mode 100644 index da534b4a9..000000000 --- a/core/src/macosTest/kotlin/dev/kdriver/core/tab/TabTest.kt +++ /dev/null @@ -1,19 +0,0 @@ -package dev.kdriver.core.tab - -import dev.kdriver.core.browser.createBrowser -import kotlinx.coroutines.runBlocking -import kotlin.test.Test -import kotlin.test.assertTrue - -class TabTest { - - @Test - fun testGetContentGetsHtmlContent() = runBlocking { - val browser = createBrowser(this, headless = true, sandbox = false) - val tab = browser.get("https://example.com") - val content = tab.getContent() - assertTrue(content.lowercase().startsWith("")) - browser.stop() - } - -} diff --git a/core/src/mingwMain/kotlin/dev/kdriver/core/browser/Process.mingw.kt b/core/src/mingwMain/kotlin/dev/kdriver/core/browser/Process.mingw.kt index c62e3b8f8..6eef34ada 100644 --- a/core/src/mingwMain/kotlin/dev/kdriver/core/browser/Process.mingw.kt +++ b/core/src/mingwMain/kotlin/dev/kdriver/core/browser/Process.mingw.kt @@ -8,6 +8,9 @@ import kotlinx.io.files.Path import platform.posix.getenv import platform.posix.memset import platform.windows.* +import kotlin.concurrent.Volatile +import kotlin.experimental.ExperimentalNativeApi +import kotlin.native.ref.createCleaner import kotlin.random.Random @OptIn(ExperimentalForeignApi::class) @@ -15,14 +18,21 @@ actual abstract class Process { abstract val processHandle: HANDLE? abstract val processId: DWORD + /** The exit code, once the process has been seen to exit. */ + @Volatile + internal var exitCode: DWORD? = null + private set + actual fun isAlive(): Boolean { - val handle = processHandle ?: return false - val exitCode = memScoped { - val code = alloc() - GetExitCodeProcess(handle, code.ptr) - code.value - } - return exitCode == STILL_ACTIVE + // Null once the exit was seen, without a handle, or if unreadable: not alive in all three cases. + val code = if (exitCode == null) processHandle?.let { readExitCode(it) } else null + if (code != null && code != STILL_ACTIVE) exitCode = code + return code == STILL_ACTIVE + } + + private fun readExitCode(handle: HANDLE): DWORD? = memScoped { + val c = alloc() + if (GetExitCodeProcess(handle, c.ptr) == 0) null else c.value } actual fun pid(): Long { @@ -32,18 +42,23 @@ actual abstract class Process { actual abstract fun destroy() } -@OptIn(ExperimentalForeignApi::class) +@OptIn(ExperimentalForeignApi::class, ExperimentalNativeApi::class) private class WindowsProcess( override val processHandle: HANDLE?, override val processId: DWORD, ) : Process() { + /** + * Closes the process handle once this object is unreachable, and never before: [isAlive] reads + * the exit code through it (to know when the process is really gone, and its profile can be + * deleted) and [destroy] terminates through it, from any thread, for as long as the object is + * used. Closing it any earlier would race them onto a closed, or reused, handle. + */ + @Suppress("unused") + private val handleCleaner = processHandle?.let { handle -> createCleaner(handle) { CloseHandle(it) } } + override fun destroy() { - processHandle?.let { - if (isAlive()) { - TerminateProcess(it, 1u) - } - CloseHandle(it) - } + val handle = processHandle ?: return + if (isAlive()) TerminateProcess(handle, 1u) } } @@ -62,19 +77,11 @@ actual suspend fun Process.readStderrSnapshot(maxBytes: Int, timeoutMillis: Long * the one running browsers in production, uses `ProcessHandle.descendants()` for that. */ /** - * Reads the exit status via `GetExitCodeProcess`, the same call [Process.isAlive] uses — null while - * it still reports `STILL_ACTIVE`. + * Reads the exit status recorded by [Process.isAlive] through `GetExitCodeProcess` — null while the + * process still runs. */ @OptIn(ExperimentalForeignApi::class) -actual fun Process.exitCodeOrNull(): Int? { - val handle = processHandle ?: return null - val code = memScoped { - val c = alloc() - GetExitCodeProcess(handle, c.ptr) - c.value - } - return if (code == STILL_ACTIVE) null else code.toInt() -} +actual fun Process.exitCodeOrNull(): Int? = if (isAlive()) null else exitCode?.toInt() @OptIn(ExperimentalForeignApi::class) actual fun Process.killTree() { @@ -147,7 +154,8 @@ actual fun isRoot(): Boolean { @OptIn(ExperimentalForeignApi::class) actual fun tempProfileDir(): Path { - val tempDir = getEnv("TEMP") ?: getEnv("TMP") ?: "C:\\Temp" + // Without a trailing separator, which would double the one added below. + val tempDir = (getEnv("TEMP") ?: getEnv("TMP") ?: "C:\\Temp").trimEnd('\\', '/') val uniqueName = "kdriver_${Random.nextLong().toString(16)}" val profilePath = "$tempDir\\$uniqueName" diff --git a/core/src/mingwMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.mingw.kt b/core/src/mingwMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.mingw.kt new file mode 100644 index 000000000..2367449b7 --- /dev/null +++ b/core/src/mingwMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.mingw.kt @@ -0,0 +1,98 @@ +package dev.kdriver.core.browser + +import kotlinx.cinterop.* +import kotlinx.io.files.Path +import platform.windows.* + +/** + * Every path goes through [extendedLengthPath]: a profile nests deep enough (extension and cache + * directories) to pass the 260 characters a plain path is limited to, and such entries would be left. + */ +@OptIn(ExperimentalForeignApi::class) +internal actual fun deleteRecursively(path: Path): Boolean { + val target = extendedLengthPath(path.toString()) + deleteEntry(target) + return isGone(target) +} + +/** Only when the system says the entry does not exist: an invalid path or a denied access is not gone. */ +@OptIn(ExperimentalForeignApi::class) +private fun isGone(path: String): Boolean { + if (GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES) return false + val error = GetLastError() + return error == ERROR_FILE_NOT_FOUND.toUInt() || error == ERROR_PATH_NOT_FOUND.toUInt() +} + +/** + * [path] in the `\\?\` form, which the wide Windows file functions accept beyond `MAX_PATH` (260 + * characters) without any system setting. That form is taken literally, with no normalisation, so + * separators are made single backslashes first. A relative path cannot take it and is returned as is + * (a temporary profile is always absolute). + */ +internal fun extendedLengthPath(path: String): String { + val slashes = path.replace('/', '\\') + // A leading pair is the start of a UNC, extended or device path: kept, the rest collapsed. + val lead = if (slashes.startsWith("\\\\")) "\\\\" else "" + val windowsPath = lead + collapseSeparators(slashes.substring(lead.length)) + return when { + windowsPath.startsWith(EXTENDED_PREFIX) || windowsPath.startsWith(DEVICE_PREFIX) -> windowsPath + // \\server\share\... becomes \\?\UNC\server\share\... + windowsPath.startsWith("\\\\") -> EXTENDED_PREFIX + "UNC\\" + windowsPath.removePrefix("\\\\") + isDriveAbsolute(windowsPath) -> EXTENDED_PREFIX + windowsPath + else -> windowsPath + } +} + +private const val EXTENDED_PREFIX = "\\\\?\\" +private const val DEVICE_PREFIX = "\\\\.\\" + +/** `C:\\...`: a drive letter, a colon and a separator. */ +private fun isDriveAbsolute(path: String): Boolean = + path.getOrNull(0)?.isLetter() == true && path.getOrNull(1) == ':' && path.getOrNull(2) == '\\' + +private fun collapseSeparators(path: String): String = buildString(path.length) { + path.forEach { c -> if (c != '\\' || lastOrNull() != '\\') append(c) } +} + +/** + * Deletes [path], and its content first if it is a directory. A junction or symbolic link (a reparse + * point) is removed itself, never followed. + */ +@OptIn(ExperimentalForeignApi::class) +private fun deleteEntry(path: String) { + val attributes = GetFileAttributesW(path) + if (attributes == INVALID_FILE_ATTRIBUTES) return + // DeleteFileW and RemoveDirectoryW both refuse a read-only entry. + val readOnly = FILE_ATTRIBUTE_READONLY.toUInt() + if (attributes and readOnly != 0u) SetFileAttributesW(path, attributes and readOnly.inv()) + + val isDirectory = attributes and FILE_ATTRIBUTE_DIRECTORY.toUInt() != 0u + val isLink = attributes and FILE_ATTRIBUTE_REPARSE_POINT.toUInt() != 0u + when { + isDirectory && !isLink -> { + children(path).forEach { deleteEntry("$path\\$it") } + RemoveDirectoryW(path) + } + + isDirectory -> RemoveDirectoryW(path) + else -> DeleteFileW(path) + } +} + +/** Lists the names in [path], read in full before anything is deleted from it. */ +@OptIn(ExperimentalForeignApi::class) +private fun children(path: String): List = memScoped { + val data = alloc() + val handle = FindFirstFileW("$path\\*", data.ptr) + if (handle == null || handle == INVALID_HANDLE_VALUE) return@memScoped emptyList() + val names = mutableListOf() + try { + do { + val name = data.cFileName.toKStringFromUtf16() + if (name != "." && name != "..") names += name + } while (FindNextFileW(handle, data.ptr) != 0) + } finally { + FindClose(handle) + } + names +} diff --git a/core/src/mingwTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt b/core/src/mingwTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt new file mode 100644 index 000000000..400105b68 --- /dev/null +++ b/core/src/mingwTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt @@ -0,0 +1,30 @@ +package dev.kdriver.core.browser + +import kotlinx.coroutines.runBlocking +import kotlinx.io.files.SystemFileSystem +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * The temporary profile is deleted by this platform's own recursive delete once the browser stops. + */ +class TemporaryProfileTest { + + /** The profile is gone after `stop()`; stopping or cleaning up again is harmless. */ + @Test + fun stopDeletesTheTemporaryProfile() = runBlocking { + val browser = createBrowser(this, headless = true, sandbox = false) + val profile = browser.config.userDataDir + assertTrue(SystemFileSystem.exists(profile), "the browser runs on a temporary profile") + + browser.stop() + assertFalse(SystemFileSystem.exists(profile), "the temporary profile must be deleted by stop()") + + // Stopping or cleaning up again is harmless. + browser.stop() + browser.cleanupTemporaryProfile() + assertFalse(SystemFileSystem.exists(profile)) + } + +} diff --git a/core/src/mingwTest/kotlin/dev/kdriver/core/browser/WindowsDeleteRecursivelyTest.kt b/core/src/mingwTest/kotlin/dev/kdriver/core/browser/WindowsDeleteRecursivelyTest.kt new file mode 100644 index 000000000..20f1b42ed --- /dev/null +++ b/core/src/mingwTest/kotlin/dev/kdriver/core/browser/WindowsDeleteRecursivelyTest.kt @@ -0,0 +1,103 @@ +package dev.kdriver.core.browser + +import kotlinx.cinterop.ExperimentalForeignApi +import kotlinx.cinterop.toKString +import kotlinx.io.files.Path +import platform.posix.getenv +import platform.windows.* +import kotlin.random.Random +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotEquals +import kotlin.test.assertTrue + +/** The Windows recursive delete of a temporary profile. */ +@OptIn(ExperimentalForeignApi::class) +class WindowsDeleteRecursivelyTest { + + /** Entries nested past `MAX_PATH` are deleted, through the extended-length form. */ + @Test + fun removesEntriesBeyondTheMaxPathLimit() { + val root = "${tempBase()}\\kdriver_long_path_test_${randomSuffix()}" + // Nested well past 260 characters, as a profile's extension or cache directories can be. + var deepest = root + createDirectory(root) + repeat(LEVELS) { level -> + deepest = "$deepest\\${"d$level".padEnd(LEVEL_NAME_LENGTH, 'x')}" + createDirectory(deepest) + } + assertTrue(deepest.length > MAX_PATH, "the test path must pass MAX_PATH, is ${deepest.length}") + val file = "$deepest\\Cookies" + val handle: HANDLE? = CreateFileW( + extendedLengthPath(file), + GENERIC_WRITE.toUInt(), + 0u, + null, + CREATE_NEW.toUInt(), + FILE_ATTRIBUTE_NORMAL.toUInt(), + null, + ) + assertTrue(handle != null && handle != INVALID_HANDLE_VALUE, "create $file, error ${GetLastError()}") + CloseHandle(handle) + + assertTrue(deleteRecursively(Path(root)), "every entry is deleted, however deep") + assertEquals(INVALID_FILE_ATTRIBUTES, GetFileAttributesW(extendedLengthPath(root))) + } + + /** The extended-length form of drive, UNC, already extended, device and relative paths. */ + @Test + fun extendedLengthPathPrefixesAbsolutePathsOnly() { + assertEquals("\\\\?\\C:\\Temp\\kdriver_1", extendedLengthPath("C:\\Temp\\kdriver_1")) + assertEquals("\\\\?\\C:\\Temp\\kdriver_1", extendedLengthPath("C:/Temp/kdriver_1")) + assertEquals("\\\\?\\UNC\\server\\share\\kdriver_1", extendedLengthPath("\\\\server\\share\\kdriver_1")) + assertEquals("\\\\?\\C:\\already", extendedLengthPath("\\\\?\\C:\\already")) + assertEquals("\\\\.\\device", extendedLengthPath("\\\\.\\device")) + assertEquals("relative\\kdriver_1", extendedLengthPath("relative/kdriver_1")) + // The extended form is taken literally: a doubled separator (TEMP ending with one) would break it. + assertEquals("\\\\?\\C:\\Temp\\kdriver_1", extendedLengthPath("C:\\Temp\\\\kdriver_1")) + assertEquals("\\\\?\\UNC\\server\\share\\kdriver_1", extendedLengthPath("\\\\server\\share\\\\kdriver_1")) + } + + /** A doubled separator, which the extended-length form would take literally, is collapsed. */ + @Test + fun removesAProfileWhosePathHasADoubledSeparator() { + val name = "kdriver_double_separator_test_${randomSuffix()}" + createDirectory("${tempBase()}\\$name") + createDirectory("${tempBase()}\\$name\\Default") + + assertTrue(deleteRecursively(Path("${tempBase()}\\\\$name"))) + assertEquals(INVALID_FILE_ATTRIBUTES, GetFileAttributesW(extendedLengthPath("${tempBase()}\\$name"))) + } + + /** Only a missing entry counts as deleted, not one the system refuses to reach. */ + @Test + fun aProfileThatCannotBeReachedIsNotReportedGone() { + // An invalid name, not a missing one: deleting it fails, and must not count as done. + assertFalse(deleteRecursively(Path("C:\\kdriver_invalid_"))) + } + + /** `TEMP` ending with a separator does not double it in the profile path. */ + @Test + fun tempProfileDirHasNoDoubledSeparator() { + assertFalse("\\\\" in tempProfileDir().toString().removePrefix("\\\\")) + } + + private fun randomSuffix(): String = Random.nextLong().toString(HEX) + + private fun tempBase(): String = + (getenv("TEMP") ?: getenv("TMP"))?.toKString()?.trimEnd('\\', '/') ?: "C:\\Temp" + + private fun createDirectory(path: String) { + assertNotEquals(0, CreateDirectoryW(extendedLengthPath(path), null), "create $path, error ${GetLastError()}") + } + + private companion object { + /** Eight levels of 40 characters: well past the 260 of `MAX_PATH`. */ + const val LEVELS = 8 + const val LEVEL_NAME_LENGTH = 40 + const val MAX_PATH = 260 + const val HEX = 16 + } + +} diff --git a/core/src/nativeMain/kotlin/dev/kdriver/core/browser/FileSystemDispatcher.native.kt b/core/src/nativeMain/kotlin/dev/kdriver/core/browser/FileSystemDispatcher.native.kt new file mode 100644 index 000000000..0c6be109d --- /dev/null +++ b/core/src/nativeMain/kotlin/dev/kdriver/core/browser/FileSystemDispatcher.native.kt @@ -0,0 +1,7 @@ +package dev.kdriver.core.browser + +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO + +internal actual val fileSystemDispatcher: CoroutineDispatcher = Dispatchers.IO diff --git a/core/src/posixMain/kotlin/dev/kdriver/core/browser/Process.posix.kt b/core/src/posixMain/kotlin/dev/kdriver/core/browser/Process.posix.kt index 61b2f1e21..75ece61bb 100644 --- a/core/src/posixMain/kotlin/dev/kdriver/core/browser/Process.posix.kt +++ b/core/src/posixMain/kotlin/dev/kdriver/core/browser/Process.posix.kt @@ -9,10 +9,17 @@ actual abstract class Process { abstract val processIdentifier: Int actual fun isAlive(): Boolean { + if (hasExited()) return false // Check if process exists by sending signal 0 return kill(processIdentifier, 0) == 0 } + /** + * Whether the process is known to have exited. Signal 0 alone cannot tell: a child that exited + * but was not reaped yet (a zombie) still has its pid, so it would look alive forever. + */ + protected open fun hasExited(): Boolean = false + actual fun pid(): Long { return processIdentifier.toLong() } @@ -93,11 +100,15 @@ actual fun exists(path: Path): Boolean { @OptIn(ExperimentalForeignApi::class, UnsafeNumber::class) actual fun tempProfileDir(): Path { - val tempDir = getenv("TMPDIR")?.toKString() ?: "/tmp" + // Without a trailing separator ($TMPDIR has one on macOS), which would double the one added below + // ("/" becomes "", so the profile is created right under it). + val tempDir = (getenv("TMPDIR")?.toKString() ?: "/tmp").trimEnd('/') val uniqueName = "kdriver_${Random.nextLong().toString(16)}" val profilePath = "$tempDir/$uniqueName" - mkdir(profilePath, 0x1FFu) // 0777 permissions + // Owner only, like the profiles Chrome creates: nobody else may list it, nor add entries (such as + // a symbolic link) that its deletion would then have to deal with. + mkdir(profilePath, S_IRWXU.convert()) return Path(profilePath) } diff --git a/core/src/posixMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.posix.kt b/core/src/posixMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.posix.kt new file mode 100644 index 000000000..52b608c1f --- /dev/null +++ b/core/src/posixMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.posix.kt @@ -0,0 +1,135 @@ +package dev.kdriver.core.browser + +import kotlinx.cinterop.* +import kotlinx.io.files.Path +import platform.posix.* + +/** + * Every entry is reached from its parent's open descriptor, never through a path that could be + * changed during the walk (see [DirectoryAccess]): an entry replaced by a symbolic link between two + * steps is unlinked, never followed, so nothing outside the profile is ever deleted, listed, or has + * its mode changed. + */ +@OptIn(ExperimentalForeignApi::class) +internal actual fun deleteRecursively(path: Path): Boolean { + val target = path.toString().trimEnd('/').ifEmpty { "/" } + val root = withCanonicalParent(target) + deleteEntry(Entry(NO_PARENT, root, root)) + return !entryExists(target) +} + +/** + * [path] with its parent directory in canonical form, free of symbolic links (on macOS `$TMPDIR` is + * under `/var`, itself a link), so that a link met during the walk can only be one that appeared + * inside the profile. The last component is kept as is: a profile that is itself a link is unlinked, + * not followed. + */ +@OptIn(ExperimentalForeignApi::class) +private fun withCanonicalParent(path: String): String { + val slash = path.lastIndexOf('/') + val parent = if (slash == 0) "/" else path.substring(0, slash.coerceAtLeast(0)) + // A buffer of our own: the realpath Kotlin/Native binds on macOS is the legacy one, which refuses + // a null buffer. + val canonical = if (slash < 0) null else memScoped { + val buffer = allocArray(PATH_MAX + 1) + realpath(parent, buffer)?.toKString() + } + return canonical?.let { "${it.trimEnd('/')}/${path.substring(slash + 1)}" } ?: path +} + +/** + * An entry of the walk: [name] in the directory open as [parentFd], or the root [path] itself when + * [parentFd] is [NO_PARENT]. [path] is the same entry from the root, for messages and for the + * platforms without `*at` functions. + */ +internal class Entry(val parentFd: Int, val name: String, val path: String) + +/** [Entry.parentFd] of the root of the walk, which is reached through its path. */ +internal const val NO_PARENT = -1 + +/** + * The `*at` operations the walk needs, which each POSIX target provides its own way: none of them + * follows a symbolic link in place of [Entry.name], nor resolves [Entry.name] anywhere but in the + * directory open as [Entry.parentFd]. + */ +internal expect object DirectoryAccess { + /** Opens [entry] if it is a real directory, or returns -1 with `errno` set. */ + fun openDirectory(entry: Entry): Int + + /** Gives the owner read, write and search permission on the directory [entry]. */ + fun grantOwnerAccess(entry: Entry): Boolean + + /** Removes [entry]: an empty directory if [directory], else a file or a link. */ + fun remove(entry: Entry, directory: Boolean) +} + +/** + * Deletes [entry], and its content first if it is a directory. Best effort: an entry that cannot be + * deleted is left, and the walk goes on. + */ +@OptIn(ExperimentalForeignApi::class) +private fun deleteEntry(entry: Entry) { + val dirFd = openDirectory(entry) + if (dirFd < 0) { + // Not a directory, a symbolic link (refused), or already gone: unlink it as it is. + DirectoryAccess.remove(entry, directory = false) + return + } + deleteChildren(dirFd, entry.path) + DirectoryAccess.remove(entry, directory = true) +} + +/** + * Opens [entry] if it is a real directory (not a link to one), or returns -1. + * + * A directory without read permission cannot be opened: it is ours (inside the profile we created), + * so we give ourselves access first, without following a link that may have replaced it since. + */ +@OptIn(ExperimentalForeignApi::class) +private fun openDirectory(entry: Entry): Int { + val fd = DirectoryAccess.openDirectory(entry) + return when { + fd >= 0 || errno != EACCES -> fd + DirectoryAccess.grantOwnerAccess(entry) -> DirectoryAccess.openDirectory(entry) + else -> -1 + } +} + +/** + * Deletes everything in the directory open as [dirFd], then closes it. The names are read in full + * before anything is deleted. + */ +@OptIn(ExperimentalForeignApi::class, UnsafeNumber::class) +private fun deleteChildren(dirFd: Int, path: String) { + // Emptying a directory needs write and search permission on it, on top of read to list it. The + // mode is changed through the descriptor, so on the very directory that was opened. + memScoped { + val info = alloc() + val ownerAccess = S_IRWXU.convert() + if (fstat(dirFd, info.ptr) == 0 && (info.st_mode.convert() and ownerAccess) != ownerAccess) { + fchmod(dirFd, (info.st_mode.convert() or ownerAccess).convert()) + } + } + // fdopendir takes over the descriptor: closedir closes it. + val dir = fdopendir(dirFd) ?: run { + close(dirFd) + return + } + try { + val names = mutableListOf() + while (true) { + val entry = readdir(dir) ?: break + val name = entry.pointed.d_name.toKString() + if (name != "." && name != "..") names += name + } + names.forEach { deleteEntry(Entry(dirFd, it, "$path/$it")) } + } finally { + closedir(dir) + } +} + +@OptIn(ExperimentalForeignApi::class) +private fun entryExists(path: String): Boolean = memScoped { + val info = alloc() + lstat(path, info.ptr) == 0 +} diff --git a/core/src/posixTest/kotlin/dev/kdriver/core/browser/PosixDeleteRecursivelyTest.kt b/core/src/posixTest/kotlin/dev/kdriver/core/browser/PosixDeleteRecursivelyTest.kt new file mode 100644 index 000000000..82eae1059 --- /dev/null +++ b/core/src/posixTest/kotlin/dev/kdriver/core/browser/PosixDeleteRecursivelyTest.kt @@ -0,0 +1,123 @@ +package dev.kdriver.core.browser + +import kotlinx.cinterop.* +import kotlinx.io.files.Path +import platform.posix.* +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** The POSIX recursive delete of a temporary profile, on the native targets. */ +@OptIn(ExperimentalForeignApi::class, UnsafeNumber::class) +class PosixDeleteRecursivelyTest { + + /** Directories and files at several levels are all deleted. */ + @Test + fun removesNestedContent() { + val root = tempDir("kdriver_delete_test_") + makeDir("$root/Default") + makeDir("$root/Default/Cache") + writeFile("$root/Default/Cache/data") + writeFile("$root/Local State") + + assertTrue(deleteRecursively(Path(root))) + assertFalse(exists(root)) + } + + /** A directory of the profile without read, or without write and search permission, is made deletable. */ + @Test + fun removesADirectoryItCannotListAtFirst() { + // A permission check that root bypasses: nothing to prove there. + if (getuid() == 0u) return + val root = tempDir("kdriver_delete_test_") + makeDir("$root/locked") + writeFile("$root/locked/file") + chmod("$root/locked", 0.convert()) + makeDir("$root/searchOnly") + writeFile("$root/searchOnly/file") + chmod("$root/searchOnly", S_IRUSR.convert()) + + assertTrue(deleteRecursively(Path(root)), "an entry of our own profile is made deletable first") + assertFalse(exists(root)) + } + + /** A link inside the profile is unlinked: its target is neither deleted nor has its mode changed. */ + @Test + fun neverFollowsNorChangesWhatALinkPointsTo() { + val outside = tempDir("kdriver_outside_test_") + writeFile("$outside/kept") + // Read-only, so a delete that followed the link would have to chmod it first. + chmod(outside, (S_IRUSR or S_IXUSR).convert()) + val root = tempDir("kdriver_delete_test_") + try { + assertEquals(0, symlink(outside, "$root/link")) + + assertTrue(deleteRecursively(Path(root))) + + assertFalse(exists(root)) + assertTrue(exists("$outside/kept"), "what a link points to must never be deleted") + assertEquals(S_IRUSR or S_IXUSR, modeOf(outside) and S_IRWXU, "nor have its mode changed") + } finally { + chmod(outside, S_IRWXU.convert()) + deleteRecursively(Path(outside)) + } + } + + /** A profile path that is itself a link is unlinked, not followed. */ + @Test + fun removesARootThatIsALinkWithoutFollowingIt() { + val outside = tempDir("kdriver_outside_test_") + writeFile("$outside/kept") + val link = "${tempDir("kdriver_link_parent_")}/profile" + try { + assertEquals(0, symlink(outside, link)) + + assertTrue(deleteRecursively(Path(link))) + + assertFalse(exists(link)) + assertTrue(exists("$outside/kept")) + } finally { + deleteRecursively(Path(outside)) + deleteRecursively(Path(link.substringBeforeLast('/'))) + } + } + + /** Nothing to delete counts as deleted. */ + @Test + fun isTrueForAMissingDirectory() { + val missing = tempDir("kdriver_missing_test_").also { rmdir(it) } + + assertTrue(deleteRecursively(Path(missing))) + } + + private fun tempDir(prefix: String): String { + val base = getenv("TMPDIR")?.toKString()?.trimEnd('/')?.takeIf { it.isNotEmpty() } ?: "/tmp" + val template = "$base/${prefix}XXXXXX".cstr + return memScoped { + val buffer = template.getPointer(this) + mkdtemp(buffer)?.toKString() ?: error("mkdtemp failed: errno $errno") + } + } + + private fun makeDir(path: String) { + assertEquals(0, mkdir(path, S_IRWXU.convert()), "mkdir $path") + } + + private fun writeFile(path: String) { + val file = fopen(path, "w") ?: error("fopen $path failed: errno $errno") + fputs("x", file) + fclose(file) + } + + private fun exists(path: String): Boolean = memScoped { + lstat(path, alloc().ptr) == 0 + } + + private fun modeOf(path: String): Int = memScoped { + val info = alloc() + check(lstat(path, info.ptr) == 0) + info.st_mode.convert() + } + +} diff --git a/core/src/linuxTest/kotlin/dev/kdriver/core/tab/TabTest.kt b/core/src/posixTest/kotlin/dev/kdriver/core/tab/TabTest.kt similarity index 67% rename from core/src/linuxTest/kotlin/dev/kdriver/core/tab/TabTest.kt rename to core/src/posixTest/kotlin/dev/kdriver/core/tab/TabTest.kt index da534b4a9..9b4d18706 100644 --- a/core/src/linuxTest/kotlin/dev/kdriver/core/tab/TabTest.kt +++ b/core/src/posixTest/kotlin/dev/kdriver/core/tab/TabTest.kt @@ -5,12 +5,16 @@ import kotlinx.coroutines.runBlocking import kotlin.test.Test import kotlin.test.assertTrue +/** Tab tests on the native POSIX targets (macOS, Linux). */ class TabTest { + /** The page's HTML, once it has loaded. */ @Test fun testGetContentGetsHtmlContent() = runBlocking { val browser = createBrowser(this, headless = true, sandbox = false) val tab = browser.get("https://example.com") + // get() returns once the navigation has started: read the document once it has loaded. + tab.waitForReadyState(ReadyState.COMPLETE) val content = tab.getContent() assertTrue(content.lowercase().startsWith("")) browser.stop() diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 4a12042ba..250b5fbf4 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -5,8 +5,9 @@ detekt = "1.23.8" dokka = "2.2.0" ksp = "2.3.12" maven = "0.37.0" -ktor = "3.4.0" +ktor = "3.4.3" mockk = "1.13.12" +slf4j = "2.0.17" jsoup = "1.16.2" kotlinx-coroutines = "1.10.2" kotlinx-serialization = "1.8.1" @@ -34,6 +35,7 @@ ktor-clientDarwin = { module = "io.ktor:ktor-client-darwin", version.ref = "ktor ktor-clientCurl = { module = "io.ktor:ktor-client-curl", version.ref = "ktor" } ktor-clientWinhttp = { module = "io.ktor:ktor-client-winhttp", version.ref = "ktor" } tests-mockk = { module = "io.mockk:mockk", version.ref = "mockk" } +tests-slf4jSimple = { module = "org.slf4j:slf4j-simple", version.ref = "slf4j" } tests-jsoup = { module = "org.jsoup:jsoup", version.ref = "jsoup" } tests-coroutines = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "kotlinx-coroutines" } kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "kotlinx-coroutines" }