diff --git a/buildSrc/src/main/kotlin/JsConfig.kt b/buildSrc/src/main/kotlin/JsConfig.kt index 161e05c452e..e089d93df10 100644 --- a/buildSrc/src/main/kotlin/JsConfig.kt +++ b/buildSrc/src/main/kotlin/JsConfig.kt @@ -34,7 +34,7 @@ fun Project.configureJs() { internal fun KotlinJsSubTargetDsl.useMochaForTests() { testTask { useMocha { - timeout = "10000" + timeout = "60000" } } } diff --git a/buildSrc/src/main/kotlin/TargetsConfig.kt b/buildSrc/src/main/kotlin/TargetsConfig.kt index d82cb47dfe3..d8f652d5b04 100644 --- a/buildSrc/src/main/kotlin/TargetsConfig.kt +++ b/buildSrc/src/main/kotlin/TargetsConfig.kt @@ -110,16 +110,16 @@ private val hierarchyTemplate = KotlinHierarchyTemplate { group("posix") } - group("jvmAndNix") { - withJvm() - group("nix") - } - group("desktop") { group("linux") group("windows") group("macos") } + + group("nonJvm") { + group("posix") + group("jsAndWasmShared") + } } } diff --git a/buildSrc/src/main/kotlin/test/server/tests/Auth.kt b/buildSrc/src/main/kotlin/test/server/tests/Auth.kt index 9f0f7d22e2c..20aa582e312 100644 --- a/buildSrc/src/main/kotlin/test/server/tests/Auth.kt +++ b/buildSrc/src/main/kotlin/test/server/tests/Auth.kt @@ -129,7 +129,8 @@ internal fun Application.authTestServer() { val token = call.request.headers["Authorization"] if (token.isNullOrEmpty() || token.contains("invalid")) { call.response.header(HttpHeaders.WWWAuthenticate, "Bearer realm=\"TestServer\"") - call.respond(HttpStatusCode.Unauthorized) + val status = call.request.queryParameters["status"]?.toIntOrNull() ?: 401 + call.respond(HttpStatusCode.fromValue(status)) return@get } diff --git a/buildSrc/src/main/kotlin/test/server/tests/MultiPartFormData.kt b/buildSrc/src/main/kotlin/test/server/tests/MultiPartFormData.kt index 9b53033cf8c..8cd297df907 100644 --- a/buildSrc/src/main/kotlin/test/server/tests/MultiPartFormData.kt +++ b/buildSrc/src/main/kotlin/test/server/tests/MultiPartFormData.kt @@ -4,6 +4,7 @@ package test.server.tests +import io.ktor.client.request.forms.* import io.ktor.http.* import io.ktor.http.content.* import io.ktor.server.application.* @@ -34,6 +35,18 @@ internal fun Application.multiPartFormDataTest() { call.receiveMultipart().readPart() call.respond(HttpStatusCode.OK) } + post("receive") { + val multipart = MultiPartFormDataContent( + formData { + append("text", "Hello, World!") + append("file", ByteArray(1024) { it.toByte() }, Headers.build { + append(HttpHeaders.ContentDisposition, """form-data; name="file"; filename="test.bin"""") + append(HttpHeaders.ContentType, ContentType.Application.OctetStream.toString()) + }) + } + ) + call.respond(multipart) + } } } } diff --git a/buildSrc/src/main/kotlin/test/server/tests/ServerSentEvents.kt b/buildSrc/src/main/kotlin/test/server/tests/ServerSentEvents.kt index 33589b9d9e9..002a106bc99 100644 --- a/buildSrc/src/main/kotlin/test/server/tests/ServerSentEvents.kt +++ b/buildSrc/src/main/kotlin/test/server/tests/ServerSentEvents.kt @@ -84,13 +84,41 @@ internal fun Application.serverSentEvents() { emit(SseEvent("Hello")) } ) - } get("/content-type-text-plain") { call.response.header(HttpHeaders.ContentType, ContentType.Text.Plain.toString()) call.respond(HttpStatusCode.OK) } + + get("/person") { + val times = call.parameters["times"]?.toInt() ?: 1 + call.respondSseEvents( + flow { + repeat(times) { + emit(SseEvent(data = "Name $it", event = "event $it", id = "$it")) + } + } + ) + } + + get("/json") { + val customer = """ + { "id": 1, + "firstName": "Jet", + "lastName": "Brains" + }""".trimIndent() + val product = """ + { "name": "Milk", + "price": "100" + }""".trimIndent() + call.respondSseEvents( + flow { + emit(SseEvent(data = customer)) + emit(SseEvent(data = product)) + } + ) + } } } } diff --git a/gradle.properties b/gradle.properties index 147f0e52aea..43452e4199e 100644 --- a/gradle.properties +++ b/gradle.properties @@ -2,11 +2,11 @@ # Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. # -# sytleguide +# styleguide kotlin.code.style=official # config -version=3.0.2-SNAPSHOT +version=3.1.0-SNAPSHOT ## Performance diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index aba5141d30d..a2432396651 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -43,7 +43,7 @@ slf4j = "2.0.16" logback = "1.5.12" dropwizard = "4.2.28" -micrometer = "1.13.6" +micrometer = "1.14.1" jansi = "2.4.1" typesafe = "1.4.3" diff --git a/ktor-client/ktor-client-android/api/ktor-client-android.api b/ktor-client/ktor-client-android/api/ktor-client-android.api index f8152b9a21f..c9626c1ad7c 100644 --- a/ktor-client/ktor-client-android/api/ktor-client-android.api +++ b/ktor-client/ktor-client-android/api/ktor-client-android.api @@ -1,6 +1,9 @@ public final class io/ktor/client/engine/android/Android : io/ktor/client/engine/HttpClientEngineFactory { public static final field INSTANCE Lio/ktor/client/engine/android/Android; public fun create (Lkotlin/jvm/functions/Function1;)Lio/ktor/client/engine/HttpClientEngine; + public fun equals (Ljava/lang/Object;)Z + public fun hashCode ()I + public fun toString ()Ljava/lang/String; } public final class io/ktor/client/engine/android/AndroidClientEngine : io/ktor/client/engine/HttpClientEngineBase { diff --git a/ktor-client/ktor-client-android/jvm/src/io/ktor/client/engine/android/Android.kt b/ktor-client/ktor-client-android/jvm/src/io/ktor/client/engine/android/Android.kt index 8138688db08..5efb76b6651 100644 --- a/ktor-client/ktor-client-android/jvm/src/io/ktor/client/engine/android/Android.kt +++ b/ktor-client/ktor-client-android/jvm/src/io/ktor/client/engine/android/Android.kt @@ -26,7 +26,7 @@ import io.ktor.client.engine.* * * You can learn more about client engines from [Engines](https://ktor.io/docs/http-client-engines.html). */ -public object Android : HttpClientEngineFactory { +public data object Android : HttpClientEngineFactory { override fun create(block: AndroidEngineConfig.() -> Unit): HttpClientEngine = AndroidClientEngine(AndroidEngineConfig().apply(block)) } diff --git a/ktor-client/ktor-client-apache/api/ktor-client-apache.api b/ktor-client/ktor-client-apache/api/ktor-client-apache.api index c9622b69391..7b79b512cd3 100644 --- a/ktor-client/ktor-client-apache/api/ktor-client-apache.api +++ b/ktor-client/ktor-client-apache/api/ktor-client-apache.api @@ -1,6 +1,9 @@ public final class io/ktor/client/engine/apache/Apache : io/ktor/client/engine/HttpClientEngineFactory { public static final field INSTANCE Lio/ktor/client/engine/apache/Apache; public fun create (Lkotlin/jvm/functions/Function1;)Lio/ktor/client/engine/HttpClientEngine; + public fun equals (Ljava/lang/Object;)Z + public fun hashCode ()I + public fun toString ()Ljava/lang/String; } public final class io/ktor/client/engine/apache/ApacheEngineConfig : io/ktor/client/engine/HttpClientEngineConfig { diff --git a/ktor-client/ktor-client-apache/jvm/src/io/ktor/client/engine/apache/Apache.kt b/ktor-client/ktor-client-apache/jvm/src/io/ktor/client/engine/apache/Apache.kt index ee3bd2489fc..2df9167d90d 100644 --- a/ktor-client/ktor-client-apache/jvm/src/io/ktor/client/engine/apache/Apache.kt +++ b/ktor-client/ktor-client-apache/jvm/src/io/ktor/client/engine/apache/Apache.kt @@ -25,7 +25,7 @@ import io.ktor.client.engine.* * * You can learn more about client engines from [Engines](https://ktor.io/docs/http-client-engines.html). */ -public object Apache : HttpClientEngineFactory { +public data object Apache : HttpClientEngineFactory { override fun create(block: ApacheEngineConfig.() -> Unit): HttpClientEngine { val config = ApacheEngineConfig().apply(block) return ApacheEngine(config) diff --git a/ktor-client/ktor-client-apache5/api/ktor-client-apache5.api b/ktor-client/ktor-client-apache5/api/ktor-client-apache5.api index 5f665603e19..9f7dd8a9e97 100644 --- a/ktor-client/ktor-client-apache5/api/ktor-client-apache5.api +++ b/ktor-client/ktor-client-apache5/api/ktor-client-apache5.api @@ -1,6 +1,9 @@ public final class io/ktor/client/engine/apache5/Apache5 : io/ktor/client/engine/HttpClientEngineFactory { public static final field INSTANCE Lio/ktor/client/engine/apache5/Apache5; public fun create (Lkotlin/jvm/functions/Function1;)Lio/ktor/client/engine/HttpClientEngine; + public fun equals (Ljava/lang/Object;)Z + public fun hashCode ()I + public fun toString ()Ljava/lang/String; } public final class io/ktor/client/engine/apache5/Apache5EngineConfig : io/ktor/client/engine/HttpClientEngineConfig { diff --git a/ktor-client/ktor-client-apache5/jvm/src/io/ktor/client/engine/apache5/Apache5.kt b/ktor-client/ktor-client-apache5/jvm/src/io/ktor/client/engine/apache5/Apache5.kt index dff6e8230b5..4d527129470 100644 --- a/ktor-client/ktor-client-apache5/jvm/src/io/ktor/client/engine/apache5/Apache5.kt +++ b/ktor-client/ktor-client-apache5/jvm/src/io/ktor/client/engine/apache5/Apache5.kt @@ -25,7 +25,7 @@ import io.ktor.client.engine.* * * You can learn more about client engines from [Engines](https://ktor.io/docs/http-client-engines.html). */ -public object Apache5 : HttpClientEngineFactory { +public data object Apache5 : HttpClientEngineFactory { override fun create(block: Apache5EngineConfig.() -> Unit): HttpClientEngine { val config = Apache5EngineConfig().apply(block) return Apache5Engine(config) diff --git a/ktor-client/ktor-client-cio/api/ktor-client-cio.klib.api b/ktor-client/ktor-client-cio/api/ktor-client-cio.klib.api index 6204ea570a1..4794aa06ca0 100644 --- a/ktor-client/ktor-client-cio/api/ktor-client-cio.klib.api +++ b/ktor-client/ktor-client-cio/api/ktor-client-cio.klib.api @@ -1,5 +1,5 @@ // Klib ABI Dump -// Targets: [androidNativeArm32, androidNativeArm64, androidNativeX64, androidNativeX86, iosArm64, iosSimulatorArm64, iosX64, linuxArm64, linuxX64, macosArm64, macosX64, mingwX64, tvosArm64, tvosSimulatorArm64, tvosX64, watchosArm32, watchosArm64, watchosDeviceArm64, watchosSimulatorArm64, watchosX64] +// Targets: [androidNativeArm32, androidNativeArm64, androidNativeX64, androidNativeX86, iosArm64, iosSimulatorArm64, iosX64, js, linuxArm64, linuxX64, macosArm64, macosX64, mingwX64, tvosArm64, tvosSimulatorArm64, tvosX64, wasmJs, watchosArm32, watchosArm64, watchosDeviceArm64, watchosSimulatorArm64, watchosX64] // Rendering settings: // - Signature version: 2 // - Show manifest properties: true @@ -62,3 +62,7 @@ final object io.ktor.client.engine.cio/CIO : io.ktor.client.engine/HttpClientEng } final fun (io.ktor.client.engine.cio/CIOEngineConfig).io.ktor.client.engine.cio/endpoint(kotlin/Function1): io.ktor.client.engine.cio/EndpointConfig // io.ktor.client.engine.cio/endpoint|endpoint@io.ktor.client.engine.cio.CIOEngineConfig(kotlin.Function1){}[0] + +// Targets: [js] +final val io.ktor.client.engine.cio/initHook // io.ktor.client.engine.cio/initHook|{}initHook[0] + final fun (): dynamic // io.ktor.client.engine.cio/initHook.|(){}[0] diff --git a/ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/CIOCommon.kt b/ktor-client/ktor-client-cio/common/src/io/ktor/client/engine/cio/CIOCommon.kt similarity index 96% rename from ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/CIOCommon.kt rename to ktor-client/ktor-client-cio/common/src/io/ktor/client/engine/cio/CIOCommon.kt index ee1023e3bd6..28b85a40111 100644 --- a/ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/CIOCommon.kt +++ b/ktor-client/ktor-client-cio/common/src/io/ktor/client/engine/cio/CIOCommon.kt @@ -26,10 +26,6 @@ import io.ktor.client.engine.* * You can learn more about client engines from [Engines](https://ktor.io/docs/http-client-engines.html). */ public data object CIO : HttpClientEngineFactory { - init { - addToLoader() - } - override fun create(block: CIOEngineConfig.() -> Unit): HttpClientEngine = CIOEngine(CIOEngineConfig().apply(block)) } diff --git a/ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/CIOEngine.kt b/ktor-client/ktor-client-cio/common/src/io/ktor/client/engine/cio/CIOEngine.kt similarity index 98% rename from ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/CIOEngine.kt rename to ktor-client/ktor-client-cio/common/src/io/ktor/client/engine/cio/CIOEngine.kt index 59fac79bfd4..8103bf9fb4b 100644 --- a/ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/CIOEngine.kt +++ b/ktor-client/ktor-client-cio/common/src/io/ktor/client/engine/cio/CIOEngine.kt @@ -61,7 +61,6 @@ internal class CIOEngine( val requestJob = requestField[Job]!! val selector = selectorManager - @OptIn(ExperimentalCoroutinesApi::class) GlobalScope.launch(parentContext, start = CoroutineStart.ATOMIC) { try { requestJob.join() diff --git a/ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/CIOEngineConfig.kt b/ktor-client/ktor-client-cio/common/src/io/ktor/client/engine/cio/CIOEngineConfig.kt similarity index 100% rename from ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/CIOEngineConfig.kt rename to ktor-client/ktor-client-cio/common/src/io/ktor/client/engine/cio/CIOEngineConfig.kt diff --git a/ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/ConnectionFactory.kt b/ktor-client/ktor-client-cio/common/src/io/ktor/client/engine/cio/ConnectionFactory.kt similarity index 100% rename from ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/ConnectionFactory.kt rename to ktor-client/ktor-client-cio/common/src/io/ktor/client/engine/cio/ConnectionFactory.kt diff --git a/ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/ConnectionPipelineCommon.kt b/ktor-client/ktor-client-cio/common/src/io/ktor/client/engine/cio/ConnectionPipelineCommon.kt similarity index 100% rename from ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/ConnectionPipelineCommon.kt rename to ktor-client/ktor-client-cio/common/src/io/ktor/client/engine/cio/ConnectionPipelineCommon.kt diff --git a/ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/Endpoint.kt b/ktor-client/ktor-client-cio/common/src/io/ktor/client/engine/cio/Endpoint.kt similarity index 100% rename from ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/Endpoint.kt rename to ktor-client/ktor-client-cio/common/src/io/ktor/client/engine/cio/Endpoint.kt diff --git a/ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/EngineTasks.kt b/ktor-client/ktor-client-cio/common/src/io/ktor/client/engine/cio/EngineTasks.kt similarity index 100% rename from ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/EngineTasks.kt rename to ktor-client/ktor-client-cio/common/src/io/ktor/client/engine/cio/EngineTasks.kt diff --git a/ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/utils.kt b/ktor-client/ktor-client-cio/common/src/io/ktor/client/engine/cio/utils.kt similarity index 98% rename from ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/utils.kt rename to ktor-client/ktor-client-cio/common/src/io/ktor/client/engine/cio/utils.kt index 8ec2b097ed1..72a12c9bfea 100644 --- a/ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/utils.kt +++ b/ktor-client/ktor-client-cio/common/src/io/ktor/client/engine/cio/utils.kt @@ -1,6 +1,6 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.client.engine.cio @@ -14,8 +14,6 @@ import io.ktor.http.content.* import io.ktor.util.date.* import io.ktor.utils.io.* import io.ktor.utils.io.CancellationException -import io.ktor.utils.io.core.* -import io.ktor.utils.io.errors.* import io.ktor.websocket.* import kotlinx.coroutines.* import kotlinx.io.IOException diff --git a/ktor-client/ktor-client-cio/jvmAndPosix/test/CIOEngineTest.kt b/ktor-client/ktor-client-cio/common/test/CIOEngineTest.kt similarity index 93% rename from ktor-client/ktor-client-cio/jvmAndPosix/test/CIOEngineTest.kt rename to ktor-client/ktor-client-cio/common/test/CIOEngineTest.kt index f442d2f88df..ccd0fd877eb 100644 --- a/ktor-client/ktor-client-cio/jvmAndPosix/test/CIOEngineTest.kt +++ b/ktor-client/ktor-client-cio/common/test/CIOEngineTest.kt @@ -1,8 +1,10 @@ /* - * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ + +package io.ktor.client.engine.cio + import io.ktor.client.* -import io.ktor.client.engine.cio.* import io.ktor.client.plugins.sse.* import io.ktor.client.plugins.websocket.* import io.ktor.client.request.* @@ -10,8 +12,8 @@ import io.ktor.client.tests.utils.* import io.ktor.http.* import io.ktor.network.selector.* import io.ktor.network.sockets.* +import io.ktor.test.dispatcher.* import io.ktor.utils.io.* -import io.ktor.utils.io.core.* import io.ktor.websocket.* import kotlinx.coroutines.* import kotlinx.coroutines.flow.* @@ -23,7 +25,7 @@ class CIOEngineTest { private val selectorManager = SelectorManager() @Test - fun testRequestTimeoutIgnoredWithWebSocket(): Unit = runBlocking { + fun testRequestTimeoutIgnoredWithWebSocket() = runTestWithRealTime { val client = HttpClient(CIO) { engine { requestTimeout = 10 @@ -47,7 +49,7 @@ class CIOEngineTest { } @Test - fun testRequestTimeoutIgnoredWithSSE(): Unit = runBlocking { + fun testRequestTimeoutIgnoredWithSSE() = runTestWithRealTime { val client = HttpClient(CIO) { engine { requestTimeout = 10 @@ -66,7 +68,7 @@ class CIOEngineTest { } @Test - fun testExpectHeader(): Unit = runBlocking { + fun testExpectHeader() = runTestWithRealTime { val body = "Hello World" withServerSocket { socket -> @@ -94,7 +96,7 @@ class CIOEngineTest { } @Test - fun testNoExpectHeaderIfNoBody(): Unit = runBlocking { + fun testNoExpectHeaderIfNoBody() = runTestWithRealTime { withServerSocket { socket -> val client = HttpClient(CIO) launch { @@ -115,7 +117,7 @@ class CIOEngineTest { } @Test - fun testDontWaitForContinueResponse(): Unit = runBlocking { + fun testDontWaitForContinueResponse() = runTestWithRealTime { withTimeout(30.seconds) { val body = "Hello World\n" @@ -147,7 +149,7 @@ class CIOEngineTest { } @Test - fun testRepeatRequestAfterExpectationFailed(): Unit = runBlocking { + fun testRepeatRequestAfterExpectationFailed() = runTestWithRealTime { val body = "Hello World" withServerSocket { socket -> diff --git a/ktor-client/ktor-client-cio/jvmAndPosix/test/ConnectionFactoryTest.kt b/ktor-client/ktor-client-cio/common/test/ConnectionFactoryTest.kt similarity index 90% rename from ktor-client/ktor-client-cio/jvmAndPosix/test/ConnectionFactoryTest.kt rename to ktor-client/ktor-client-cio/common/test/ConnectionFactoryTest.kt index a4354f66eda..cc77fc7fe4e 100644 --- a/ktor-client/ktor-client-cio/jvmAndPosix/test/ConnectionFactoryTest.kt +++ b/ktor-client/ktor-client-cio/common/test/ConnectionFactoryTest.kt @@ -1,9 +1,12 @@ /* - * Copyright 2014-2023 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ -import io.ktor.client.engine.cio.* + +package io.ktor.client.engine.cio + import io.ktor.network.selector.* import io.ktor.network.sockets.* +import io.ktor.test.dispatcher.* import io.ktor.utils.io.core.* import kotlinx.coroutines.* import kotlin.test.* @@ -23,7 +26,7 @@ class ConnectionFactoryTest { } @Test - fun testLimitSemaphore() = runBlocking { + fun testLimitSemaphore() = runTestWithRealTime { val connectionFactory = ConnectionFactory( selectorManager, connectionsLimit = 2, @@ -44,7 +47,7 @@ class ConnectionFactoryTest { } @Test - fun testAddressSemaphore() = runBlocking { + fun testAddressSemaphore() = runTestWithRealTime { val connectionFactory = ConnectionFactory( selectorManager, connectionsLimit = 2, @@ -67,7 +70,7 @@ class ConnectionFactoryTest { } @Test - fun testReleaseLimitSemaphoreWhenFailed() = runBlocking { + fun testReleaseLimitSemaphoreWhenFailed() = runTestWithRealTime { val connectionFactory = ConnectionFactory( selectorManager, connectionsLimit = 2, diff --git a/ktor-client/ktor-client-cio/gradle.properties b/ktor-client/ktor-client-cio/gradle.properties new file mode 100644 index 00000000000..d12c10bfad8 --- /dev/null +++ b/ktor-client/ktor-client-cio/gradle.properties @@ -0,0 +1,5 @@ +# +# Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. +# +target.js.browser=false +target.wasmJs.browser=false diff --git a/ktor-client/ktor-client-cio/js/src/io/ktor/client/engine/cio/Loader.js.kt b/ktor-client/ktor-client-cio/js/src/io/ktor/client/engine/cio/Loader.js.kt new file mode 100644 index 00000000000..95af101c028 --- /dev/null +++ b/ktor-client/ktor-client-cio/js/src/io/ktor/client/engine/cio/Loader.js.kt @@ -0,0 +1,18 @@ +/* + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + +package io.ktor.client.engine.cio + +import io.ktor.client.engine.* +import io.ktor.util.* +import io.ktor.utils.io.* + +@Suppress("DEPRECATION") +@OptIn(ExperimentalStdlibApi::class, ExperimentalJsExport::class, InternalAPI::class) +@Deprecated("", level = DeprecationLevel.HIDDEN) +@JsExport +@EagerInitialization +public val initHook: dynamic = run { + if (PlatformUtils.IS_NODE) engines.append(CIO) +} diff --git a/ktor-client/ktor-client-cio/jvm/src/io/ktor/client/engine/cio/LoaderJvm.kt b/ktor-client/ktor-client-cio/jvm/src/io/ktor/client/engine/cio/LoaderJvm.kt deleted file mode 100644 index 2f48c8228ca..00000000000 --- a/ktor-client/ktor-client-cio/jvm/src/io/ktor/client/engine/cio/LoaderJvm.kt +++ /dev/null @@ -1,8 +0,0 @@ -/* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ - -package io.ktor.client.engine.cio - -internal actual fun addToLoader() { -} diff --git a/ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/Loader.kt b/ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/Loader.kt deleted file mode 100644 index 727472064ec..00000000000 --- a/ktor-client/ktor-client-cio/jvmAndPosix/src/io/ktor/client/engine/cio/Loader.kt +++ /dev/null @@ -1,7 +0,0 @@ -/* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ - -package io.ktor.client.engine.cio - -internal expect fun addToLoader() diff --git a/ktor-client/ktor-client-cio/posix/src/io/ktor/client/engine/cio/ConnectionPipelineNative.kt b/ktor-client/ktor-client-cio/nonJvm/src/io/ktor/client/engine/cio/ConnectionPipeline.nonJvm.kt similarity index 83% rename from ktor-client/ktor-client-cio/posix/src/io/ktor/client/engine/cio/ConnectionPipelineNative.kt rename to ktor-client/ktor-client-cio/nonJvm/src/io/ktor/client/engine/cio/ConnectionPipeline.nonJvm.kt index 1c9c9baf521..a2c8a5d4381 100644 --- a/ktor-client/ktor-client-cio/posix/src/io/ktor/client/engine/cio/ConnectionPipelineNative.kt +++ b/ktor-client/ktor-client-cio/nonJvm/src/io/ktor/client/engine/cio/ConnectionPipeline.nonJvm.kt @@ -21,9 +21,9 @@ internal actual class ConnectionPipeline actual constructor( actual override val coroutineContext: CoroutineContext = parentContext init { - error("Pipelining is not supported in native CIO") + error("Pipelining is not supported in native/js/wasm CIO") } actual val pipelineContext: Job - get() = error("Pipelining is not supported in native CIO") + get() = error("Pipelining is not supported in native/js/wasm CIO") } diff --git a/ktor-client/ktor-client-cio/posix/src/io/ktor/client/engine/cio/ExceptionUtilsNative.kt b/ktor-client/ktor-client-cio/nonJvm/src/io/ktor/client/engine/cio/ExceptionUtils.nonJvm.kt similarity index 100% rename from ktor-client/ktor-client-cio/posix/src/io/ktor/client/engine/cio/ExceptionUtilsNative.kt rename to ktor-client/ktor-client-cio/nonJvm/src/io/ktor/client/engine/cio/ExceptionUtils.nonJvm.kt diff --git a/ktor-client/ktor-client-cio/posix/src/io/ktor/client/engine/cio/LoaderNative.kt b/ktor-client/ktor-client-cio/posix/src/io/ktor/client/engine/cio/Loader.posix.kt similarity index 60% rename from ktor-client/ktor-client-cio/posix/src/io/ktor/client/engine/cio/LoaderNative.kt rename to ktor-client/ktor-client-cio/posix/src/io/ktor/client/engine/cio/Loader.posix.kt index 48523ab257f..693972ec912 100644 --- a/ktor-client/ktor-client-cio/posix/src/io/ktor/client/engine/cio/LoaderNative.kt +++ b/ktor-client/ktor-client-cio/posix/src/io/ktor/client/engine/cio/Loader.posix.kt @@ -7,11 +7,7 @@ package io.ktor.client.engine.cio import io.ktor.client.engine.* import io.ktor.utils.io.* -@OptIn(ExperimentalStdlibApi::class) +@Suppress("DEPRECATION") +@OptIn(ExperimentalStdlibApi::class, InternalAPI::class) @EagerInitialization -private val initHook = CIO - -@OptIn(InternalAPI::class) -internal actual fun addToLoader() { - engines.append(CIO) -} +private val initHook = engines.append(CIO) diff --git a/ktor-client/ktor-client-cio/wasmJs/src/io/ktor/client/engine/cio/Loader.wasmJs.kt b/ktor-client/ktor-client-cio/wasmJs/src/io/ktor/client/engine/cio/Loader.wasmJs.kt new file mode 100644 index 00000000000..e4aae973489 --- /dev/null +++ b/ktor-client/ktor-client-cio/wasmJs/src/io/ktor/client/engine/cio/Loader.wasmJs.kt @@ -0,0 +1,16 @@ +/* + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + +package io.ktor.client.engine.cio + +import io.ktor.client.engine.* +import io.ktor.util.* +import io.ktor.utils.io.* + +@Suppress("DEPRECATION") +@OptIn(InternalAPI::class, ExperimentalStdlibApi::class) +@EagerInitialization +private val initHook: Unit = run { + if (PlatformUtils.IS_NODE) engines.append(CIO) +} diff --git a/ktor-client/ktor-client-core/api/ktor-client-core.api b/ktor-client/ktor-client-core/api/ktor-client-core.api index 99aafdb303f..c5f07b8bf65 100644 --- a/ktor-client/ktor-client-core/api/ktor-client-core.api +++ b/ktor-client/ktor-client-core/api/ktor-client-core.api @@ -767,24 +767,48 @@ public final class io/ktor/client/plugins/sse/BuildersKt { public static synthetic fun serverSentEvents-1wIb-0I$default (Lio/ktor/client/HttpClient;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/String;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function1;Lkotlin/jvm/functions/Function2;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; public static final fun serverSentEvents-3bFjkrY (Lio/ktor/client/HttpClient;Ljava/lang/String;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function1;Lkotlin/jvm/functions/Function2;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public static synthetic fun serverSentEvents-3bFjkrY$default (Lio/ktor/client/HttpClient;Ljava/lang/String;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function1;Lkotlin/jvm/functions/Function2;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; + public static final fun serverSentEvents-BqdlHlk (Lio/ktor/client/HttpClient;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/String;Lkotlin/jvm/functions/Function2;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function1;Lkotlin/jvm/functions/Function2;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; + public static synthetic fun serverSentEvents-BqdlHlk$default (Lio/ktor/client/HttpClient;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/String;Lkotlin/jvm/functions/Function2;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function1;Lkotlin/jvm/functions/Function2;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; + public static final fun serverSentEvents-Mswn-_c (Lio/ktor/client/HttpClient;Lkotlin/jvm/functions/Function1;Lkotlin/jvm/functions/Function2;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function2;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; + public static synthetic fun serverSentEvents-Mswn-_c$default (Lio/ktor/client/HttpClient;Lkotlin/jvm/functions/Function1;Lkotlin/jvm/functions/Function2;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function2;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; public static final fun serverSentEvents-mY9Nd3A (Lio/ktor/client/HttpClient;Lkotlin/jvm/functions/Function1;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function2;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public static synthetic fun serverSentEvents-mY9Nd3A$default (Lio/ktor/client/HttpClient;Lkotlin/jvm/functions/Function1;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function2;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; + public static final fun serverSentEvents-pTj2aPc (Lio/ktor/client/HttpClient;Ljava/lang/String;Lkotlin/jvm/functions/Function2;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function1;Lkotlin/jvm/functions/Function2;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; + public static synthetic fun serverSentEvents-pTj2aPc$default (Lio/ktor/client/HttpClient;Ljava/lang/String;Lkotlin/jvm/functions/Function2;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function1;Lkotlin/jvm/functions/Function2;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; + public static final fun serverSentEventsSession-Mswn-_c (Lio/ktor/client/HttpClient;Ljava/lang/String;Lkotlin/jvm/functions/Function2;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function1;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; + public static synthetic fun serverSentEventsSession-Mswn-_c$default (Lio/ktor/client/HttpClient;Ljava/lang/String;Lkotlin/jvm/functions/Function2;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function1;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; public static final fun serverSentEventsSession-i8z2VEo (Lio/ktor/client/HttpClient;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function1;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public static synthetic fun serverSentEventsSession-i8z2VEo$default (Lio/ktor/client/HttpClient;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function1;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; public static final fun serverSentEventsSession-mY9Nd3A (Lio/ktor/client/HttpClient;Ljava/lang/String;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function1;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; + public static final fun serverSentEventsSession-mY9Nd3A (Lio/ktor/client/HttpClient;Lkotlin/jvm/functions/Function2;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function1;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public static synthetic fun serverSentEventsSession-mY9Nd3A$default (Lio/ktor/client/HttpClient;Ljava/lang/String;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function1;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; + public static synthetic fun serverSentEventsSession-mY9Nd3A$default (Lio/ktor/client/HttpClient;Lkotlin/jvm/functions/Function2;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function1;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; + public static final fun serverSentEventsSession-tL6_L-A (Lio/ktor/client/HttpClient;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/String;Lkotlin/jvm/functions/Function2;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function1;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; + public static synthetic fun serverSentEventsSession-tL6_L-A$default (Lio/ktor/client/HttpClient;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/String;Lkotlin/jvm/functions/Function2;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function1;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; public static final fun serverSentEventsSession-xEWcMm4 (Lio/ktor/client/HttpClient;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/String;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function1;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public static synthetic fun serverSentEventsSession-xEWcMm4$default (Lio/ktor/client/HttpClient;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/String;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function1;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; + public static final fun sse-BAHpl2s (Lio/ktor/client/HttpClient;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/String;Lkotlin/jvm/functions/Function1;Lkotlin/jvm/functions/Function2;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function2;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; + public static synthetic fun sse-BAHpl2s$default (Lio/ktor/client/HttpClient;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/String;Lkotlin/jvm/functions/Function1;Lkotlin/jvm/functions/Function2;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function2;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; public static final fun sse-Mswn-_c (Lio/ktor/client/HttpClient;Ljava/lang/String;Lkotlin/jvm/functions/Function1;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function2;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; + public static final fun sse-Mswn-_c (Lio/ktor/client/HttpClient;Lkotlin/jvm/functions/Function1;Lkotlin/jvm/functions/Function2;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function2;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public static synthetic fun sse-Mswn-_c$default (Lio/ktor/client/HttpClient;Ljava/lang/String;Lkotlin/jvm/functions/Function1;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function2;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; + public static synthetic fun sse-Mswn-_c$default (Lio/ktor/client/HttpClient;Lkotlin/jvm/functions/Function1;Lkotlin/jvm/functions/Function2;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function2;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; + public static final fun sse-Q9yt8Vw (Lio/ktor/client/HttpClient;Ljava/lang/String;Lkotlin/jvm/functions/Function1;Lkotlin/jvm/functions/Function2;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function2;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; + public static synthetic fun sse-Q9yt8Vw$default (Lio/ktor/client/HttpClient;Ljava/lang/String;Lkotlin/jvm/functions/Function1;Lkotlin/jvm/functions/Function2;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function2;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; public static final fun sse-mY9Nd3A (Lio/ktor/client/HttpClient;Lkotlin/jvm/functions/Function1;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function2;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public static synthetic fun sse-mY9Nd3A$default (Lio/ktor/client/HttpClient;Lkotlin/jvm/functions/Function1;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function2;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; public static final fun sse-tL6_L-A (Lio/ktor/client/HttpClient;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/String;Lkotlin/jvm/functions/Function1;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function2;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public static synthetic fun sse-tL6_L-A$default (Lio/ktor/client/HttpClient;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/String;Lkotlin/jvm/functions/Function1;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function2;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; + public static final fun sseSession-Mswn-_c (Lio/ktor/client/HttpClient;Ljava/lang/String;Lkotlin/jvm/functions/Function2;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function1;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; + public static synthetic fun sseSession-Mswn-_c$default (Lio/ktor/client/HttpClient;Ljava/lang/String;Lkotlin/jvm/functions/Function2;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function1;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; public static final fun sseSession-i8z2VEo (Lio/ktor/client/HttpClient;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function1;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public static synthetic fun sseSession-i8z2VEo$default (Lio/ktor/client/HttpClient;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function1;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; public static final fun sseSession-mY9Nd3A (Lio/ktor/client/HttpClient;Ljava/lang/String;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function1;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; + public static final fun sseSession-mY9Nd3A (Lio/ktor/client/HttpClient;Lkotlin/jvm/functions/Function2;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function1;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public static synthetic fun sseSession-mY9Nd3A$default (Lio/ktor/client/HttpClient;Ljava/lang/String;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function1;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; + public static synthetic fun sseSession-mY9Nd3A$default (Lio/ktor/client/HttpClient;Lkotlin/jvm/functions/Function2;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function1;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; + public static final fun sseSession-tL6_L-A (Lio/ktor/client/HttpClient;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/String;Lkotlin/jvm/functions/Function2;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function1;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; + public static synthetic fun sseSession-tL6_L-A$default (Lio/ktor/client/HttpClient;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/String;Lkotlin/jvm/functions/Function2;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function1;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; public static final fun sseSession-xEWcMm4 (Lio/ktor/client/HttpClient;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/String;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function1;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public static synthetic fun sseSession-xEWcMm4$default (Lio/ktor/client/HttpClient;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/String;Lkotlin/time/Duration;Ljava/lang/Boolean;Ljava/lang/Boolean;Lkotlin/jvm/functions/Function1;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; } @@ -796,6 +820,14 @@ public final class io/ktor/client/plugins/sse/ClientSSESession : io/ktor/client/ public fun getIncoming ()Lkotlinx/coroutines/flow/Flow; } +public final class io/ktor/client/plugins/sse/ClientSSESessionWithDeserialization : io/ktor/client/plugins/sse/SSESessionWithDeserialization { + public fun (Lio/ktor/client/call/HttpClientCall;Lio/ktor/client/plugins/sse/SSESessionWithDeserialization;)V + public final fun getCall ()Lio/ktor/client/call/HttpClientCall; + public fun getCoroutineContext ()Lkotlin/coroutines/CoroutineContext; + public fun getDeserializer ()Lkotlin/jvm/functions/Function2; + public fun getIncoming ()Lkotlinx/coroutines/flow/Flow; +} + public final class io/ktor/client/plugins/sse/DefaultClientSSESession : io/ktor/client/plugins/sse/SSESession { public fun (Lio/ktor/client/plugins/sse/SSEClientContent;Lio/ktor/utils/io/ByteReadChannel;Lkotlin/coroutines/CoroutineContext;)V public fun getCoroutineContext ()Lkotlin/coroutines/CoroutineContext; @@ -845,6 +877,11 @@ public abstract interface class io/ktor/client/plugins/sse/SSESession : kotlinx/ public abstract fun getIncoming ()Lkotlinx/coroutines/flow/Flow; } +public abstract interface class io/ktor/client/plugins/sse/SSESessionWithDeserialization : kotlinx/coroutines/CoroutineScope { + public abstract fun getDeserializer ()Lkotlin/jvm/functions/Function2; + public abstract fun getIncoming ()Lkotlinx/coroutines/flow/Flow; +} + public final class io/ktor/client/plugins/websocket/BuildersKt { public static final fun WebSockets (Lio/ktor/client/HttpClientConfig;Lkotlin/jvm/functions/Function1;)V public static final fun webSocket (Lio/ktor/client/HttpClient;Lio/ktor/http/HttpMethod;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/String;Lkotlin/jvm/functions/Function1;Lkotlin/jvm/functions/Function2;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; diff --git a/ktor-client/ktor-client-core/api/ktor-client-core.klib.api b/ktor-client/ktor-client-core/api/ktor-client-core.klib.api index 854e339bc84..01db08dcc68 100644 --- a/ktor-client/ktor-client-core/api/ktor-client-core.klib.api +++ b/ktor-client/ktor-client-core/api/ktor-client-core.klib.api @@ -82,6 +82,13 @@ abstract interface io.ktor.client.plugins.sse/SSESession : kotlinx.coroutines/Co abstract fun (): kotlinx.coroutines.flow/Flow // io.ktor.client.plugins.sse/SSESession.incoming.|(){}[0] } +abstract interface io.ktor.client.plugins.sse/SSESessionWithDeserialization : kotlinx.coroutines/CoroutineScope { // io.ktor.client.plugins.sse/SSESessionWithDeserialization|null[0] + abstract val deserializer // io.ktor.client.plugins.sse/SSESessionWithDeserialization.deserializer|{}deserializer[0] + abstract fun (): kotlin/Function2 // io.ktor.client.plugins.sse/SSESessionWithDeserialization.deserializer.|(){}[0] + abstract val incoming // io.ktor.client.plugins.sse/SSESessionWithDeserialization.incoming|{}incoming[0] + abstract fun (): kotlinx.coroutines.flow/Flow> // io.ktor.client.plugins.sse/SSESessionWithDeserialization.incoming.|(){}[0] +} + abstract interface io.ktor.client.plugins.websocket/ClientWebSocketSession : io.ktor.websocket/WebSocketSession { // io.ktor.client.plugins.websocket/ClientWebSocketSession|null[0] abstract val call // io.ktor.client.plugins.websocket/ClientWebSocketSession.call|{}call[0] abstract fun (): io.ktor.client.call/HttpClientCall // io.ktor.client.plugins.websocket/ClientWebSocketSession.call.|(){}[0] @@ -437,6 +444,19 @@ final class io.ktor.client.plugins.sse/ClientSSESession : io.ktor.client.plugins final fun (): kotlinx.coroutines.flow/Flow // io.ktor.client.plugins.sse/ClientSSESession.incoming.|(){}[0] } +final class io.ktor.client.plugins.sse/ClientSSESessionWithDeserialization : io.ktor.client.plugins.sse/SSESessionWithDeserialization { // io.ktor.client.plugins.sse/ClientSSESessionWithDeserialization|null[0] + constructor (io.ktor.client.call/HttpClientCall, io.ktor.client.plugins.sse/SSESessionWithDeserialization) // io.ktor.client.plugins.sse/ClientSSESessionWithDeserialization.|(io.ktor.client.call.HttpClientCall;io.ktor.client.plugins.sse.SSESessionWithDeserialization){}[0] + + final val call // io.ktor.client.plugins.sse/ClientSSESessionWithDeserialization.call|{}call[0] + final fun (): io.ktor.client.call/HttpClientCall // io.ktor.client.plugins.sse/ClientSSESessionWithDeserialization.call.|(){}[0] + final val coroutineContext // io.ktor.client.plugins.sse/ClientSSESessionWithDeserialization.coroutineContext|{}coroutineContext[0] + final fun (): kotlin.coroutines/CoroutineContext // io.ktor.client.plugins.sse/ClientSSESessionWithDeserialization.coroutineContext.|(){}[0] + final val deserializer // io.ktor.client.plugins.sse/ClientSSESessionWithDeserialization.deserializer|{}deserializer[0] + final fun (): kotlin/Function2 // io.ktor.client.plugins.sse/ClientSSESessionWithDeserialization.deserializer.|(){}[0] + final val incoming // io.ktor.client.plugins.sse/ClientSSESessionWithDeserialization.incoming|{}incoming[0] + final fun (): kotlinx.coroutines.flow/Flow> // io.ktor.client.plugins.sse/ClientSSESessionWithDeserialization.incoming.|(){}[0] +} + final class io.ktor.client.plugins.sse/DefaultClientSSESession : io.ktor.client.plugins.sse/SSESession { // io.ktor.client.plugins.sse/DefaultClientSSESession|null[0] constructor (io.ktor.client.plugins.sse/SSEClientContent, io.ktor.utils.io/ByteReadChannel, kotlin.coroutines/CoroutineContext) // io.ktor.client.plugins.sse/DefaultClientSSESession.|(io.ktor.client.plugins.sse.SSEClientContent;io.ktor.utils.io.ByteReadChannel;kotlin.coroutines.CoroutineContext){}[0] @@ -1161,6 +1181,11 @@ final object io.ktor.client.engine/ProxyBuilder { // io.ktor.client.engine/Proxy final fun socks(kotlin/String, kotlin/Int): io.ktor.client.engine/ProxyConfig // io.ktor.client.engine/ProxyBuilder.socks|socks(kotlin.String;kotlin.Int){}[0] } +final object io.ktor.client.engine/engines : kotlin.collections/Iterable> { // io.ktor.client.engine/engines|null[0] + final fun append(io.ktor.client.engine/HttpClientEngineFactory) // io.ktor.client.engine/engines.append|append(io.ktor.client.engine.HttpClientEngineFactory){}[0] + final fun iterator(): kotlin.collections/Iterator> // io.ktor.client.engine/engines.iterator|iterator(){}[0] +} + final object io.ktor.client.plugins.api/Send : io.ktor.client.plugins.api/ClientHook> { // io.ktor.client.plugins.api/Send|null[0] final fun install(io.ktor.client/HttpClient, kotlin.coroutines/SuspendFunction2) // io.ktor.client.plugins.api/Send.install|install(io.ktor.client.HttpClient;kotlin.coroutines.SuspendFunction2){}[0] @@ -1393,6 +1418,8 @@ final fun io.ktor.client/HttpClient(io.ktor.client.engine/HttpClientEngine, kotl final fun io.ktor.client/HttpClient(kotlin/Function1, kotlin/Unit> = ...): io.ktor.client/HttpClient // io.ktor.client/HttpClient|HttpClient(kotlin.Function1,kotlin.Unit>){}[0] final inline fun (io.ktor.client.request.forms/FormBuilder).io.ktor.client.request.forms/append(kotlin/String, io.ktor.http/Headers = ..., kotlin/Long? = ..., crossinline kotlin/Function1) // io.ktor.client.request.forms/append|append@io.ktor.client.request.forms.FormBuilder(kotlin.String;io.ktor.http.Headers;kotlin.Long?;kotlin.Function1){}[0] final inline fun <#A: kotlin/Any?> io.ktor.client.plugins/unwrapRequestTimeoutException(kotlin/Function0<#A>): #A // io.ktor.client.plugins/unwrapRequestTimeoutException|unwrapRequestTimeoutException(kotlin.Function0<0:0>){0§}[0] +final inline fun <#A: reified kotlin/Any?> (io.ktor.client.plugins.sse/SSESessionWithDeserialization).io.ktor.client.plugins.sse/deserialize(io.ktor.sse/TypedServerSentEvent): #A? // io.ktor.client.plugins.sse/deserialize|deserialize@io.ktor.client.plugins.sse.SSESessionWithDeserialization(io.ktor.sse.TypedServerSentEvent){0§}[0] +final inline fun <#A: reified kotlin/Any?> (io.ktor.client.plugins.sse/SSESessionWithDeserialization).io.ktor.client.plugins.sse/deserialize(kotlin/String?): #A? // io.ktor.client.plugins.sse/deserialize|deserialize@io.ktor.client.plugins.sse.SSESessionWithDeserialization(kotlin.String?){0§}[0] final inline fun <#A: reified kotlin/Any?> (io.ktor.client.request/HttpRequestBuilder).io.ktor.client.request/setBody(#A) // io.ktor.client.request/setBody|setBody@io.ktor.client.request.HttpRequestBuilder(0:0){0§}[0] final suspend fun (io.ktor.client.call/HttpClientCall).io.ktor.client.call/save(): io.ktor.client.call/HttpClientCall // io.ktor.client.call/save|save@io.ktor.client.call.HttpClientCall(){}[0] final suspend fun (io.ktor.client.plugins.cache.storage/CacheStorage).io.ktor.client.plugins.cache.storage/store(io.ktor.client.statement/HttpResponse): io.ktor.client.plugins.cache.storage/CachedResponseData // io.ktor.client.plugins.cache.storage/store|store@io.ktor.client.plugins.cache.storage.CacheStorage(io.ktor.client.statement.HttpResponse){}[0] @@ -1409,17 +1436,29 @@ final suspend fun (io.ktor.client.statement/HttpResponse).io.ktor.client.stateme final suspend fun (io.ktor.client/HttpClient).io.ktor.client.plugins.cookies/cookies(io.ktor.http/Url): kotlin.collections/List // io.ktor.client.plugins.cookies/cookies|cookies@io.ktor.client.HttpClient(io.ktor.http.Url){}[0] final suspend fun (io.ktor.client/HttpClient).io.ktor.client.plugins.cookies/cookies(kotlin/String): kotlin.collections/List // io.ktor.client.plugins.cookies/cookies|cookies@io.ktor.client.HttpClient(kotlin.String){}[0] final suspend fun (io.ktor.client/HttpClient).io.ktor.client.plugins.sse/serverSentEvents(kotlin/Function1, kotlin.time/Duration? = ..., kotlin/Boolean? = ..., kotlin/Boolean? = ..., kotlin.coroutines/SuspendFunction1) // io.ktor.client.plugins.sse/serverSentEvents|serverSentEvents@io.ktor.client.HttpClient(kotlin.Function1;kotlin.time.Duration?;kotlin.Boolean?;kotlin.Boolean?;kotlin.coroutines.SuspendFunction1){}[0] +final suspend fun (io.ktor.client/HttpClient).io.ktor.client.plugins.sse/serverSentEvents(kotlin/Function1, kotlin/Function2, kotlin.time/Duration? = ..., kotlin/Boolean? = ..., kotlin/Boolean? = ..., kotlin.coroutines/SuspendFunction1) // io.ktor.client.plugins.sse/serverSentEvents|serverSentEvents@io.ktor.client.HttpClient(kotlin.Function1;kotlin.Function2;kotlin.time.Duration?;kotlin.Boolean?;kotlin.Boolean?;kotlin.coroutines.SuspendFunction1){}[0] final suspend fun (io.ktor.client/HttpClient).io.ktor.client.plugins.sse/serverSentEvents(kotlin/String, kotlin.time/Duration? = ..., kotlin/Boolean? = ..., kotlin/Boolean? = ..., kotlin/Function1 = ..., kotlin.coroutines/SuspendFunction1) // io.ktor.client.plugins.sse/serverSentEvents|serverSentEvents@io.ktor.client.HttpClient(kotlin.String;kotlin.time.Duration?;kotlin.Boolean?;kotlin.Boolean?;kotlin.Function1;kotlin.coroutines.SuspendFunction1){}[0] +final suspend fun (io.ktor.client/HttpClient).io.ktor.client.plugins.sse/serverSentEvents(kotlin/String, kotlin/Function2, kotlin.time/Duration? = ..., kotlin/Boolean? = ..., kotlin/Boolean? = ..., kotlin/Function1 = ..., kotlin.coroutines/SuspendFunction1) // io.ktor.client.plugins.sse/serverSentEvents|serverSentEvents@io.ktor.client.HttpClient(kotlin.String;kotlin.Function2;kotlin.time.Duration?;kotlin.Boolean?;kotlin.Boolean?;kotlin.Function1;kotlin.coroutines.SuspendFunction1){}[0] final suspend fun (io.ktor.client/HttpClient).io.ktor.client.plugins.sse/serverSentEvents(kotlin/String? = ..., kotlin/String? = ..., kotlin/Int? = ..., kotlin/String? = ..., kotlin.time/Duration? = ..., kotlin/Boolean? = ..., kotlin/Boolean? = ..., kotlin/Function1 = ..., kotlin.coroutines/SuspendFunction1) // io.ktor.client.plugins.sse/serverSentEvents|serverSentEvents@io.ktor.client.HttpClient(kotlin.String?;kotlin.String?;kotlin.Int?;kotlin.String?;kotlin.time.Duration?;kotlin.Boolean?;kotlin.Boolean?;kotlin.Function1;kotlin.coroutines.SuspendFunction1){}[0] +final suspend fun (io.ktor.client/HttpClient).io.ktor.client.plugins.sse/serverSentEvents(kotlin/String? = ..., kotlin/String? = ..., kotlin/Int? = ..., kotlin/String? = ..., kotlin/Function2, kotlin.time/Duration? = ..., kotlin/Boolean? = ..., kotlin/Boolean? = ..., kotlin/Function1 = ..., kotlin.coroutines/SuspendFunction1) // io.ktor.client.plugins.sse/serverSentEvents|serverSentEvents@io.ktor.client.HttpClient(kotlin.String?;kotlin.String?;kotlin.Int?;kotlin.String?;kotlin.Function2;kotlin.time.Duration?;kotlin.Boolean?;kotlin.Boolean?;kotlin.Function1;kotlin.coroutines.SuspendFunction1){}[0] final suspend fun (io.ktor.client/HttpClient).io.ktor.client.plugins.sse/serverSentEventsSession(kotlin.time/Duration? = ..., kotlin/Boolean? = ..., kotlin/Boolean? = ..., kotlin/Function1): io.ktor.client.plugins.sse/ClientSSESession // io.ktor.client.plugins.sse/serverSentEventsSession|serverSentEventsSession@io.ktor.client.HttpClient(kotlin.time.Duration?;kotlin.Boolean?;kotlin.Boolean?;kotlin.Function1){}[0] +final suspend fun (io.ktor.client/HttpClient).io.ktor.client.plugins.sse/serverSentEventsSession(kotlin/Function2, kotlin.time/Duration? = ..., kotlin/Boolean? = ..., kotlin/Boolean? = ..., kotlin/Function1): io.ktor.client.plugins.sse/ClientSSESessionWithDeserialization // io.ktor.client.plugins.sse/serverSentEventsSession|serverSentEventsSession@io.ktor.client.HttpClient(kotlin.Function2;kotlin.time.Duration?;kotlin.Boolean?;kotlin.Boolean?;kotlin.Function1){}[0] final suspend fun (io.ktor.client/HttpClient).io.ktor.client.plugins.sse/serverSentEventsSession(kotlin/String, kotlin.time/Duration? = ..., kotlin/Boolean? = ..., kotlin/Boolean? = ..., kotlin/Function1 = ...): io.ktor.client.plugins.sse/ClientSSESession // io.ktor.client.plugins.sse/serverSentEventsSession|serverSentEventsSession@io.ktor.client.HttpClient(kotlin.String;kotlin.time.Duration?;kotlin.Boolean?;kotlin.Boolean?;kotlin.Function1){}[0] +final suspend fun (io.ktor.client/HttpClient).io.ktor.client.plugins.sse/serverSentEventsSession(kotlin/String, kotlin/Function2, kotlin.time/Duration? = ..., kotlin/Boolean? = ..., kotlin/Boolean? = ..., kotlin/Function1 = ...): io.ktor.client.plugins.sse/ClientSSESessionWithDeserialization // io.ktor.client.plugins.sse/serverSentEventsSession|serverSentEventsSession@io.ktor.client.HttpClient(kotlin.String;kotlin.Function2;kotlin.time.Duration?;kotlin.Boolean?;kotlin.Boolean?;kotlin.Function1){}[0] final suspend fun (io.ktor.client/HttpClient).io.ktor.client.plugins.sse/serverSentEventsSession(kotlin/String? = ..., kotlin/String? = ..., kotlin/Int? = ..., kotlin/String? = ..., kotlin.time/Duration? = ..., kotlin/Boolean? = ..., kotlin/Boolean? = ..., kotlin/Function1 = ...): io.ktor.client.plugins.sse/ClientSSESession // io.ktor.client.plugins.sse/serverSentEventsSession|serverSentEventsSession@io.ktor.client.HttpClient(kotlin.String?;kotlin.String?;kotlin.Int?;kotlin.String?;kotlin.time.Duration?;kotlin.Boolean?;kotlin.Boolean?;kotlin.Function1){}[0] +final suspend fun (io.ktor.client/HttpClient).io.ktor.client.plugins.sse/serverSentEventsSession(kotlin/String? = ..., kotlin/String? = ..., kotlin/Int? = ..., kotlin/String? = ..., kotlin/Function2, kotlin.time/Duration? = ..., kotlin/Boolean? = ..., kotlin/Boolean? = ..., kotlin/Function1 = ...): io.ktor.client.plugins.sse/ClientSSESessionWithDeserialization // io.ktor.client.plugins.sse/serverSentEventsSession|serverSentEventsSession@io.ktor.client.HttpClient(kotlin.String?;kotlin.String?;kotlin.Int?;kotlin.String?;kotlin.Function2;kotlin.time.Duration?;kotlin.Boolean?;kotlin.Boolean?;kotlin.Function1){}[0] final suspend fun (io.ktor.client/HttpClient).io.ktor.client.plugins.sse/sse(kotlin/Function1, kotlin.time/Duration? = ..., kotlin/Boolean? = ..., kotlin/Boolean? = ..., kotlin.coroutines/SuspendFunction1) // io.ktor.client.plugins.sse/sse|sse@io.ktor.client.HttpClient(kotlin.Function1;kotlin.time.Duration?;kotlin.Boolean?;kotlin.Boolean?;kotlin.coroutines.SuspendFunction1){}[0] +final suspend fun (io.ktor.client/HttpClient).io.ktor.client.plugins.sse/sse(kotlin/Function1, kotlin/Function2, kotlin.time/Duration? = ..., kotlin/Boolean? = ..., kotlin/Boolean? = ..., kotlin.coroutines/SuspendFunction1) // io.ktor.client.plugins.sse/sse|sse@io.ktor.client.HttpClient(kotlin.Function1;kotlin.Function2;kotlin.time.Duration?;kotlin.Boolean?;kotlin.Boolean?;kotlin.coroutines.SuspendFunction1){}[0] final suspend fun (io.ktor.client/HttpClient).io.ktor.client.plugins.sse/sse(kotlin/String, kotlin/Function1 = ..., kotlin.time/Duration? = ..., kotlin/Boolean? = ..., kotlin/Boolean? = ..., kotlin.coroutines/SuspendFunction1) // io.ktor.client.plugins.sse/sse|sse@io.ktor.client.HttpClient(kotlin.String;kotlin.Function1;kotlin.time.Duration?;kotlin.Boolean?;kotlin.Boolean?;kotlin.coroutines.SuspendFunction1){}[0] +final suspend fun (io.ktor.client/HttpClient).io.ktor.client.plugins.sse/sse(kotlin/String, kotlin/Function1 = ..., kotlin/Function2, kotlin.time/Duration? = ..., kotlin/Boolean? = ..., kotlin/Boolean? = ..., kotlin.coroutines/SuspendFunction1) // io.ktor.client.plugins.sse/sse|sse@io.ktor.client.HttpClient(kotlin.String;kotlin.Function1;kotlin.Function2;kotlin.time.Duration?;kotlin.Boolean?;kotlin.Boolean?;kotlin.coroutines.SuspendFunction1){}[0] final suspend fun (io.ktor.client/HttpClient).io.ktor.client.plugins.sse/sse(kotlin/String? = ..., kotlin/String? = ..., kotlin/Int? = ..., kotlin/String? = ..., kotlin/Function1 = ..., kotlin.time/Duration? = ..., kotlin/Boolean? = ..., kotlin/Boolean? = ..., kotlin.coroutines/SuspendFunction1) // io.ktor.client.plugins.sse/sse|sse@io.ktor.client.HttpClient(kotlin.String?;kotlin.String?;kotlin.Int?;kotlin.String?;kotlin.Function1;kotlin.time.Duration?;kotlin.Boolean?;kotlin.Boolean?;kotlin.coroutines.SuspendFunction1){}[0] +final suspend fun (io.ktor.client/HttpClient).io.ktor.client.plugins.sse/sse(kotlin/String? = ..., kotlin/String? = ..., kotlin/Int? = ..., kotlin/String? = ..., kotlin/Function1 = ..., kotlin/Function2, kotlin.time/Duration? = ..., kotlin/Boolean? = ..., kotlin/Boolean? = ..., kotlin.coroutines/SuspendFunction1) // io.ktor.client.plugins.sse/sse|sse@io.ktor.client.HttpClient(kotlin.String?;kotlin.String?;kotlin.Int?;kotlin.String?;kotlin.Function1;kotlin.Function2;kotlin.time.Duration?;kotlin.Boolean?;kotlin.Boolean?;kotlin.coroutines.SuspendFunction1){}[0] final suspend fun (io.ktor.client/HttpClient).io.ktor.client.plugins.sse/sseSession(kotlin.time/Duration? = ..., kotlin/Boolean? = ..., kotlin/Boolean? = ..., kotlin/Function1): io.ktor.client.plugins.sse/ClientSSESession // io.ktor.client.plugins.sse/sseSession|sseSession@io.ktor.client.HttpClient(kotlin.time.Duration?;kotlin.Boolean?;kotlin.Boolean?;kotlin.Function1){}[0] +final suspend fun (io.ktor.client/HttpClient).io.ktor.client.plugins.sse/sseSession(kotlin/Function2, kotlin.time/Duration? = ..., kotlin/Boolean? = ..., kotlin/Boolean? = ..., kotlin/Function1): io.ktor.client.plugins.sse/ClientSSESessionWithDeserialization // io.ktor.client.plugins.sse/sseSession|sseSession@io.ktor.client.HttpClient(kotlin.Function2;kotlin.time.Duration?;kotlin.Boolean?;kotlin.Boolean?;kotlin.Function1){}[0] final suspend fun (io.ktor.client/HttpClient).io.ktor.client.plugins.sse/sseSession(kotlin/String, kotlin.time/Duration? = ..., kotlin/Boolean? = ..., kotlin/Boolean? = ..., kotlin/Function1 = ...): io.ktor.client.plugins.sse/ClientSSESession // io.ktor.client.plugins.sse/sseSession|sseSession@io.ktor.client.HttpClient(kotlin.String;kotlin.time.Duration?;kotlin.Boolean?;kotlin.Boolean?;kotlin.Function1){}[0] +final suspend fun (io.ktor.client/HttpClient).io.ktor.client.plugins.sse/sseSession(kotlin/String, kotlin/Function2, kotlin.time/Duration? = ..., kotlin/Boolean? = ..., kotlin/Boolean? = ..., kotlin/Function1 = ...): io.ktor.client.plugins.sse/ClientSSESessionWithDeserialization // io.ktor.client.plugins.sse/sseSession|sseSession@io.ktor.client.HttpClient(kotlin.String;kotlin.Function2;kotlin.time.Duration?;kotlin.Boolean?;kotlin.Boolean?;kotlin.Function1){}[0] final suspend fun (io.ktor.client/HttpClient).io.ktor.client.plugins.sse/sseSession(kotlin/String? = ..., kotlin/String? = ..., kotlin/Int? = ..., kotlin/String? = ..., kotlin.time/Duration? = ..., kotlin/Boolean? = ..., kotlin/Boolean? = ..., kotlin/Function1 = ...): io.ktor.client.plugins.sse/ClientSSESession // io.ktor.client.plugins.sse/sseSession|sseSession@io.ktor.client.HttpClient(kotlin.String?;kotlin.String?;kotlin.Int?;kotlin.String?;kotlin.time.Duration?;kotlin.Boolean?;kotlin.Boolean?;kotlin.Function1){}[0] +final suspend fun (io.ktor.client/HttpClient).io.ktor.client.plugins.sse/sseSession(kotlin/String? = ..., kotlin/String? = ..., kotlin/Int? = ..., kotlin/String? = ..., kotlin/Function2, kotlin.time/Duration? = ..., kotlin/Boolean? = ..., kotlin/Boolean? = ..., kotlin/Function1 = ...): io.ktor.client.plugins.sse/ClientSSESessionWithDeserialization // io.ktor.client.plugins.sse/sseSession|sseSession@io.ktor.client.HttpClient(kotlin.String?;kotlin.String?;kotlin.Int?;kotlin.String?;kotlin.Function2;kotlin.time.Duration?;kotlin.Boolean?;kotlin.Boolean?;kotlin.Function1){}[0] final suspend fun (io.ktor.client/HttpClient).io.ktor.client.plugins.websocket/webSocket(io.ktor.http/HttpMethod = ..., kotlin/String? = ..., kotlin/Int? = ..., kotlin/String? = ..., kotlin/Function1 = ..., kotlin.coroutines/SuspendFunction1) // io.ktor.client.plugins.websocket/webSocket|webSocket@io.ktor.client.HttpClient(io.ktor.http.HttpMethod;kotlin.String?;kotlin.Int?;kotlin.String?;kotlin.Function1;kotlin.coroutines.SuspendFunction1){}[0] final suspend fun (io.ktor.client/HttpClient).io.ktor.client.plugins.websocket/webSocket(kotlin/Function1, kotlin.coroutines/SuspendFunction1) // io.ktor.client.plugins.websocket/webSocket|webSocket@io.ktor.client.HttpClient(kotlin.Function1;kotlin.coroutines.SuspendFunction1){}[0] final suspend fun (io.ktor.client/HttpClient).io.ktor.client.plugins.websocket/webSocket(kotlin/String, kotlin/Function1 = ..., kotlin.coroutines/SuspendFunction1) // io.ktor.client.plugins.websocket/webSocket|webSocket@io.ktor.client.HttpClient(kotlin.String;kotlin.Function1;kotlin.coroutines.SuspendFunction1){}[0] @@ -1512,12 +1551,6 @@ final suspend inline fun <#A: reified kotlin/Any?> (io.ktor.client.plugins.webso final suspend inline fun <#A: reified kotlin/Any?> (io.ktor.client.plugins.websocket/DefaultClientWebSocketSession).io.ktor.client.plugins.websocket/sendSerialized(#A) // io.ktor.client.plugins.websocket/sendSerialized|sendSerialized@io.ktor.client.plugins.websocket.DefaultClientWebSocketSession(0:0){0§}[0] final suspend inline fun <#A: reified kotlin/Any?> (io.ktor.client.statement/HttpResponse).io.ktor.client.call/body(): #A // io.ktor.client.call/body|body@io.ktor.client.statement.HttpResponse(){0§}[0] -// Targets: [native] -final object io.ktor.client.engine/engines : kotlin.collections/Iterable> { // io.ktor.client.engine/engines|null[0] - final fun append(io.ktor.client.engine/HttpClientEngineFactory) // io.ktor.client.engine/engines.append|append(io.ktor.client.engine.HttpClientEngineFactory){}[0] - final fun iterator(): kotlin.collections/Iterator> // io.ktor.client.engine/engines.iterator|iterator(){}[0] -} - // Targets: [js, wasmJs] abstract interface io.ktor.client.fetch/AbortSignal : io.ktor.client.fetch/EventTarget { // io.ktor.client.fetch/AbortSignal|null[0] abstract var aborted // io.ktor.client.fetch/AbortSignal.aborted|{}aborted[0] @@ -1786,6 +1819,9 @@ open class io.ktor.client.engine.js/JsClientEngineConfig : io.ktor.client.engine // Targets: [js, wasmJs] final object io.ktor.client.engine.js/Js : io.ktor.client.engine/HttpClientEngineFactory { // io.ktor.client.engine.js/Js|null[0] final fun create(kotlin/Function1): io.ktor.client.engine/HttpClientEngine // io.ktor.client.engine.js/Js.create|create(kotlin.Function1){}[0] + final fun equals(kotlin/Any?): kotlin/Boolean // io.ktor.client.engine.js/Js.equals|equals(kotlin.Any?){}[0] + final fun hashCode(): kotlin/Int // io.ktor.client.engine.js/Js.hashCode|hashCode(){}[0] + final fun toString(): kotlin/String // io.ktor.client.engine.js/Js.toString|toString(){}[0] } // Targets: [js, wasmJs] @@ -2179,6 +2215,10 @@ abstract interface io.ktor.client.fetch/Uint8ArrayConstructor { // io.ktor.clien abstract fun of(kotlin/Array...): io.ktor.client.fetch/Uint8Array // io.ktor.client.fetch/Uint8ArrayConstructor.of|of(kotlin.Array...){}[0] } +// Targets: [js] +final val io.ktor.client.engine.js/initHook // io.ktor.client.engine.js/initHook|{}initHook[0] + final fun (): dynamic // io.ktor.client.engine.js/initHook.|(){}[0] + // Targets: [js] final inline fun (io.ktor.client.fetch/Uint8Array).io.ktor.client.fetch/get(kotlin/Number): kotlin/Number? // io.ktor.client.fetch/get|get@io.ktor.client.fetch.Uint8Array(kotlin.Number){}[0] diff --git a/ktor-client/ktor-client-core/build.gradle.kts b/ktor-client/ktor-client-core/build.gradle.kts index 19fdad7c0a8..f11621825cf 100644 --- a/ktor-client/ktor-client-core/build.gradle.kts +++ b/ktor-client/ktor-client-core/build.gradle.kts @@ -8,6 +8,7 @@ kotlin.sourceSets { commonMain { dependencies { api(project(":ktor-http")) + api(project(":ktor-http:ktor-http-cio")) api(project(":ktor-shared:ktor-events")) api(project(":ktor-shared:ktor-websocket-serialization")) api(project(":ktor-shared:ktor-sse")) diff --git a/ktor-client/ktor-client-core/common/src/io/ktor/client/HttpClient.kt b/ktor-client/ktor-client-core/common/src/io/ktor/client/HttpClient.kt index 874ff130392..75aabe09998 100644 --- a/ktor-client/ktor-client-core/common/src/io/ktor/client/HttpClient.kt +++ b/ktor-client/ktor-client-core/common/src/io/ktor/client/HttpClient.kt @@ -1,6 +1,6 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.client @@ -1449,7 +1449,7 @@ public class HttpClient( @Suppress("UNCHECKED_CAST") val plugin = installedFeatures[key as AttributeKey] - if (plugin is Closeable) { + if (plugin is AutoCloseable) { plugin.close() } } diff --git a/ktor-client/ktor-client-core/common/src/io/ktor/client/engine/HttpClientEngineBase.kt b/ktor-client/ktor-client-core/common/src/io/ktor/client/engine/HttpClientEngineBase.kt index 0ac6ebc76fb..8c7ec428928 100644 --- a/ktor-client/ktor-client-core/common/src/io/ktor/client/engine/HttpClientEngineBase.kt +++ b/ktor-client/ktor-client-core/common/src/io/ktor/client/engine/HttpClientEngineBase.kt @@ -1,11 +1,10 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.client.engine import io.ktor.util.* -import io.ktor.utils.io.core.* import kotlinx.atomicfu.* import kotlinx.coroutines.* import kotlin.coroutines.* @@ -39,19 +38,4 @@ public abstract class HttpClientEngineBase(private val engineName: String) : Htt public class ClientEngineClosedException(override val cause: Throwable? = null) : IllegalStateException("Client already closed") -/** - * Closes [CoroutineDispatcher] if it's [CloseableCoroutineDispatcher] or [Closeable]. - */ -@OptIn(ExperimentalCoroutinesApi::class) -private fun CoroutineDispatcher.close() { - try { - when (this) { - is CloseableCoroutineDispatcher -> close() - is Closeable -> close() - } - } catch (ignore: Throwable) { - // Some closeable dispatchers like Dispatchers.IO can't be closed. - } -} - internal expect fun ioDispatcher(): CoroutineDispatcher diff --git a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/DefaultTransform.kt b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/DefaultTransform.kt index 6d35d2a0f6e..3273ab2860b 100644 --- a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/DefaultTransform.kt +++ b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/DefaultTransform.kt @@ -8,6 +8,7 @@ import io.ktor.client.* import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* +import io.ktor.http.cio.* import io.ktor.http.content.* import io.ktor.util.logging.* import io.ktor.utils.io.* @@ -111,6 +112,22 @@ public fun HttpClient.defaultTransformers() { proceedWith(HttpResponseContainer(info, response.status)) } + MultiPartData::class -> { + val rawContentType = checkNotNull(context.response.headers[HttpHeaders.ContentType]) { + "No content type provided for multipart" + } + val contentType = ContentType.parse(rawContentType) + check(contentType.match(ContentType.MultiPart.FormData)) { + "Expected multipart/form-data, got $contentType" + } + + val contentLength = context.response.headers[HttpHeaders.ContentLength]?.toLong() + val body = CIOMultipartDataBase(coroutineContext, body, rawContentType, contentLength) + val parsedResponse = HttpResponseContainer(info, body) + + proceedWith(parsedResponse) + } + else -> null } if (result != null) { diff --git a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/sse/ClientSSESession.kt b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/sse/ClientSSESession.kt index e554ee5619b..43287d5f361 100644 --- a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/sse/ClientSSESession.kt +++ b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/sse/ClientSSESession.kt @@ -6,22 +6,209 @@ package io.ktor.client.plugins.sse import io.ktor.client.call.* import io.ktor.sse.* +import io.ktor.util.reflect.* import kotlinx.coroutines.* import kotlinx.coroutines.flow.* /** - * A Server-sent events session. - */ + * A session for handling Server-Sent Events (SSE) from a server. + * + * Example of usage: + * ```kotlin + * client.sse("http://localhost:8080/sse") { // `this` is `ClientSSESession` + * incoming.collect { event -> + * println("Id: ${event.id}") + * println("Event: ${event.event}") + * println("Data: ${event.data}") + * } + * } + * ``` + * + * To learn more, see [the SSE](https://en.wikipedia.org/wiki/Server-sent_events) + * and [the SSE specification](https://html.spec.whatwg.org/multipage/server-sent-events.html). +*/ public interface SSESession : CoroutineScope { /** - * An incoming server-sent events flow. + * An incoming Server-Sent Events (SSE) flow. + * + * Each [ServerSentEvent] can contain following fields: + * - [ServerSentEvent.data] data field of the event. + * - [ServerSentEvent.event] string identifying the type of event. + * - [ServerSentEvent.id] event ID. + * - [ServerSentEvent.retry] reconnection time, in milliseconds to wait before reconnecting. + * - [ServerSentEvent.comments] comment lines starting with a ':' character. */ public val incoming: Flow } /** - * A client Server-sent events session. + * A session with deserialization support for handling Server-Sent Events (SSE) from a server. * - * @property call associated with session. + * Example of usage: + * ```kotlin + * client.sse({ + * url("http://localhost:8080/serverSentEvents") + * }, deserialize = { + * typeInfo, jsonString -> + * val serializer = Json.serializersModule.serializer(typeInfo.kotlinType!!) + * Json.decodeFromString(serializer, jsonString)!! + * }) { // `this` is `ClientSSESessionWithDeserialization` + * incoming.collect { event: TypedServerSentEvent -> + * when (event.event) { + * "customer" -> { + * val customer: Customer? = deserialize(event.data) + * } + * "product" -> { + * val product: Product? = deserialize(event.data) + * } + * } + * } + * } + * ``` + * + * To learn more, see [the SSE](https://en.wikipedia.org/wiki/Server-sent_events) + * and [the SSE specification](https://html.spec.whatwg.org/multipage/server-sent-events.html). + */ +public interface SSESessionWithDeserialization : CoroutineScope { + /** + * An incoming Server-Sent Events (SSE) flow. + * + * Each [TypedServerSentEvent] can contain following fields: + * - [TypedServerSentEvent.data] data field of the event. It can be deserialized into an object + * of desired type using the [deserialize] function + * - [TypedServerSentEvent.event] string identifying the type of event. + * - [TypedServerSentEvent.id] event ID. + * - [TypedServerSentEvent.retry] reconnection time, in milliseconds to wait before reconnecting. + * - [TypedServerSentEvent.comments] comment lines starting with a ':' character. + */ + public val incoming: Flow> + + /** + * Deserializer for transforming the `data` field of a `ServerSentEvent` into a desired data object. + */ + public val deserializer: (TypeInfo, String) -> Any? +} + +/** + * Deserialize the provided [data] into an object of type [T] using the deserializer function + * defined in the [SSESessionWithDeserialization] interface. + * + * @param data The string data to deserialize. + * @return The deserialized object of type [T], or null if deserialization is not successful. + * + * Example of usage: + * ```kotlin + * client.sse({ + * url("http://localhost:8080/serverSentEvents") + * }, deserialize = { + * typeInfo, jsonString -> + * val serializer = Json.serializersModule.serializer(typeInfo.kotlinType!!) + * Json.decodeFromString(serializer, jsonString)!! + * }) { // `this` is `ClientSSESessionWithDeserialization` + * incoming.collect { event: TypedServerSentEvent -> + * when (event.event) { + * "customer" -> { + * val customer: Customer? = deserialize(event.data) + * } + * "product" -> { + * val product: Product? = deserialize(event.data) + * } + * } + * } + * } + * ``` + */ +public inline fun SSESessionWithDeserialization.deserialize(data: String?): T? { + return data?.let { + deserializer(typeInfo(), data) as? T + } +} + +/** + * Deserialize the provided [event] data into an object of type [T] using the deserializer function + * defined in the [SSESessionWithDeserialization] interface. + * + * @param event The Server-sent event containing data to deserialize. + * @return The deserialized object of type [T], or null if deserialization is not successful. + * + * Example of usage: + * ```kotlin + * client.sse({ + * url("http://localhost:8080/serverSentEvents") + * }, deserialize = { + * typeInfo, jsonString -> + * val serializer = Json.serializersModule.serializer(typeInfo.kotlinType!!) + * Json.decodeFromString(serializer, jsonString)!! + * }) { // `this` is `ClientSSESessionWithDeserialization` + * incoming.collect { event: TypedServerSentEvent -> + * when (event.event) { + * "customer" -> { + * val customer: Customer? = deserialize(event.data) + * } + * "product" -> { + * val product: Product? = deserialize(event.data) + * } + * } + * } + * } + * ``` + */ +public inline fun SSESessionWithDeserialization.deserialize( + event: TypedServerSentEvent +): T? = deserialize(event.data) + +/** + * A client session for handling Server-Sent Events (SSE) from a server. + * + * @property call The HTTP call associated with the session. + * + * Example of usage: + * ```kotlin + * client.sse("http://localhost:8080/sse") { // `this` is `ClientSSESession` + * incoming.collect { event -> + * println("Id: ${event.id}") + * println("Event: ${event.event}") + * println("Data: ${event.data}") + * } + * } + * ``` + * + * To learn more, see [the SSE](https://en.wikipedia.org/wiki/Server-sent_events) + * and [the SSE specification](https://html.spec.whatwg.org/multipage/server-sent-events.html). */ public class ClientSSESession(public val call: HttpClientCall, delegate: SSESession) : SSESession by delegate + +/** + * A client session with deserialization support for handling Server-Sent Events (SSE) from a server. + * + * @property call The HTTP call associated with the session. + * + * Example of usage: + * ```kotlin + * client.sse({ + * url("http://localhost:8080/serverSentEvents") + * }, deserialize = { + * typeInfo, jsonString -> + * val serializer = Json.serializersModule.serializer(typeInfo.kotlinType!!) + * Json.decodeFromString(serializer, jsonString)!! + * }) { // `this` is `ClientSSESessionWithDeserialization` + * incoming.collect { event: TypedServerSentEvent -> + * when (event.event) { + * "customer" -> { + * val customer: Customer? = deserialize(event.data) + * } + * "product" -> { + * val product: Product? = deserialize(event.data) + * } + * } + * } + * } + * ``` + * + * To learn more, see [the SSE](https://en.wikipedia.org/wiki/Server-sent_events) + * and [the SSE specification](https://html.spec.whatwg.org/multipage/server-sent-events.html). + */ +public class ClientSSESessionWithDeserialization( + public val call: HttpClientCall, + delegate: SSESessionWithDeserialization +) : SSESessionWithDeserialization by delegate diff --git a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/sse/SSE.kt b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/sse/SSE.kt index ecb623f9d37..e88b58c61ee 100644 --- a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/sse/SSE.kt +++ b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/sse/SSE.kt @@ -11,30 +11,65 @@ import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* import io.ktor.http.content.* +import io.ktor.sse.* import io.ktor.util.* import io.ktor.util.logging.* import io.ktor.util.pipeline.* +import io.ktor.util.reflect.* import io.ktor.utils.io.* +import kotlinx.coroutines.flow.* +import kotlin.coroutines.* internal val LOGGER = KtorSimpleLogger("io.ktor.client.plugins.sse.SSE") /** - * Indicates if a client engine supports Server-sent events. + * Indicates if a client engine supports Server-Sent Events (SSE). */ public data object SSECapability : HttpClientEngineCapability /** - * Client Server-sent events plugin that allows you to establish an SSE connection to a server - * and receive Server-sent events from it. + * Client Server-Sent Events (SSE) plugin that allows you to establish an SSE connection to a server + * and receive Server-Sent Events from it. + * For a simple session, use [ClientSSESession]. + * For a session with deserialization, use [ClientSSESessionWithDeserialization]. * * ```kotlin * val client = HttpClient { * install(SSE) * } - * client.sse { - * val event = incoming.receive() + * + * // SSE request + * client.serverSentEvents("http://localhost:8080/sse") { // `this` is `ClientSSESession` + * incoming.collect { event -> + * println("Id: ${event.id}") + * println("Event: ${event.event}") + * println("Data: ${event.data}") + * } + * } + * + * // SSE request with deserialization + * client.sse({ + * url("http://localhost:8080/serverSentEvents") + * }, deserialize = { + * typeInfo, jsonString -> + * val serializer = Json.serializersModule.serializer(typeInfo.kotlinType!!) + * Json.decodeFromString(serializer, jsonString)!! + * }) { // `this` is `ClientSSESessionWithDeserialization` + * incoming.collect { event: TypedServerSentEvent -> + * when (event.event) { + * "customer" -> { + * val customer: Customer? = deserialize(event.data) + * } + * "product" -> { + * val product: Product? = deserialize(event.data) + * } + * } + * } * } * ``` + * + * To learn more, see [the SSE](https://en.wikipedia.org/wiki/Server-sent_events) + * and [the SSE specification](https://html.spec.whatwg.org/multipage/server-sent-events.html). */ @OptIn(InternalAPI::class) public val SSE: ClientPlugin = createClientPlugin( @@ -96,7 +131,24 @@ public val SSE: ClientPlugin = createClientPlugin( } LOGGER.trace("Receive SSE session from ${response.request.url}: $session") - proceedWith(HttpResponseContainer(info, ClientSSESession(context, session))) + + val deserializer = response.request.attributes.getOrNull(deserializerAttr) + val clientSSESession = deserializer?.let { + ClientSSESessionWithDeserialization( + context, + object : SSESessionWithDeserialization { + override val incoming: Flow> = + session.incoming.map { event: ServerSentEvent -> + TypedServerSentEvent(event.data, event.event, event.id, event.retry, event.comments) + } + + override val deserializer: (TypeInfo, String) -> Any? = deserializer + + override val coroutineContext: CoroutineContext = session.coroutineContext + } + ) + } ?: ClientSSESession(context, session) + proceedWith(HttpResponseContainer(info, clientSSESession)) } } diff --git a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/sse/SSEConfig.kt b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/sse/SSEConfig.kt index e52f296a547..b84098f4f8d 100644 --- a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/sse/SSEConfig.kt +++ b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/sse/SSEConfig.kt @@ -23,14 +23,14 @@ public class SSEConfig { public var reconnectionTime: Duration = 3000.milliseconds /** - * Add events consisting only of comments in the incoming flow. + * Adds events consisting only of comments in the incoming flow. */ public fun showCommentEvents() { showCommentEvents = true } /** - * Add events consisting only of the retry field in the incoming flow. + * Adds events consisting only of the retry field in the incoming flow. */ public fun showRetryEvents() { showRetryEvents = true diff --git a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/sse/builders.kt b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/sse/builders.kt index e8c4e8f82bc..0c27d308628 100644 --- a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/sse/builders.kt +++ b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/sse/builders.kt @@ -10,6 +10,7 @@ import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* import io.ktor.util.* +import io.ktor.util.reflect.* import kotlinx.coroutines.* import kotlin.time.* @@ -17,9 +18,20 @@ internal val sseRequestAttr = AttributeKey("SSERequestFlag") internal val reconnectionTimeAttr = AttributeKey("SSEReconnectionTime") internal val showCommentEventsAttr = AttributeKey("SSEShowCommentEvents") internal val showRetryEventsAttr = AttributeKey("SSEShowRetryEvents") +internal val deserializerAttr = AttributeKey<(TypeInfo, String) -> Any?>("SSEDeserializer") /** * Installs the [SSE] plugin using the [config] as configuration. + * + * Example of usage: + * ```kotlin + * val client = HttpClient() { + * SSE { + * showCommentEvents() + * showRetryEvents() + * } + * } + * ``` */ public fun HttpClientConfig<*>.SSE(config: SSEConfig.() -> Unit) { install(SSE) { @@ -27,42 +39,52 @@ public fun HttpClientConfig<*>.SSE(config: SSEConfig.() -> Unit) { } } +// Builders for the `ClientSSESession` + /** - * Opens a [ClientSSESession]. + * Opens a [ClientSSESession] to receive Server-Sent Events (SSE) from a server. + * + * @param reconnectionTime The time duration to wait before attempting reconnection in case of connection loss + * @param showCommentEvents When enabled, events containing only comments field will be presented in the incoming flow + * @param showRetryEvents When enabled, events containing only comments field will be presented in the incoming flow + * + * Example of usage: + * ```kotlin + * val session = client.serverSentEventsSession { + * url("http://localhost:8080/sse") + * } + * session.incoming.collect { event -> + * println("Id: ${event.id}") + * println("Event: ${event.event}") + * println("Data: ${event.data}") + * } + * ``` */ public suspend fun HttpClient.serverSentEventsSession( reconnectionTime: Duration? = null, showCommentEvents: Boolean? = null, showRetryEvents: Boolean? = null, block: HttpRequestBuilder.() -> Unit -): ClientSSESession { - plugin(SSE) - - val sessionDeferred = CompletableDeferred() - val statement = prepareRequest { - block() - addAttribute(sseRequestAttr, true) - addAttribute(reconnectionTimeAttr, reconnectionTime) - addAttribute(showCommentEventsAttr, showCommentEvents) - addAttribute(showRetryEventsAttr, showRetryEvents) - } - @Suppress("SuspendFunctionOnCoroutineScope") - launch { - try { - statement.body { session -> - sessionDeferred.complete(session) - } - } catch (cause: CancellationException) { - sessionDeferred.cancel(cause) - } catch (cause: Throwable) { - sessionDeferred.completeExceptionally(mapToSSEException(response = null, cause)) - } - } - return sessionDeferred.await() -} +): ClientSSESession = processSession(reconnectionTime, showCommentEvents, showRetryEvents, block) {} /** - * Opens a [ClientSSESession]. + * Opens a [ClientSSESession] to receive Server-Sent Events (SSE) from a server. + * + * @param reconnectionTime The time duration to wait before attempting reconnection in case of connection loss + * @param showCommentEvents When enabled, events containing only comments field will be presented in the incoming flow + * @param showRetryEvents When enabled, events containing only comments field will be presented in the incoming flow + * + * Example of usage: + * ```kotlin + * val session = client.serverSentEventsSession { + * url("http://localhost:8080/sse") + * } + * session.incoming.collect { event -> + * println("Id: ${event.id}") + * println("Event: ${event.event}") + * println("Data: ${event.data}") + * } + * ``` */ public suspend fun HttpClient.serverSentEventsSession( scheme: String? = null, @@ -79,7 +101,23 @@ public suspend fun HttpClient.serverSentEventsSession( } /** - * Opens a [ClientSSESession]. + * Opens a [ClientSSESession] to receive Server-Sent Events (SSE) from a server. + * + * @param reconnectionTime The time duration to wait before attempting reconnection in case of connection loss + * @param showCommentEvents When enabled, events containing only comments field will be presented in the incoming flow + * @param showRetryEvents When enabled, events containing only comments field will be presented in the incoming flow + * + * Example of usage: + * ```kotlin + * val session = client.serverSentEventsSession { + * url("http://localhost:8080/sse") + * } + * session.incoming.collect { event -> + * println("Id: ${event.id}") + * println("Event: ${event.event}") + * println("Data: ${event.data}") + * } + * ``` */ public suspend fun HttpClient.serverSentEventsSession( urlString: String, @@ -93,7 +131,22 @@ public suspend fun HttpClient.serverSentEventsSession( } /** - * Opens a [block] with [ClientSSESession]. + * Opens a [ClientSSESession] to receive Server-Sent Events (SSE) from a server and performs [block]. + * + * @param reconnectionTime The time duration to wait before attempting reconnection in case of connection loss + * @param showCommentEvents When enabled, events containing only comments field will be presented in the incoming flow + * @param showRetryEvents When enabled, events containing only comments field will be presented in the incoming flow + * + * Example of usage: + * ```kotlin + * client.serverSentEvents("http://localhost:8080/sse") { // `this` is `ClientSSESession` + * incoming.collect { event -> + * println("Id: ${event.id}") + * println("Event: ${event.event}") + * println("Data: ${event.data}") + * } + * } + * ``` */ public suspend fun HttpClient.serverSentEvents( request: HttpRequestBuilder.() -> Unit, @@ -115,7 +168,22 @@ public suspend fun HttpClient.serverSentEvents( } /** - * Opens a [block] with [ClientSSESession]. + * Opens a [ClientSSESession] to receive Server-Sent Events (SSE) from a server and performs [block]. + * + * @param reconnectionTime The time duration to wait before attempting reconnection in case of connection loss + * @param showCommentEvents When enabled, events containing only comments field will be presented in the incoming flow + * @param showRetryEvents When enabled, events containing only comments field will be presented in the incoming flow + * + * Example of usage: + * ```kotlin + * client.serverSentEvents("http://localhost:8080/sse") { // `this` is `ClientSSESession` + * incoming.collect { event -> + * println("Id: ${event.id}") + * println("Event: ${event.event}") + * println("Data: ${event.data}") + * } + * } + * ``` */ public suspend fun HttpClient.serverSentEvents( scheme: String? = null, @@ -141,7 +209,22 @@ public suspend fun HttpClient.serverSentEvents( } /** - * Opens a [block] with [ClientSSESession]. + * Opens a [ClientSSESession] to receive Server-Sent Events (SSE) from a server and performs [block]. + * + * @param reconnectionTime The time duration to wait before attempting reconnection in case of connection loss + * @param showCommentEvents When enabled, events containing only comments field will be presented in the incoming flow + * @param showRetryEvents When enabled, events containing only comments field will be presented in the incoming flow + * + * Example of usage: + * ```kotlin + * client.serverSentEvents("http://localhost:8080/sse") { // `this` is `ClientSSESession` + * incoming.collect { event -> + * println("Id: ${event.id}") + * println("Event: ${event.event}") + * println("Data: ${event.data}") + * } + * } + * ``` */ public suspend fun HttpClient.serverSentEvents( urlString: String, @@ -164,7 +247,23 @@ public suspend fun HttpClient.serverSentEvents( } /** - * Opens a [ClientSSESession]. + * Opens a [ClientSSESession] to receive Server-Sent Events (SSE) from a server. + * + * @param reconnectionTime The time duration to wait before attempting reconnection in case of connection loss + * @param showCommentEvents When enabled, events containing only comments field will be presented in the incoming flow + * @param showRetryEvents When enabled, events containing only comments field will be presented in the incoming flow + * + * Example of usage: + * ```kotlin + * val session = client.sseSession { + * url("http://localhost:8080/sse") + * } + * session.incoming.collect { event -> + * println("Id: ${event.id}") + * println("Event: ${event.event}") + * println("Data: ${event.data}") + * } + * ``` */ public suspend fun HttpClient.sseSession( reconnectionTime: Duration? = null, @@ -174,7 +273,23 @@ public suspend fun HttpClient.sseSession( ): ClientSSESession = serverSentEventsSession(reconnectionTime, showCommentEvents, showRetryEvents, block) /** - * Opens a [ClientSSESession]. + * Opens a [ClientSSESession] to receive Server-Sent Events (SSE) from a server. + * + * @param reconnectionTime The time duration to wait before attempting reconnection in case of connection loss + * @param showCommentEvents When enabled, events containing only comments field will be presented in the incoming flow + * @param showRetryEvents When enabled, events containing only comments field will be presented in the incoming flow + * + * Example of usage: + * ```kotlin + * val session = client.sseSession { + * url("http://localhost:8080/sse") + * } + * session.incoming.collect { event -> + * println("Id: ${event.id}") + * println("Event: ${event.event}") + * println("Data: ${event.data}") + * } + * ``` */ public suspend fun HttpClient.sseSession( scheme: String? = null, @@ -189,7 +304,23 @@ public suspend fun HttpClient.sseSession( serverSentEventsSession(scheme, host, port, path, reconnectionTime, showCommentEvents, showRetryEvents, block) /** - * Opens a [ClientSSESession]. + * Opens a [ClientSSESession] to receive Server-Sent Events (SSE) from a server. + * + * @param reconnectionTime The time duration to wait before attempting reconnection in case of connection loss + * @param showCommentEvents When enabled, events containing only comments field will be presented in the incoming flow + * @param showRetryEvents When enabled, events containing only comments field will be presented in the incoming flow + * + * Example of usage: + * ```kotlin + * val session = client.sseSession { + * url("http://localhost:8080/sse") + * } + * session.incoming.collect { event -> + * println("Id: ${event.id}") + * println("Event: ${event.event}") + * println("Data: ${event.data}") + * } + * ``` */ public suspend fun HttpClient.sseSession( urlString: String, @@ -200,7 +331,22 @@ public suspend fun HttpClient.sseSession( ): ClientSSESession = serverSentEventsSession(urlString, reconnectionTime, showCommentEvents, showRetryEvents, block) /** - * Opens a [block] with [ClientSSESession]. + * Opens a [ClientSSESession] to receive Server-Sent Events (SSE) from a server and performs [block]. + * + * @param reconnectionTime The time duration to wait before attempting reconnection in case of connection loss + * @param showCommentEvents When enabled, events containing only comments field will be presented in the incoming flow + * @param showRetryEvents When enabled, events containing only comments field will be presented in the incoming flow + * + * Example of usage: + * ```kotlin + * client.sse("http://localhost:8080/sse") { // `this` is `ClientSSESession` + * incoming.collect { event -> + * println("Id: ${event.id}") + * println("Event: ${event.event}") + * println("Data: ${event.data}") + * } + * } + * ``` */ public suspend fun HttpClient.sse( request: HttpRequestBuilder.() -> Unit, @@ -211,7 +357,22 @@ public suspend fun HttpClient.sse( ): Unit = serverSentEvents(request, reconnectionTime, showCommentEvents, showRetryEvents, block) /** - * Opens a [block] with [ClientSSESession]. + * Opens a [ClientSSESession] to receive Server-Sent Events (SSE) from a server and performs [block]. + * + * @param reconnectionTime The time duration to wait before attempting reconnection in case of connection loss + * @param showCommentEvents When enabled, events containing only comments field will be presented in the incoming flow + * @param showRetryEvents When enabled, events containing only comments field will be presented in the incoming flow + * + * Example of usage: + * ```kotlin + * client.sse("http://localhost:8080/sse") { // `this` is `ClientSSESession` + * incoming.collect { event -> + * println("Id: ${event.id}") + * println("Event: ${event.event}") + * println("Data: ${event.data}") + * } + * } + * ``` */ public suspend fun HttpClient.sse( scheme: String? = null, @@ -227,7 +388,22 @@ public suspend fun HttpClient.sse( serverSentEvents(scheme, host, port, path, reconnectionTime, showCommentEvents, showRetryEvents, request, block) /** - * Opens a [block] with [ClientSSESession]. + * Opens a [ClientSSESession] to receive Server-Sent Events (SSE) from a server and performs [block]. + * + * @param reconnectionTime The time duration to wait before attempting reconnection in case of connection loss + * @param showCommentEvents When enabled, events containing only comments field will be presented in the incoming flow + * @param showRetryEvents When enabled, events containing only comments field will be presented in the incoming flow + * + * Example of usage: + * ```kotlin + * client.sse("http://localhost:8080/sse") { // `this` is `ClientSSESession` + * incoming.collect { event -> + * println("Id: ${event.id}") + * println("Event: ${event.event}") + * println("Data: ${event.data}") + * } + * } + * ``` */ public suspend fun HttpClient.sse( urlString: String, @@ -238,6 +414,618 @@ public suspend fun HttpClient.sse( block: suspend ClientSSESession.() -> Unit ): Unit = serverSentEvents(urlString, reconnectionTime, showCommentEvents, showRetryEvents, request, block) +// Builders for the `ClientSSESessionWithDeserialization` + +/** + * Opens a [ClientSSESessionWithDeserialization] to receive Server-Sent Events (SSE) from a server with ability to + * deserialize the `data` field of the `TypedServerSentEvent`. + * + * @param deserialize The deserializer function to transform the `data` field of the `TypedServerSentEvent` + * into an object + * @param reconnectionTime The time duration to wait before attempting reconnection in case of connection loss + * @param showCommentEvents When enabled, events containing only comments field will be presented in the incoming flow + * @param showRetryEvents When enabled, events containing only comments field will be presented in the incoming flow + * + * Example of usage: + * ```kotlin + * val session = client.serverSentEventsSession("http://localhost:8080/sse", deserialize = { typeInfo, jsonString -> + * val serializer = Json.serializersModule.serializer(typeInfo.kotlinType!!) + * Json.decodeFromString(serializer, jsonString)!! + * }) + * + * session.apply { + * incoming.collect { event: TypedServerSentEvent -> + * when (event.event) { + * "customer" -> { + * val customer: Customer? = deserialize(event.data) + * } + * + * "product" -> { + * val product: Product? = deserialize(event.data) + * } + * } + * } + * } + * ``` + */ +public suspend fun HttpClient.serverSentEventsSession( + deserialize: (TypeInfo, String) -> Any?, + reconnectionTime: Duration? = null, + showCommentEvents: Boolean? = null, + showRetryEvents: Boolean? = null, + block: HttpRequestBuilder.() -> Unit +): ClientSSESessionWithDeserialization = processSession(reconnectionTime, showCommentEvents, showRetryEvents, block) { + addAttribute( + deserializerAttr, + deserialize + ) +} + +/** + * Opens a [ClientSSESessionWithDeserialization] to receive Server-Sent Events (SSE) from a server with ability to + * deserialize the `data` field of the `TypedServerSentEvent`. + * + * @param deserialize The deserializer function to transform the `data` field of the `TypedServerSentEvent` + * into an object + * @param reconnectionTime The time duration to wait before attempting reconnection in case of connection loss + * @param showCommentEvents When enabled, events containing only comments field will be presented in the incoming flow + * @param showRetryEvents When enabled, events containing only comments field will be presented in the incoming flow + * + * Example of usage: + * ```kotlin + * val session = client.serverSentEventsSession("http://localhost:8080/sse", deserialize = { typeInfo, jsonString -> + * val serializer = Json.serializersModule.serializer(typeInfo.kotlinType!!) + * Json.decodeFromString(serializer, jsonString)!! + * }) + * + * session.apply { + * incoming.collect { event: TypedServerSentEvent -> + * when (event.event) { + * "customer" -> { + * val customer: Customer? = deserialize(event.data) + * } + * + * "product" -> { + * val product: Product? = deserialize(event.data) + * } + * } + * } + * } + * ``` + */ +public suspend fun HttpClient.serverSentEventsSession( + scheme: String? = null, + host: String? = null, + port: Int? = null, + path: String? = null, + deserialize: (TypeInfo, String) -> Any?, + reconnectionTime: Duration? = null, + showCommentEvents: Boolean? = null, + showRetryEvents: Boolean? = null, + block: HttpRequestBuilder.() -> Unit = {} +): ClientSSESessionWithDeserialization = + serverSentEventsSession(deserialize, reconnectionTime, showCommentEvents, showRetryEvents) { + url(scheme, host, port, path) + block() + } + +/** + * Opens a [ClientSSESessionWithDeserialization] to receive Server-Sent Events (SSE) from a server with ability to + * deserialize the `data` field of the `TypedServerSentEvent`. + * + * @param deserialize The deserializer function to transform the `data` field of the `TypedServerSentEvent` + * into an object + * @param reconnectionTime The time duration to wait before attempting reconnection in case of connection loss + * @param showCommentEvents When enabled, events containing only comments field will be presented in the incoming flow + * @param showRetryEvents When enabled, events containing only comments field will be presented in the incoming flow + * + * Example of usage: + * ```kotlin + * val session = client.serverSentEventsSession("http://localhost:8080/sse", deserialize = { typeInfo, jsonString -> + * val serializer = Json.serializersModule.serializer(typeInfo.kotlinType!!) + * Json.decodeFromString(serializer, jsonString)!! + * }) + * + * session.apply { + * incoming.collect { event: TypedServerSentEvent -> + * when (event.event) { + * "customer" -> { + * val customer: Customer? = deserialize(event.data) + * } + * + * "product" -> { + * val product: Product? = deserialize(event.data) + * } + * } + * } + * } + * ``` + */ +public suspend fun HttpClient.serverSentEventsSession( + urlString: String, + deserialize: (TypeInfo, String) -> Any?, + reconnectionTime: Duration? = null, + showCommentEvents: Boolean? = null, + showRetryEvents: Boolean? = null, + block: HttpRequestBuilder.() -> Unit = {} +): ClientSSESessionWithDeserialization = + serverSentEventsSession(deserialize, reconnectionTime, showCommentEvents, showRetryEvents) { + url.takeFrom(urlString) + block() + } + +/** + * Opens a [ClientSSESessionWithDeserialization] to receive Server-Sent Events (SSE) from a server with ability to + * deserialize the `data` field of the `TypedServerSentEvent`. + * + * @param deserialize The deserializer function to transform the `data` field of the `TypedServerSentEvent` + * into an object + * @param reconnectionTime The time duration to wait before attempting reconnection in case of connection loss + * @param showCommentEvents When enabled, events containing only comments field will be presented in the incoming flow + * @param showRetryEvents When enabled, events containing only comments field will be presented in the incoming flow + * + * Example of usage: + * ```kotlin + * client.serverSentEvents({ + * url("http://localhost:8080/sse") + * }, deserialize = { + * typeInfo, jsonString -> + * val serializer = Json.serializersModule.serializer(typeInfo.kotlinType!!) + * Json.decodeFromString(serializer, jsonString)!! + * }) { // `this` is `ClientSSESessionWithDeserialization` + * incoming.collect { event: TypedServerSentEvent -> + * when (event.event) { + * "customer" -> { + * val customer: Customer? = deserialize(event.data) + * } + * "product" -> { + * val product: Product? = deserialize(event.data) + * } + * } + * } + * } + * ``` + */ +public suspend fun HttpClient.serverSentEvents( + request: HttpRequestBuilder.() -> Unit, + deserialize: (TypeInfo, String) -> Any?, + reconnectionTime: Duration? = null, + showCommentEvents: Boolean? = null, + showRetryEvents: Boolean? = null, + block: suspend ClientSSESessionWithDeserialization.() -> Unit +) { + val session = serverSentEventsSession(deserialize, reconnectionTime, showCommentEvents, showRetryEvents, request) + try { + block(session) + } catch (cause: CancellationException) { + throw cause + } catch (cause: Throwable) { + throw mapToSSEException(session.call.response, cause) + } finally { + session.cancel() + } +} + +/** + * Opens a [ClientSSESessionWithDeserialization] to receive Server-Sent Events (SSE) from a server with ability to + * deserialize the `data` field of the `TypedServerSentEvent` and performs [block]. + * + * @param deserialize The deserializer function to transform the `data` field of the `TypedServerSentEvent` + * into an object + * @param reconnectionTime The time duration to wait before attempting reconnection in case of connection loss + * @param showCommentEvents When enabled, events containing only comments field will be presented in the incoming flow + * @param showRetryEvents When enabled, events containing only comments field will be presented in the incoming flow + * + * Example of usage: + * ```kotlin + * client.serverSentEvents({ + * url("http://localhost:8080/sse") + * }, deserialize = { + * typeInfo, jsonString -> + * val serializer = Json.serializersModule.serializer(typeInfo.kotlinType!!) + * Json.decodeFromString(serializer, jsonString)!! + * }) { // `this` is `ClientSSESessionWithDeserialization` + * incoming.collect { event: TypedServerSentEvent -> + * when (event.event) { + * "customer" -> { + * val customer: Customer? = deserialize(event.data) + * } + * "product" -> { + * val product: Product? = deserialize(event.data) + * } + * } + * } + * } + * ``` + */ +public suspend fun HttpClient.serverSentEvents( + scheme: String? = null, + host: String? = null, + port: Int? = null, + path: String? = null, + deserialize: (TypeInfo, String) -> Any?, + reconnectionTime: Duration? = null, + showCommentEvents: Boolean? = null, + showRetryEvents: Boolean? = null, + request: HttpRequestBuilder.() -> Unit = {}, + block: suspend ClientSSESessionWithDeserialization.() -> Unit +) { + serverSentEvents( + { + url(scheme, host, port, path) + request() + }, + deserialize, + reconnectionTime, + showCommentEvents, + showRetryEvents, + block + ) +} + +/** + * Opens a [ClientSSESessionWithDeserialization] to receive Server-Sent Events (SSE) from a server with ability to + * deserialize the `data` field of the `TypedServerSentEvent` and performs [block]. + * + * @param deserialize The deserializer function to transform the `data` field of the `TypedServerSentEvent` + * into an object + * @param reconnectionTime The time duration to wait before attempting reconnection in case of connection loss + * @param showCommentEvents When enabled, events containing only comments field will be presented in the incoming flow + * @param showRetryEvents When enabled, events containing only comments field will be presented in the incoming flow + * + * Example of usage: + * ```kotlin + * client.sse({ + * url("http://localhost:8080/serverSentEvents") + * }, deserialize = { + * typeInfo, jsonString -> + * val serializer = Json.serializersModule.serializer(typeInfo.kotlinType!!) + * Json.decodeFromString(serializer, jsonString)!! + * }) { // `this` is `ClientSSESessionWithDeserialization` + * incoming.collect { event: TypedServerSentEvent -> + * when (event.event) { + * "customer" -> { + * val customer: Customer? = deserialize(event.data) + * } + * "product" -> { + * val product: Product? = deserialize(event.data) + * } + * } + * } + * } + * ``` + */ +public suspend fun HttpClient.serverSentEvents( + urlString: String, + deserialize: (TypeInfo, String) -> Any?, + reconnectionTime: Duration? = null, + showCommentEvents: Boolean? = null, + showRetryEvents: Boolean? = null, + request: HttpRequestBuilder.() -> Unit = {}, + block: suspend ClientSSESessionWithDeserialization.() -> Unit +) { + serverSentEvents( + { + url.takeFrom(urlString) + request() + }, + deserialize, + reconnectionTime, + showCommentEvents, + showRetryEvents, + block + ) +} + +/** + * Opens a [ClientSSESessionWithDeserialization] to receive Server-Sent Events (SSE) from a server with ability to + * deserialize the `data` field of the `TypedServerSentEvent` and performs [block]. + * + * @param deserialize The deserializer function to transform the `data` field of the `TypedServerSentEvent` + * into an object + * @param reconnectionTime The time duration to wait before attempting reconnection in case of connection loss + * @param showCommentEvents When enabled, events containing only comments field will be presented in the incoming flow + * @param showRetryEvents When enabled, events containing only comments field will be presented in the incoming flow + * + * Example of usage: + * ```kotlin + * val session = client.sseSession("http://localhost:8080/sse", deserialize = { typeInfo, jsonString -> + * val serializer = Json.serializersModule.serializer(typeInfo.kotlinType!!) + * Json.decodeFromString(serializer, jsonString)!! + * }) + * + * session.apply { + * incoming.collect { event: TypedServerSentEvent -> + * when (event.event) { + * "customer" -> { + * val customer: Customer? = deserialize(event.data) + * } + * + * "product" -> { + * val product: Product? = deserialize(event.data) + * } + * } + * } + * } + * ``` + */ +public suspend fun HttpClient.sseSession( + deserialize: (TypeInfo, String) -> Any?, + reconnectionTime: Duration? = null, + showCommentEvents: Boolean? = null, + showRetryEvents: Boolean? = null, + block: HttpRequestBuilder.() -> Unit +): ClientSSESessionWithDeserialization = + serverSentEventsSession(deserialize, reconnectionTime, showCommentEvents, showRetryEvents, block) + +/** + * Opens a [ClientSSESessionWithDeserialization] to receive Server-Sent Events (SSE) from a server with ability to + * deserialize the `data` field of the `TypedServerSentEvent` and performs [block]. + * + * @param deserialize The deserializer function to transform the `data` field of the `TypedServerSentEvent` + * into an object + * @param reconnectionTime The time duration to wait before attempting reconnection in case of connection loss + * @param showCommentEvents When enabled, events containing only comments field will be presented in the incoming flow + * @param showRetryEvents When enabled, events containing only comments field will be presented in the incoming flow + * + * Example of usage: + * ```kotlin + * val session = client.sseSession("http://localhost:8080/sse", deserialize = { typeInfo, jsonString -> + * val serializer = Json.serializersModule.serializer(typeInfo.kotlinType!!) + * Json.decodeFromString(serializer, jsonString)!! + * }) + * + * session.apply { + * incoming.collect { event: TypedServerSentEvent -> + * when (event.event) { + * "customer" -> { + * val customer: Customer? = deserialize(event.data) + * } + * + * "product" -> { + * val product: Product? = deserialize(event.data) + * } + * } + * } + * } + * ``` + */ +public suspend fun HttpClient.sseSession( + scheme: String? = null, + host: String? = null, + port: Int? = null, + path: String? = null, + deserialize: (TypeInfo, String) -> Any?, + reconnectionTime: Duration? = null, + showCommentEvents: Boolean? = null, + showRetryEvents: Boolean? = null, + block: HttpRequestBuilder.() -> Unit = {} +): ClientSSESessionWithDeserialization = serverSentEventsSession( + scheme, + host, + port, + path, + deserialize, + reconnectionTime, + showCommentEvents, + showRetryEvents, + block +) + +/** + * Opens a [ClientSSESessionWithDeserialization] to receive Server-Sent Events (SSE) from a server with ability to + * deserialize the `data` field of the `TypedServerSentEvent` and performs [block]. + * + * @param deserialize The deserializer function to transform the `data` field of the `TypedServerSentEvent` + * into an object + * @param reconnectionTime The time duration to wait before attempting reconnection in case of connection loss + * @param showCommentEvents When enabled, events containing only comments field will be presented in the incoming flow + * @param showRetryEvents When enabled, events containing only comments field will be presented in the incoming flow + * + * Example of usage: + * ```kotlin + * val session = client.sseSession("http://localhost:8080/sse", deserialize = { typeInfo, jsonString -> + * val serializer = Json.serializersModule.serializer(typeInfo.kotlinType!!) + * Json.decodeFromString(serializer, jsonString)!! + * }) + * + * session.apply { + * incoming.collect { event: TypedServerSentEvent -> + * when (event.event) { + * "customer" -> { + * val customer: Customer? = deserialize(event.data) + * } + * + * "product" -> { + * val product: Product? = deserialize(event.data) + * } + * } + * } + * } + * ``` + */ +public suspend fun HttpClient.sseSession( + urlString: String, + deserialize: (TypeInfo, String) -> Any?, + reconnectionTime: Duration? = null, + showCommentEvents: Boolean? = null, + showRetryEvents: Boolean? = null, + block: HttpRequestBuilder.() -> Unit = {} +): ClientSSESessionWithDeserialization = + serverSentEventsSession(urlString, deserialize, reconnectionTime, showCommentEvents, showRetryEvents, block) + +/** + * Opens a [ClientSSESessionWithDeserialization] to receive Server-Sent Events (SSE) from a server with ability to + * deserialize the `data` field of the `TypedServerSentEvent` and performs [block]. + * + * @param deserialize The deserializer function to transform the `data` field of the `TypedServerSentEvent` + * into an object + * @param reconnectionTime The time duration to wait before attempting reconnection in case of connection loss + * @param showCommentEvents When enabled, events containing only comments field will be presented in the incoming flow + * @param showRetryEvents When enabled, events containing only comments field will be presented in the incoming flow + * + * Example of usage: + * ```kotlin + * client.sse({ + * url("http://localhost:8080/sse") + * }, deserialize = { + * typeInfo, jsonString -> + * val serializer = Json.serializersModule.serializer(typeInfo.kotlinType!!) + * Json.decodeFromString(serializer, jsonString)!! + * }) { // `this` is `ClientSSESessionWithDeserialization` + * incoming.collect { event: TypedServerSentEvent -> + * when (event.event) { + * "customer" -> { + * val customer: Customer? = deserialize(event.data) + * } + * "product" -> { + * val product: Product? = deserialize(event.data) + * } + * } + * } + * } + * ``` + */ +public suspend fun HttpClient.sse( + request: HttpRequestBuilder.() -> Unit, + deserialize: (TypeInfo, String) -> Any?, + reconnectionTime: Duration? = null, + showCommentEvents: Boolean? = null, + showRetryEvents: Boolean? = null, + block: suspend ClientSSESessionWithDeserialization.() -> Unit +): Unit = serverSentEvents(request, deserialize, reconnectionTime, showCommentEvents, showRetryEvents, block) + +/** + * Opens a [ClientSSESessionWithDeserialization] to receive Server-Sent Events (SSE) from a server with ability to + * deserialize the `data` field of the `TypedServerSentEvent` and performs [block]. + * + * @param deserialize The deserializer function to transform the `data` field of the `TypedServerSentEvent` + * into an object + * @param reconnectionTime The time duration to wait before attempting reconnection in case of connection loss + * @param showCommentEvents When enabled, events containing only comments field will be presented in the incoming flow + * @param showRetryEvents When enabled, events containing only comments field will be presented in the incoming flow + * + * Example of usage: + * ```kotlin + * client.sse({ + * url("http://localhost:8080/sse") + * }, deserialize = { + * typeInfo, jsonString -> + * val serializer = Json.serializersModule.serializer(typeInfo.kotlinType!!) + * Json.decodeFromString(serializer, jsonString)!! + * }) { // `this` is `ClientSSESessionWithDeserialization` + * incoming.collect { event: TypedServerSentEvent -> + * when (event.event) { + * "customer" -> { + * val customer: Customer? = deserialize(event.data) + * } + * "product" -> { + * val product: Product? = deserialize(event.data) + * } + * } + * } + * } + * ``` + */ +public suspend fun HttpClient.sse( + scheme: String? = null, + host: String? = null, + port: Int? = null, + path: String? = null, + request: HttpRequestBuilder.() -> Unit = {}, + deserialize: (TypeInfo, String) -> Any?, + reconnectionTime: Duration? = null, + showCommentEvents: Boolean? = null, + showRetryEvents: Boolean? = null, + block: suspend ClientSSESessionWithDeserialization.() -> Unit +): Unit = serverSentEvents( + scheme, + host, + port, + path, + deserialize, + reconnectionTime, + showCommentEvents, + showRetryEvents, + request, + block +) + +/** + * Opens a [ClientSSESessionWithDeserialization] to receive Server-Sent Events (SSE) from a server with ability to + * deserialize the `data` field of the `TypedServerSentEvent` and performs [block]. + * + * @param deserialize The deserializer function to transform the `data` field of the `TypedServerSentEvent` + * into an object + * @param reconnectionTime The time duration to wait before attempting reconnection in case of connection loss + * @param showCommentEvents When enabled, events containing only comments field will be presented in the incoming flow + * @param showRetryEvents When enabled, events containing only comments field will be presented in the incoming flow + * + * Example of usage: + * ```kotlin + * client.sse({ + * url("http://localhost:8080/sse") + * }, deserialize = { + * typeInfo, jsonString -> + * val serializer = Json.serializersModule.serializer(typeInfo.kotlinType!!) + * Json.decodeFromString(serializer, jsonString)!! + * }) { // `this` is `ClientSSESessionWithDeserialization` + * incoming.collect { event: TypedServerSentEvent -> + * when (event.event) { + * "customer" -> { + * val customer: Customer? = deserialize(event.data) + * } + * "product" -> { + * val product: Product? = deserialize(event.data) + * } + * } + * } + * } + * ``` + */ +public suspend fun HttpClient.sse( + urlString: String, + request: HttpRequestBuilder.() -> Unit = {}, + deserialize: (TypeInfo, String) -> Any?, + reconnectionTime: Duration? = null, + showCommentEvents: Boolean? = null, + showRetryEvents: Boolean? = null, + block: suspend ClientSSESessionWithDeserialization.() -> Unit +): Unit = serverSentEvents(urlString, deserialize, reconnectionTime, showCommentEvents, showRetryEvents, request, block) + +private suspend inline fun HttpClient.processSession( + reconnectionTime: Duration?, + showCommentEvents: Boolean?, + showRetryEvents: Boolean?, + block: HttpRequestBuilder.() -> Unit, + additionalAttributes: HttpRequestBuilder.() -> Unit +): T { + plugin(SSE) + + val sessionDeferred = CompletableDeferred() + val statement = prepareRequest { + block() + addAttribute(sseRequestAttr, true) + addAttribute(reconnectionTimeAttr, reconnectionTime) + addAttribute(showCommentEventsAttr, showCommentEvents) + addAttribute(showRetryEventsAttr, showRetryEvents) + additionalAttributes() + } + @Suppress("SuspendFunctionOnCoroutineScope") + launch { + try { + statement.body { session -> + sessionDeferred.complete(session) + } + } catch (cause: CancellationException) { + sessionDeferred.cancel(cause) + } catch (cause: Throwable) { + sessionDeferred.completeExceptionally(mapToSSEException(response = null, cause)) + } + } + return sessionDeferred.await() +} + private fun HttpRequestBuilder.addAttribute(attributeKey: AttributeKey, value: T?) { if (value != null) { attributes.put(attributeKey, value) diff --git a/ktor-client/ktor-client-core/common/src/io/ktor/client/request/HttpRequest.kt b/ktor-client/ktor-client-core/common/src/io/ktor/client/request/HttpRequest.kt index a55c6b4395d..e4f283b97a3 100644 --- a/ktor-client/ktor-client-core/common/src/io/ktor/client/request/HttpRequest.kt +++ b/ktor-client/ktor-client-core/common/src/io/ktor/client/request/HttpRequest.kt @@ -339,8 +339,9 @@ public class SSEClientResponseAdapter : ResponseAdapter { status == HttpStatusCode.OK && contentType?.withoutParameters() == ContentType.Text.EventStream ) { + outgoingContent as SSEClientContent DefaultClientSSESession( - outgoingContent as SSEClientContent, + outgoingContent, responseBody, callContext ) diff --git a/ktor-client/ktor-client-core/js/src/io/ktor/client/engine/js/Js.kt b/ktor-client/ktor-client-core/js/src/io/ktor/client/engine/js/Js.kt index e94bd74ef32..3b12c807001 100644 --- a/ktor-client/ktor-client-core/js/src/io/ktor/client/engine/js/Js.kt +++ b/ktor-client/ktor-client-core/js/src/io/ktor/client/engine/js/Js.kt @@ -1,10 +1,11 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.engine.js import io.ktor.client.engine.* +import io.ktor.utils.io.* /** * A JavaScript client engine that uses the fetch API to execute requests. @@ -20,7 +21,7 @@ import io.ktor.client.engine.* * * You can learn more about client engines from [Engines](https://ktor.io/docs/http-client-engines.html). */ -public actual object Js : HttpClientEngineFactory { +public actual data object Js : HttpClientEngineFactory { override fun create(block: JsClientEngineConfig.() -> Unit): HttpClientEngine = JsClientEngine(JsClientEngineConfig().apply(block)) } @@ -45,3 +46,10 @@ public actual open class JsClientEngineConfig : HttpClientEngineConfig() { */ public var nodeOptions: dynamic = js("Object").create(null) } + +@Suppress("DEPRECATION") +@OptIn(ExperimentalStdlibApi::class, ExperimentalJsExport::class, InternalAPI::class) +@Deprecated("", level = DeprecationLevel.HIDDEN) +@JsExport +@EagerInitialization +public val initHook: dynamic = engines.append(Js) diff --git a/ktor-client/ktor-client-core/jsAndWasmShared/src/io/ktor/client/HttpClientJs.kt b/ktor-client/ktor-client-core/jsAndWasmShared/src/io/ktor/client/HttpClientJs.kt index 95c8f4c333d..db69d907cdc 100644 --- a/ktor-client/ktor-client-core/jsAndWasmShared/src/io/ktor/client/HttpClientJs.kt +++ b/ktor-client/ktor-client-core/jsAndWasmShared/src/io/ktor/client/HttpClientJs.kt @@ -1,9 +1,10 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client +import io.ktor.client.engine.* import io.ktor.client.engine.js.* import io.ktor.utils.io.* @@ -16,4 +17,9 @@ import io.ktor.utils.io.* @KtorDsl public actual fun HttpClient( block: HttpClientConfig<*>.() -> Unit -): HttpClient = HttpClient(JsClient(), block) +): HttpClient = HttpClient(FACTORY, block) + +// we need to fall back to the default (Js) engine if there are no other engines, +// but in the presence of other engines, they're preferred. +@OptIn(InternalAPI::class) +private val FACTORY = engines.firstOrNull { it != Js } ?: Js diff --git a/ktor-client/ktor-client-core/jvm/src/io/ktor/client/plugins/cache/storage/FileCacheStorage.kt b/ktor-client/ktor-client-core/jvm/src/io/ktor/client/plugins/cache/storage/FileCacheStorage.kt index 40887edfb05..12fef1b75e6 100644 --- a/ktor-client/ktor-client-core/jvm/src/io/ktor/client/plugins/cache/storage/FileCacheStorage.kt +++ b/ktor-client/ktor-client-core/jvm/src/io/ktor/client/plugins/cache/storage/FileCacheStorage.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.plugins.cache.storage @@ -10,7 +10,6 @@ import io.ktor.util.* import io.ktor.util.collections.* import io.ktor.util.date.* import io.ktor.utils.io.* -import io.ktor.utils.io.core.* import io.ktor.utils.io.jvm.javaio.* import kotlinx.coroutines.* import kotlinx.coroutines.sync.* diff --git a/ktor-client/ktor-client-core/posix/src/io/ktor/client/engine/Loader.kt b/ktor-client/ktor-client-core/nonJvm/src/io/ktor/client/engine/Loader.kt similarity index 100% rename from ktor-client/ktor-client-core/posix/src/io/ktor/client/engine/Loader.kt rename to ktor-client/ktor-client-core/nonJvm/src/io/ktor/client/engine/Loader.kt diff --git a/ktor-client/ktor-client-core/posix/src/io/ktor/client/HttpClient.kt b/ktor-client/ktor-client-core/posix/src/io/ktor/client/HttpClient.kt index 58c90f0c010..0695c91c5ce 100644 --- a/ktor-client/ktor-client-core/posix/src/io/ktor/client/HttpClient.kt +++ b/ktor-client/ktor-client-core/posix/src/io/ktor/client/HttpClient.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client @@ -13,10 +13,13 @@ import io.ktor.utils.io.* * The [HttpClientEngine] is selected from the dependencies. * https://ktor.io/docs/http-client-engines.html */ -@OptIn(InternalAPI::class) @KtorDsl public actual fun HttpClient( block: HttpClientConfig<*>.() -> Unit -): HttpClient = engines.firstOrNull()?.let { HttpClient(it, block) } ?: error( - "Failed to find HttpClientEngineContainer. Consider adding [HttpClientEngine] implementation in dependencies." +): HttpClient = HttpClient(FACTORY, block) + +@OptIn(InternalAPI::class) +private val FACTORY = engines.firstOrNull() ?: error( + "Failed to find HTTP client engine implementation: consider adding client engine dependency. " + + "See https://ktor.io/docs/http-client-engines.html" ) diff --git a/ktor-client/ktor-client-core/wasmJs/src/io/ktor/client/engine/js/Js.kt b/ktor-client/ktor-client-core/wasmJs/src/io/ktor/client/engine/js/Js.kt index 82ff4ed746a..c134605f869 100644 --- a/ktor-client/ktor-client-core/wasmJs/src/io/ktor/client/engine/js/Js.kt +++ b/ktor-client/ktor-client-core/wasmJs/src/io/ktor/client/engine/js/Js.kt @@ -1,11 +1,12 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.engine.js import io.ktor.client.engine.* -import io.ktor.client.utils.makeJsObject +import io.ktor.client.utils.* +import io.ktor.utils.io.* /** * A JavaScript client engine that uses the fetch API to execute requests. @@ -21,7 +22,7 @@ import io.ktor.client.utils.makeJsObject * * You can learn more about client engines from [Engines](https://ktor.io/docs/http-client-engines.html). */ -public actual object Js : HttpClientEngineFactory { +public actual data object Js : HttpClientEngineFactory { override fun create(block: JsClientEngineConfig.() -> Unit): HttpClientEngine = JsClientEngine(JsClientEngineConfig().apply(block)) } @@ -46,3 +47,8 @@ public actual open class JsClientEngineConfig : HttpClientEngineConfig() { */ public var nodeOptions: JsAny = makeJsObject() } + +@OptIn(InternalAPI::class, ExperimentalStdlibApi::class) +@Suppress("DEPRECATION") +@EagerInitialization +private val initHook: Unit = engines.append(Js) diff --git a/ktor-client/ktor-client-curl/build.gradle.kts b/ktor-client/ktor-client-curl/build.gradle.kts index 1aa87437023..9122715068e 100644 --- a/ktor-client/ktor-client-curl/build.gradle.kts +++ b/ktor-client/ktor-client-curl/build.gradle.kts @@ -1,40 +1,20 @@ -apply() +import org.jetbrains.kotlin.gradle.plugin.mpp.* -val paths = listOf( - "/opt/homebrew/opt/curl/include/", - "/opt/local/include/", - "/usr/local/include/", - "/usr/include/", - "/usr/local/opt/curl/include/", - "/usr/include/x86_64-linux-gnu/", - "/usr/local/Cellar/curl/7.62.0/include/", - "/usr/local/Cellar/curl/7.63.0/include/", - "/usr/local/Cellar/curl/7.65.3/include/", - "/usr/local/Cellar/curl/7.66.0/include/", - "/usr/local/Cellar/curl/7.80.0/include/", - "/usr/local/Cellar/curl/7.80.0_1/include/", - "/usr/local/Cellar/curl/7.81.0/include/", - "desktop/interop/mingwX64/include/", -) +apply() plugins { id("kotlinx-serialization") } kotlin { - createCInterop("libcurl", listOf("macosX64", "linuxX64", "mingwX64")) { - definitionFile = File(projectDir, "desktop/interop/libcurl.def") - includeDirs.headerFilterOnly(paths) - } - - createCInterop("libcurl", listOf("macosArm64")) { - definitionFile = File(projectDir, "desktop/interop/libcurl_arm64.def") - includeDirs.headerFilterOnly(paths) - } - - createCInterop("libcurl", listOf("linuxArm64")) { - definitionFile = File(projectDir, "desktop/interop/libcurl_linux_arm64.def") - includeDirs.headerFilterOnly(listOf("desktop/interop/linuxArm64/include/")) + targets.withType().configureEach { + compilations.named("main") { + cinterops.create("libcurl") { + definitionFile = file("desktop/interop/libcurl.def") + includeDirs(file("desktop/interop/include")) + extraOpts("-libraryPath", file("desktop/interop/lib/${target.name}")) + } + } } sourceSets { diff --git a/ktor-client/ktor-client-curl/desktop/interop/linuxArm64/include/curl/curl.h b/ktor-client/ktor-client-curl/desktop/interop/include/curl/curl.h old mode 100755 new mode 100644 similarity index 93% rename from ktor-client/ktor-client-curl/desktop/interop/linuxArm64/include/curl/curl.h rename to ktor-client/ktor-client-curl/desktop/interop/include/curl/curl.h index 8cc0b6ffe33..c4fae4d4463 --- a/ktor-client/ktor-client-curl/desktop/interop/linuxArm64/include/curl/curl.h +++ b/ktor-client/ktor-client-curl/desktop/interop/include/curl/curl.h @@ -34,50 +34,50 @@ #endif /* Compile-time deprecation macros. */ -#if defined(__GNUC__) && (__GNUC__ >= 6) && \ +#if (defined(__GNUC__) && \ + ((__GNUC__ > 12) || ((__GNUC__ == 12) && (__GNUC_MINOR__ >= 1 ))) || \ + defined(__IAR_SYSTEMS_ICC__)) && \ !defined(__INTEL_COMPILER) && \ !defined(CURL_DISABLE_DEPRECATION) && !defined(BUILDING_LIBCURL) -#define CURL_DEPRECATED(version, message) \ - __attribute__((deprecated("since " # version ". " message))) +#define CURL_DEPRECATED(version, message) \ + __attribute__((deprecated("since " # version ". " message))) +#if defined(__IAR_SYSTEMS_ICC__) +#define CURL_IGNORE_DEPRECATION(statements) \ + _Pragma("diag_suppress=Pe1444") \ + statements \ + _Pragma("diag_default=Pe1444") +#else #define CURL_IGNORE_DEPRECATION(statements) \ _Pragma("GCC diagnostic push") \ _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") \ statements \ _Pragma("GCC diagnostic pop") +#endif #else #define CURL_DEPRECATED(version, message) #define CURL_IGNORE_DEPRECATION(statements) statements #endif #include "curlver.h" /* libcurl version defines */ -#include "system.h" /* determine things run-time */ - -/* - * Define CURL_WIN32 when build target is Win32 API - */ - -#if (defined(_WIN32) || defined(__WIN32__) || defined(WIN32)) && \ - !defined(__SYMBIAN32__) -#define CURL_WIN32 -#endif +#include "system.h" /* determine things runtime */ #include #include -#if (defined(__FreeBSD__) && (__FreeBSD__ >= 2)) || defined(__MidnightBSD__) +#if defined(__FreeBSD__) || defined(__MidnightBSD__) /* Needed for __FreeBSD_version or __MidnightBSD_version symbol definition */ -#include +#include #endif /* The include stuff here below is mainly for time_t! */ #include #include -#if defined(CURL_WIN32) && !defined(_WIN32_WCE) && !defined(__CYGWIN__) +#if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(__CYGWIN__) #if !(defined(_WINSOCKAPI_) || defined(_WINSOCK_H) || \ defined(__LWIP_OPT_H__) || defined(LWIP_HDR_OPT_H)) -/* The check above prevents the winsock2 inclusion if winsock.h already was - included, since they can't co-exist without problems */ +/* The check above prevents the winsock2.h inclusion if winsock.h already was + included, since they cannot co-exist without problems */ #include #include #endif @@ -87,20 +87,20 @@ libc5-based Linux systems. Only include it on systems that are known to require it! */ #if defined(_AIX) || defined(__NOVELL_LIBC__) || defined(__NetBSD__) || \ - defined(__minix) || defined(__SYMBIAN32__) || defined(__INTEGRITY) || \ + defined(__minix) || defined(__INTEGRITY) || \ defined(ANDROID) || defined(__ANDROID__) || defined(__OpenBSD__) || \ defined(__CYGWIN__) || defined(AMIGA) || defined(__NuttX__) || \ (defined(__FreeBSD_version) && (__FreeBSD_version < 800000)) || \ (defined(__MidnightBSD_version) && (__MidnightBSD_version < 100000)) || \ - defined(__sun__) || defined(__serenity__) + defined(__sun__) || defined(__serenity__) || defined(__vxworks__) #include #endif -#if !defined(CURL_WIN32) && !defined(_WIN32_WCE) +#if !defined(_WIN32) && !defined(_WIN32_WCE) #include #endif -#if !defined(CURL_WIN32) +#if !defined(_WIN32) #include #endif @@ -127,7 +127,7 @@ typedef void CURLSH; #ifdef CURL_STATICLIB # define CURL_EXTERN -#elif defined(CURL_WIN32) || defined(__SYMBIAN32__) || \ +#elif defined(_WIN32) || \ (__has_declspec_attribute(dllexport) && \ __has_declspec_attribute(dllimport)) # if defined(BUILDING_LIBCURL) @@ -143,7 +143,7 @@ typedef void CURLSH; #ifndef curl_socket_typedef /* socket typedef */ -#if defined(CURL_WIN32) && !defined(__LWIP_OPT_H__) && !defined(LWIP_HDR_OPT_H) +#if defined(_WIN32) && !defined(__LWIP_OPT_H__) && !defined(LWIP_HDR_OPT_H) typedef SOCKET curl_socket_t; #define CURL_SOCKET_BAD INVALID_SOCKET #else @@ -158,9 +158,9 @@ typedef enum { CURLSSLBACKEND_NONE = 0, CURLSSLBACKEND_OPENSSL = 1, CURLSSLBACKEND_GNUTLS = 2, - CURLSSLBACKEND_NSS = 3, + CURLSSLBACKEND_NSS CURL_DEPRECATED(8.3.0, "") = 3, CURLSSLBACKEND_OBSOLETE4 = 4, /* Was QSOSSL. */ - CURLSSLBACKEND_GSKIT = 5, + CURLSSLBACKEND_GSKIT CURL_DEPRECATED(8.3.0, "") = 5, CURLSSLBACKEND_POLARSSL CURL_DEPRECATED(7.69.0, "") = 6, CURLSSLBACKEND_WOLFSSL = 7, CURLSSLBACKEND_SCHANNEL = 8, @@ -173,8 +173,9 @@ typedef enum { } curl_sslbackend; /* aliases for library clones and renames */ -#define CURLSSLBACKEND_LIBRESSL CURLSSLBACKEND_OPENSSL +#define CURLSSLBACKEND_AWSLC CURLSSLBACKEND_OPENSSL #define CURLSSLBACKEND_BORINGSSL CURLSSLBACKEND_OPENSSL +#define CURLSSLBACKEND_LIBRESSL CURLSSLBACKEND_OPENSSL /* deprecated names: */ #define CURLSSLBACKEND_CYASSL CURLSSLBACKEND_WOLFSSL @@ -196,9 +197,9 @@ struct curl_httppost { files */ long flags; /* as defined below */ -/* specified content is a file name */ +/* specified content is a filename */ #define CURL_HTTPPOST_FILENAME (1<<0) -/* specified content is a file name */ +/* specified content is a filename */ #define CURL_HTTPPOST_READFILE (1<<1) /* name is only stored pointer do not free in formfree */ #define CURL_HTTPPOST_PTRNAME (1<<2) @@ -214,8 +215,8 @@ struct curl_httppost { /* use size in 'contentlen', added in 7.46.0 */ #define CURL_HTTPPOST_LARGE (1<<7) - char *showfilename; /* The file name to show. If not set, the - actual file name will be used (if this + char *showfilename; /* The filename to show. If not set, the + actual filename will be used (if this is a file part) */ void *userp; /* custom pointer used for HTTPPOST_CALLBACK posts */ @@ -330,7 +331,8 @@ struct curl_fileinfo { unsigned int flags; - /* used internally */ + /* These are libcurl private struct fields. Previously used by libcurl, so + they must never be interfered with. */ char *b_data; size_t b_size; size_t b_used; @@ -356,13 +358,13 @@ typedef long (*curl_chunk_bgn_callback)(const void *transfer_info, download of an individual chunk finished. Note! After this callback was set then it have to be called FOR ALL chunks. Even if downloading of this chunk was skipped in CHUNK_BGN_FUNC. - This is the reason why we don't need "transfer_info" parameter in this + This is the reason why we do not need "transfer_info" parameter in this callback and we are not interested in "remains" parameter too. */ typedef long (*curl_chunk_end_callback)(void *ptr); /* return codes for FNMATCHFUNCTION */ #define CURL_FNMATCHFUNC_MATCH 0 /* string corresponds to the pattern */ -#define CURL_FNMATCHFUNC_NOMATCH 1 /* pattern doesn't match the string */ +#define CURL_FNMATCHFUNC_NOMATCH 1 /* pattern does not match the string */ #define CURL_FNMATCHFUNC_FAIL 2 /* an error occurred */ /* callback type for wildcard downloading pattern matching. If the @@ -374,7 +376,7 @@ typedef int (*curl_fnmatch_callback)(void *ptr, /* These are the return codes for the seek callbacks */ #define CURL_SEEKFUNC_OK 0 #define CURL_SEEKFUNC_FAIL 1 /* fail the entire transfer */ -#define CURL_SEEKFUNC_CANTSEEK 2 /* tell libcurl seeking can't be done, so +#define CURL_SEEKFUNC_CANTSEEK 2 /* tell libcurl seeking cannot be done, so libcurl might try other means instead */ typedef int (*curl_seek_callback)(void *instream, curl_off_t offset, @@ -457,7 +459,7 @@ typedef curlioerr (*curl_ioctl_callback)(CURL *handle, #ifndef CURL_DID_MEMORY_FUNC_TYPEDEFS /* * The following typedef's are signatures of malloc, free, realloc, strdup and - * calloc respectively. Function pointers of these types can be passed to the + * calloc respectively. Function pointers of these types can be passed to the * curl_global_init_mem() function to set user defined memory management * callback routines. */ @@ -545,17 +547,17 @@ typedef enum { CURLE_WRITE_ERROR, /* 23 */ CURLE_OBSOLETE24, /* 24 - NOT USED */ CURLE_UPLOAD_FAILED, /* 25 - failed upload "command" */ - CURLE_READ_ERROR, /* 26 - couldn't open/read from file */ + CURLE_READ_ERROR, /* 26 - could not open/read from file */ CURLE_OUT_OF_MEMORY, /* 27 */ CURLE_OPERATION_TIMEDOUT, /* 28 - the timeout time was reached */ CURLE_OBSOLETE29, /* 29 - NOT USED */ CURLE_FTP_PORT_FAILED, /* 30 - FTP PORT operation failed */ CURLE_FTP_COULDNT_USE_REST, /* 31 - the REST command failed */ CURLE_OBSOLETE32, /* 32 - NOT USED */ - CURLE_RANGE_ERROR, /* 33 - RANGE "command" didn't work */ + CURLE_RANGE_ERROR, /* 33 - RANGE "command" did not work */ CURLE_HTTP_POST_ERROR, /* 34 */ CURLE_SSL_CONNECT_ERROR, /* 35 - wrong when connecting with SSL */ - CURLE_BAD_DOWNLOAD_RESUME, /* 36 - couldn't resume download */ + CURLE_BAD_DOWNLOAD_RESUME, /* 36 - could not resume download */ CURLE_FILE_COULDNT_READ_FILE, /* 37 */ CURLE_LDAP_CANNOT_BIND, /* 38 */ CURLE_LDAP_SEARCH_FAILED, /* 39 */ @@ -579,9 +581,9 @@ typedef enum { CURLE_RECV_ERROR, /* 56 - failure in receiving network data */ CURLE_OBSOLETE57, /* 57 - NOT IN USE */ CURLE_SSL_CERTPROBLEM, /* 58 - problem with the local certificate */ - CURLE_SSL_CIPHER, /* 59 - couldn't use specified cipher */ + CURLE_SSL_CIPHER, /* 59 - could not use specified cipher */ CURLE_PEER_FAILED_VERIFICATION, /* 60 - peer's certificate or fingerprint - wasn't verified fine */ + was not verified fine */ CURLE_BAD_CONTENT_ENCODING, /* 61 - Unrecognized/bad encoding */ CURLE_OBSOLETE62, /* 62 - NOT IN USE since 7.82.0 */ CURLE_FILESIZE_EXCEEDED, /* 63 - Maximum file size exceeded */ @@ -610,7 +612,7 @@ typedef enum { CURLE_SSL_SHUTDOWN_FAILED, /* 80 - Failed to shut down the SSL connection */ CURLE_AGAIN, /* 81 - socket is not ready for send/recv, - wait till it's ready and try again (Added + wait till it is ready and try again (Added in 7.18.2) */ CURLE_SSL_CRL_BADFILE, /* 82 - could not load CRL file, missing or wrong format (Added in 7.19.0) */ @@ -637,16 +639,18 @@ typedef enum { CURLE_PROXY, /* 97 - proxy handshake error */ CURLE_SSL_CLIENTCERT, /* 98 - client-side certificate required */ CURLE_UNRECOVERABLE_POLL, /* 99 - poll/select returned fatal error */ + CURLE_TOO_LARGE, /* 100 - a value/data met its maximum */ + CURLE_ECH_REQUIRED, /* 101 - ECH tried but failed */ CURL_LAST /* never use! */ } CURLcode; #ifndef CURL_NO_OLDIES /* define this to test if your app builds with all the obsolete stuff removed! */ -/* Previously obsolete error code re-used in 7.38.0 */ +/* Previously obsolete error code reused in 7.38.0 */ #define CURLE_OBSOLETE16 CURLE_HTTP2 -/* Previously obsolete error codes re-used in 7.24.0 */ +/* Previously obsolete error codes reused in 7.24.0 */ #define CURLE_OBSOLETE10 CURLE_FTP_ACCEPT_FAILED #define CURLE_OBSOLETE12 CURLE_FTP_ACCEPT_TIMEOUT @@ -717,6 +721,8 @@ typedef enum { with them. */ #define CURLOPT_WRITEINFO CURLOPT_OBSOLETE40 #define CURLOPT_CLOSEPOLICY CURLOPT_OBSOLETE72 +#define CURLOPT_OBSOLETE72 9999 +#define CURLOPT_OBSOLETE40 9999 #endif /* !CURL_NO_OLDIES */ @@ -767,7 +773,7 @@ typedef CURLcode (*curl_conv_callback)(char *buffer, size_t length); typedef CURLcode (*curl_ssl_ctx_callback)(CURL *curl, /* easy handle */ void *ssl_ctx, /* actually an OpenSSL - or WolfSSL SSL_CTX, + or wolfSSL SSL_CTX, or an mbedTLS mbedtls_ssl_config */ void *userptr); @@ -777,13 +783,14 @@ typedef enum { CONNECT HTTP/1.1 */ CURLPROXY_HTTP_1_0 = 1, /* added in 7.19.4, force to use CONNECT HTTP/1.0 */ - CURLPROXY_HTTPS = 2, /* added in 7.52.0 */ + CURLPROXY_HTTPS = 2, /* HTTPS but stick to HTTP/1 added in 7.52.0 */ + CURLPROXY_HTTPS2 = 3, /* HTTPS and attempt HTTP/2 added in 8.2.0 */ CURLPROXY_SOCKS4 = 4, /* support added in 7.15.2, enum existed already in 7.10 */ CURLPROXY_SOCKS5 = 5, /* added in 7.10 */ CURLPROXY_SOCKS4A = 6, /* added in 7.18.0 */ CURLPROXY_SOCKS5_HOSTNAME = 7 /* Use the SOCKS5 protocol but pass along the - host name rather than the IP address. added + hostname rather than the IP address. added in 7.18.0 */ } curl_proxytype; /* this enum was added in 7.10 */ @@ -815,7 +822,10 @@ typedef enum { #define CURLAUTH_GSSAPI CURLAUTH_NEGOTIATE #define CURLAUTH_NTLM (((unsigned long)1)<<3) #define CURLAUTH_DIGEST_IE (((unsigned long)1)<<4) +#ifndef CURL_NO_OLDIES + /* functionality removed since 8.8.0 */ #define CURLAUTH_NTLM_WB (((unsigned long)1)<<5) +#endif #define CURLAUTH_BEARER (((unsigned long)1)<<6) #define CURLAUTH_AWS_SIGV4 (((unsigned long)1)<<7) #define CURLAUTH_ONLY (((unsigned long)1)<<31) @@ -860,7 +870,7 @@ enum curl_khstat { CURLKHSTAT_FINE_ADD_TO_FILE, CURLKHSTAT_FINE, CURLKHSTAT_REJECT, /* reject the connection, return an error */ - CURLKHSTAT_DEFER, /* do not accept it, but we can't answer right now. + CURLKHSTAT_DEFER, /* do not accept it, but we cannot answer right now. Causes a CURLE_PEER_FAILED_VERIFICATION error but the connection will be left intact etc */ CURLKHSTAT_FINE_REPLACE, /* accept and replace the wrong key */ @@ -1080,7 +1090,7 @@ typedef CURLSTScode (*curl_hstswrite_callback)(CURL *easy, #define CURLOPT(na,t,nu) na = t + nu #define CURLOPTDEPRECATED(na,t,nu,v,m) na CURL_DEPRECATED(v,m) = t + nu -/* CURLOPT aliases that make no run-time difference */ +/* CURLOPT aliases that make no runtime difference */ /* 'char *' argument to a string with a trailing zero */ #define CURLOPTTYPE_STRINGPOINT CURLOPTTYPE_OBJECTPOINT @@ -1147,7 +1157,7 @@ typedef enum { * * For large file support, there is also a _LARGE version of the key * which takes an off_t type, allowing platforms with larger off_t - * sizes to handle larger files. See below for INFILESIZE_LARGE. + * sizes to handle larger files. See below for INFILESIZE_LARGE. */ CURLOPT(CURLOPT_INFILESIZE, CURLOPTTYPE_LONG, 14), @@ -1180,7 +1190,7 @@ typedef enum { * * Note there is also a _LARGE version of this key which uses * off_t types, allowing for large file offsets on platforms which - * use larger-than-32-bit off_t's. Look below for RESUME_FROM_LARGE. + * use larger-than-32-bit off_t's. Look below for RESUME_FROM_LARGE. */ CURLOPT(CURLOPT_RESUME_FROM, CURLOPTTYPE_LONG, 21), @@ -1242,8 +1252,7 @@ typedef enum { /* send linked-list of post-transfer QUOTE commands */ CURLOPT(CURLOPT_POSTQUOTE, CURLOPTTYPE_SLISTPOINT, 39), - /* OBSOLETE, do not use! */ - CURLOPT(CURLOPT_OBSOLETE40, CURLOPTTYPE_OBJECTPOINT, 40), + /* 40 is not used */ /* talk a lot */ CURLOPT(CURLOPT_VERBOSE, CURLOPTTYPE_LONG, 41), @@ -1316,9 +1325,9 @@ typedef enum { /* Set the interface string to use as outgoing network interface */ CURLOPT(CURLOPT_INTERFACE, CURLOPTTYPE_STRINGPOINT, 62), - /* Set the krb4/5 security level, this also enables krb4/5 awareness. This - * is a string, 'clear', 'safe', 'confidential' or 'private'. If the string - * is set but doesn't match one of these, 'private' will be used. */ + /* Set the krb4/5 security level, this also enables krb4/5 awareness. This + * is a string, 'clear', 'safe', 'confidential' or 'private'. If the string + * is set but does not match one of these, 'private' will be used. */ CURLOPT(CURLOPT_KRBLEVEL, CURLOPTTYPE_STRINGPOINT, 63), /* Set if we should verify the peer in ssl handshake, set 1 to verify. */ @@ -1344,22 +1353,20 @@ typedef enum { /* Max amount of cached alive connections */ CURLOPT(CURLOPT_MAXCONNECTS, CURLOPTTYPE_LONG, 71), - /* OBSOLETE, do not use! */ - CURLOPT(CURLOPT_OBSOLETE72, CURLOPTTYPE_LONG, 72), - + /* 72 = OBSOLETE */ /* 73 = OBSOLETE */ /* Set to explicitly use a new connection for the upcoming transfer. - Do not use this unless you're absolutely sure of this, as it makes the + Do not use this unless you are absolutely sure of this, as it makes the operation slower and is less friendly for the network. */ CURLOPT(CURLOPT_FRESH_CONNECT, CURLOPTTYPE_LONG, 74), - /* Set to explicitly forbid the upcoming transfer's connection to be re-used - when done. Do not use this unless you're absolutely sure of this, as it + /* Set to explicitly forbid the upcoming transfer's connection to be reused + when done. Do not use this unless you are absolutely sure of this, as it makes the operation slower and is less friendly for the network. */ CURLOPT(CURLOPT_FORBID_REUSE, CURLOPTTYPE_LONG, 75), - /* Set to a file name that contains random data for libcurl to use to + /* Set to a filename that contains random data for libcurl to use to seed the random engine when doing SSL connects. */ CURLOPTDEPRECATED(CURLOPT_RANDOM_FILE, CURLOPTTYPE_STRINGPOINT, 76, 7.84.0, "Serves no purpose anymore"), @@ -1386,11 +1393,11 @@ typedef enum { * provided hostname. */ CURLOPT(CURLOPT_SSL_VERIFYHOST, CURLOPTTYPE_LONG, 81), - /* Specify which file name to write all known cookies in after completed - operation. Set file name to "-" (dash) to make it go to stdout. */ + /* Specify which filename to write all known cookies in after completed + operation. Set filename to "-" (dash) to make it go to stdout. */ CURLOPT(CURLOPT_COOKIEJAR, CURLOPTTYPE_STRINGPOINT, 82), - /* Specify which SSL ciphers to use */ + /* Specify which TLS 1.2 (1.1, 1.0) ciphers to use */ CURLOPT(CURLOPT_SSL_CIPHER_LIST, CURLOPTTYPE_STRINGPOINT, 83), /* Specify which HTTP version to use! This must be set to one of the @@ -1486,7 +1493,7 @@ typedef enum { CURLOPT(CURLOPT_HTTPAUTH, CURLOPTTYPE_VALUES, 107), /* Set the ssl context callback function, currently only for OpenSSL or - WolfSSL ssl_ctx, or mbedTLS mbedtls_ssl_config in the second argument. + wolfSSL ssl_ctx, or mbedTLS mbedtls_ssl_config in the second argument. The function must match the curl_ssl_ctx_callback prototype. */ CURLOPT(CURLOPT_SSL_CTX_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 108), @@ -1506,7 +1513,7 @@ typedef enum { CURLOPT(CURLOPT_PROXYAUTH, CURLOPTTYPE_VALUES, 111), /* Option that changes the timeout, in seconds, associated with getting a - response. This is different from transfer timeout time and essentially + response. This is different from transfer timeout time and essentially places a demand on the server to acknowledge commands in a timely manner. For FTP, SMTP, IMAP and POP3. */ CURLOPT(CURLOPT_SERVER_RESPONSE_TIMEOUT, CURLOPTTYPE_LONG, 112), @@ -1520,7 +1527,7 @@ typedef enum { an HTTP or FTP server. Note there is also _LARGE version which adds large file support for - platforms which have larger off_t sizes. See MAXFILESIZE_LARGE below. */ + platforms which have larger off_t sizes. See MAXFILESIZE_LARGE below. */ CURLOPT(CURLOPT_MAXFILESIZE, CURLOPTTYPE_LONG, 114), /* See the comment for INFILESIZE above, but in short, specifies @@ -1528,17 +1535,17 @@ typedef enum { */ CURLOPT(CURLOPT_INFILESIZE_LARGE, CURLOPTTYPE_OFF_T, 115), - /* Sets the continuation offset. There is also a CURLOPTTYPE_LONG version + /* Sets the continuation offset. There is also a CURLOPTTYPE_LONG version * of this; look above for RESUME_FROM. */ CURLOPT(CURLOPT_RESUME_FROM_LARGE, CURLOPTTYPE_OFF_T, 116), /* Sets the maximum size of data that will be downloaded from - * an HTTP or FTP server. See MAXFILESIZE above for the LONG version. + * an HTTP or FTP server. See MAXFILESIZE above for the LONG version. */ CURLOPT(CURLOPT_MAXFILESIZE_LARGE, CURLOPTTYPE_OFF_T, 117), - /* Set this option to the file name of your .netrc file you want libcurl + /* Set this option to the filename of your .netrc file you want libcurl to parse (using the CURLOPT_NETRC option). If not set, libcurl will do a poor attempt to find the user's home directory and check for a .netrc file in there. */ @@ -1648,7 +1655,7 @@ typedef enum { CURLOPT(CURLOPT_SOCKOPTFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 148), CURLOPT(CURLOPT_SOCKOPTDATA, CURLOPTTYPE_CBPOINT, 149), - /* set to 0 to disable session ID re-use for this transfer, default is + /* set to 0 to disable session ID reuse for this transfer, default is enabled (== 1) */ CURLOPT(CURLOPT_SSL_SESSIONID_CACHE, CURLOPTTYPE_LONG, 150), @@ -1685,7 +1692,7 @@ typedef enum { /* Callback function for opening socket (instead of socket(2)). Optionally, callback is able change the address or refuse to connect returning - CURL_SOCKET_BAD. The callback should have type + CURL_SOCKET_BAD. The callback should have type curl_opensocket_callback */ CURLOPT(CURLOPT_OPENSOCKETFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 163), CURLOPT(CURLOPT_OPENSOCKETDATA, CURLOPTTYPE_CBPOINT, 164), @@ -1755,7 +1762,7 @@ typedef enum { CURLOPTDEPRECATED(CURLOPT_REDIR_PROTOCOLS, CURLOPTTYPE_LONG, 182, 7.85.0, "Use CURLOPT_REDIR_PROTOCOLS_STR"), - /* set the SSH knownhost file name to use */ + /* set the SSH knownhost filename to use */ CURLOPT(CURLOPT_SSH_KNOWNHOSTS, CURLOPTTYPE_STRINGPOINT, 183), /* set the SSH host key callback, must point to a curl_sshkeycallback @@ -1836,7 +1843,7 @@ typedef enum { future libcurl release. libcurl will ask for the compressed methods it knows of, and if that - isn't any, it will not ask for transfer-encoding at all even if this + is not any, it will not ask for transfer-encoding at all even if this option is set to 1. */ @@ -1850,7 +1857,8 @@ typedef enum { /* allow GSSAPI credential delegation */ CURLOPT(CURLOPT_GSSAPI_DELEGATION, CURLOPTTYPE_VALUES, 210), - /* Set the name servers to use for DNS resolution */ + /* Set the name servers to use for DNS resolution. + * Only supported by the c-ares DNS backend */ CURLOPT(CURLOPT_DNS_SERVERS, CURLOPTTYPE_STRINGPOINT, 211), /* Time-out accept operations (currently for FTP only) after this amount @@ -1937,7 +1945,7 @@ typedef enum { /* Service Name */ CURLOPT(CURLOPT_SERVICE_NAME, CURLOPTTYPE_STRINGPOINT, 236), - /* Wait/don't wait for pipe/mutex to clarify */ + /* Wait/do not wait for pipe/mutex to clarify */ CURLOPT(CURLOPT_PIPEWAIT, CURLOPTTYPE_LONG, 237), /* Set the protocol used when curl is given a URL without a protocol */ @@ -2013,7 +2021,7 @@ typedef enum { /* password for the SSL private key for proxy */ CURLOPT(CURLOPT_PROXY_KEYPASSWD, CURLOPTTYPE_STRINGPOINT, 258), - /* Specify which SSL ciphers to use for proxy */ + /* Specify which TLS 1.2 (1.1, 1.0) ciphers to use for proxy */ CURLOPT(CURLOPT_PROXY_SSL_CIPHER_LIST, CURLOPTTYPE_STRINGPOINT, 259), /* CRL file for proxy */ @@ -2098,7 +2106,7 @@ typedef enum { /* alt-svc control bitmask */ CURLOPT(CURLOPT_ALTSVC_CTRL, CURLOPTTYPE_LONG, 286), - /* alt-svc cache file name to possibly read from/write to */ + /* alt-svc cache filename to possibly read from/write to */ CURLOPT(CURLOPT_ALTSVC, CURLOPTTYPE_STRINGPOINT, 287), /* maximum age (idle time) of a connection to consider it for reuse @@ -2109,7 +2117,7 @@ typedef enum { CURLOPT(CURLOPT_SASL_AUTHZID, CURLOPTTYPE_STRINGPOINT, 289), /* allow RCPT TO command to fail for some recipients */ - CURLOPT(CURLOPT_MAIL_RCPT_ALLLOWFAILS, CURLOPTTYPE_LONG, 290), + CURLOPT(CURLOPT_MAIL_RCPT_ALLOWFAILS, CURLOPTTYPE_LONG, 290), /* the private SSL-certificate as a "blob" */ CURLOPT(CURLOPT_SSLCERT_BLOB, CURLOPTTYPE_BLOB, 291), @@ -2124,13 +2132,13 @@ typedef enum { /* the EC curves requested by the TLS client (RFC 8422, 5.1); * OpenSSL support via 'set_groups'/'set_curves': - * https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set1_groups.html + * https://docs.openssl.org/master/man3/SSL_CTX_set1_curves/ */ CURLOPT(CURLOPT_SSL_EC_CURVES, CURLOPTTYPE_STRINGPOINT, 298), /* HSTS bitmask */ CURLOPT(CURLOPT_HSTS_CTRL, CURLOPTTYPE_LONG, 299), - /* HSTS file name */ + /* HSTS filename */ CURLOPT(CURLOPT_HSTS, CURLOPTTYPE_STRINGPOINT, 300), /* HSTS read callback */ @@ -2194,7 +2202,7 @@ typedef enum { /* specify which protocols that libcurl is allowed to follow directs to */ CURLOPT(CURLOPT_REDIR_PROTOCOLS_STR, CURLOPTTYPE_STRINGPOINT, 319), - /* websockets options */ + /* WebSockets options */ CURLOPT(CURLOPT_WS_OPTIONS, CURLOPTTYPE_LONG, 320), /* CA cache timeout */ @@ -2203,6 +2211,18 @@ typedef enum { /* Can leak things, gonna exit() soon */ CURLOPT(CURLOPT_QUICK_EXIT, CURLOPTTYPE_LONG, 322), + /* set a specific client IP for HAProxy PROXY protocol header? */ + CURLOPT(CURLOPT_HAPROXY_CLIENT_IP, CURLOPTTYPE_STRINGPOINT, 323), + + /* millisecond version */ + CURLOPT(CURLOPT_SERVER_RESPONSE_TIMEOUT_MS, CURLOPTTYPE_LONG, 324), + + /* set ECH configuration */ + CURLOPT(CURLOPT_ECH, CURLOPTTYPE_STRINGPOINT, 325), + + /* maximum number of keepalive probes (Linux, *BSD, macOS, etc.) */ + CURLOPT(CURLOPT_TCP_KEEPCNT, CURLOPTTYPE_LONG, 326), + CURLOPT_LASTENTRY /* the last unused */ } CURLoption; @@ -2231,6 +2251,9 @@ typedef enum { /* */ #define CURLOPT_FTP_RESPONSE_TIMEOUT CURLOPT_SERVER_RESPONSE_TIMEOUT +/* Added in 8.2.0 */ +#define CURLOPT_MAIL_RCPT_ALLLOWFAILS CURLOPT_MAIL_RCPT_ALLOWFAILS + #else /* This is set if CURL_NO_OLDIES is defined at compile-time */ #undef CURLOPT_DNS_USE_GLOBAL_CACHE /* soon obsolete */ @@ -2250,9 +2273,9 @@ typedef enum { /* These enums are for use with the CURLOPT_HTTP_VERSION option. */ enum { - CURL_HTTP_VERSION_NONE, /* setting this means we don't care, and that we'd - like the library to choose the best possible - for us! */ + CURL_HTTP_VERSION_NONE, /* setting this means we do not care, and that we + would like the library to choose the best + possible for us! */ CURL_HTTP_VERSION_1_0, /* please use HTTP 1.0 in the request */ CURL_HTTP_VERSION_1_1, /* please use HTTP 1.1 in the request */ CURL_HTTP_VERSION_2_0, /* please use HTTP 2 in the request */ @@ -2305,30 +2328,26 @@ enum CURL_NETRC_OPTION { CURL_NETRC_LAST }; -enum { - CURL_SSLVERSION_DEFAULT, - CURL_SSLVERSION_TLSv1, /* TLS 1.x */ - CURL_SSLVERSION_SSLv2, - CURL_SSLVERSION_SSLv3, - CURL_SSLVERSION_TLSv1_0, - CURL_SSLVERSION_TLSv1_1, - CURL_SSLVERSION_TLSv1_2, - CURL_SSLVERSION_TLSv1_3, - - CURL_SSLVERSION_LAST /* never use, keep last */ -}; +#define CURL_SSLVERSION_DEFAULT 0 +#define CURL_SSLVERSION_TLSv1 1 /* TLS 1.x */ +#define CURL_SSLVERSION_SSLv2 2 +#define CURL_SSLVERSION_SSLv3 3 +#define CURL_SSLVERSION_TLSv1_0 4 +#define CURL_SSLVERSION_TLSv1_1 5 +#define CURL_SSLVERSION_TLSv1_2 6 +#define CURL_SSLVERSION_TLSv1_3 7 -enum { - CURL_SSLVERSION_MAX_NONE = 0, - CURL_SSLVERSION_MAX_DEFAULT = (CURL_SSLVERSION_TLSv1 << 16), - CURL_SSLVERSION_MAX_TLSv1_0 = (CURL_SSLVERSION_TLSv1_0 << 16), - CURL_SSLVERSION_MAX_TLSv1_1 = (CURL_SSLVERSION_TLSv1_1 << 16), - CURL_SSLVERSION_MAX_TLSv1_2 = (CURL_SSLVERSION_TLSv1_2 << 16), - CURL_SSLVERSION_MAX_TLSv1_3 = (CURL_SSLVERSION_TLSv1_3 << 16), +#define CURL_SSLVERSION_LAST 8 /* never use, keep last */ + +#define CURL_SSLVERSION_MAX_NONE 0 +#define CURL_SSLVERSION_MAX_DEFAULT (CURL_SSLVERSION_TLSv1 << 16) +#define CURL_SSLVERSION_MAX_TLSv1_0 (CURL_SSLVERSION_TLSv1_0 << 16) +#define CURL_SSLVERSION_MAX_TLSv1_1 (CURL_SSLVERSION_TLSv1_1 << 16) +#define CURL_SSLVERSION_MAX_TLSv1_2 (CURL_SSLVERSION_TLSv1_2 << 16) +#define CURL_SSLVERSION_MAX_TLSv1_3 (CURL_SSLVERSION_TLSv1_3 << 16) /* never use, keep last */ - CURL_SSLVERSION_MAX_LAST = (CURL_SSLVERSION_LAST << 16) -}; +#define CURL_SSLVERSION_MAX_LAST (CURL_SSLVERSION_LAST << 16) enum CURL_TLSAUTH { CURL_TLSAUTH_NONE, @@ -2416,7 +2435,7 @@ CURL_EXTERN CURLcode curl_mime_name(curl_mimepart *part, const char *name); * * DESCRIPTION * - * Set mime part remote file name. + * Set mime part remote filename. */ CURL_EXTERN CURLcode curl_mime_filename(curl_mimepart *part, const char *filename); @@ -2625,7 +2644,7 @@ CURL_EXTERN char *curl_getenv(const char *variable); * * DESCRIPTION * - * Returns a static ascii string of the libcurl version. + * Returns a static ASCII string of the libcurl version. */ CURL_EXTERN char *curl_version(void); @@ -2697,10 +2716,10 @@ CURL_EXTERN CURLcode curl_global_init(long flags); * DESCRIPTION * * curl_global_init() or curl_global_init_mem() should be invoked exactly once - * for each application that uses libcurl. This function can be used to + * for each application that uses libcurl. This function can be used to * initialize libcurl and set user defined memory management callback - * functions. Users can implement memory management routines to check for - * memory leaks, check for mis-use of the curl library etc. User registered + * functions. Users can implement memory management routines to check for + * memory leaks, check for mis-use of the curl library etc. User registered * callback routines will be invoked by this library instead of the system * memory management routines like malloc, free etc. */ @@ -2721,6 +2740,20 @@ CURL_EXTERN CURLcode curl_global_init_mem(long flags, */ CURL_EXTERN void curl_global_cleanup(void); +/* + * NAME curl_global_trace() + * + * DESCRIPTION + * + * curl_global_trace() can be invoked at application start to + * configure which components in curl should participate in tracing. + + * This function is thread-safe if CURL_VERSION_THREADSAFE is set in the + * curl_version_info_data.features flag (fetch by curl_version_info()). + + */ +CURL_EXTERN CURLcode curl_global_trace(const char *config); + /* linked-list structure for the CURLOPT_QUOTE option (and other) */ struct curl_slist { char *data; @@ -2800,13 +2833,14 @@ CURL_EXTERN void curl_slist_free_all(struct curl_slist *list); */ CURL_EXTERN time_t curl_getdate(const char *p, const time_t *unused); -/* info about the certificate chain, only for OpenSSL, GnuTLS, Schannel, NSS - and GSKit builds. Asked for with CURLOPT_CERTINFO / CURLINFO_CERTINFO */ +/* info about the certificate chain, for SSL backends that support it. Asked + for with CURLOPT_CERTINFO / CURLINFO_CERTINFO */ struct curl_certinfo { int num_of_certs; /* number of certificates with information */ - struct curl_slist **certinfo; /* for each index in this array, there's a - linked list with textual information in the - format "name: value" */ + struct curl_slist **certinfo; /* for each index in this array, there is a + linked list with textual information for a + certificate in the format "name:content". + eg "Subject:foo", "Issuer:bar", etc. */ }; /* Information about the SSL library used and the respective internal SSL @@ -2914,7 +2948,12 @@ typedef enum { CURLINFO_REFERER = CURLINFO_STRING + 60, CURLINFO_CAINFO = CURLINFO_STRING + 61, CURLINFO_CAPATH = CURLINFO_STRING + 62, - CURLINFO_LASTONE = 62 + CURLINFO_XFER_ID = CURLINFO_OFF_T + 63, + CURLINFO_CONN_ID = CURLINFO_OFF_T + 64, + CURLINFO_QUEUE_TIME_T = CURLINFO_OFF_T + 65, + CURLINFO_USED_PROXY = CURLINFO_LONG + 66, + CURLINFO_POSTTRANSFER_TIME_T = CURLINFO_OFF_T + 67, + CURLINFO_LASTONE = 67 } CURLINFO; /* CURLINFO_RESPONSE_CODE is the new name for the option previously known as @@ -2990,7 +3029,7 @@ typedef enum { } CURLSHcode; typedef enum { - CURLSHOPT_NONE, /* don't use */ + CURLSHOPT_NONE, /* do not use */ CURLSHOPT_SHARE, /* specify a data type to share */ CURLSHOPT_UNSHARE, /* specify which data type to stop sharing */ CURLSHOPT_LOCKFUNC, /* pass in a 'curl_lock_function' pointer */ @@ -3010,17 +3049,18 @@ CURL_EXTERN CURLSHcode curl_share_cleanup(CURLSH *share); */ typedef enum { - CURLVERSION_FIRST, - CURLVERSION_SECOND, - CURLVERSION_THIRD, - CURLVERSION_FOURTH, - CURLVERSION_FIFTH, - CURLVERSION_SIXTH, - CURLVERSION_SEVENTH, - CURLVERSION_EIGHTH, - CURLVERSION_NINTH, - CURLVERSION_TENTH, - CURLVERSION_ELEVENTH, + CURLVERSION_FIRST, /* 7.10 */ + CURLVERSION_SECOND, /* 7.11.1 */ + CURLVERSION_THIRD, /* 7.12.0 */ + CURLVERSION_FOURTH, /* 7.16.1 */ + CURLVERSION_FIFTH, /* 7.57.0 */ + CURLVERSION_SIXTH, /* 7.66.0 */ + CURLVERSION_SEVENTH, /* 7.70.0 */ + CURLVERSION_EIGHTH, /* 7.72.0 */ + CURLVERSION_NINTH, /* 7.75.0 */ + CURLVERSION_TENTH, /* 7.77.0 */ + CURLVERSION_ELEVENTH, /* 7.87.0 */ + CURLVERSION_TWELFTH, /* 8.8.0 */ CURLVERSION_LAST /* never actually use this */ } CURLversion; @@ -3029,7 +3069,7 @@ typedef enum { meant to be a built-in version number for what kind of struct the caller expects. If the struct ever changes, we redefine the NOW to another enum from above. */ -#define CURLVERSION_NOW CURLVERSION_ELEVENTH +#define CURLVERSION_NOW CURLVERSION_TWELFTH struct curl_version_info_data { CURLversion age; /* age of the returned struct */ @@ -3089,6 +3129,9 @@ struct curl_version_info_data { /* These fields were added in CURLVERSION_ELEVENTH */ /* feature_names is terminated by an entry with a NULL feature name */ const char * const *feature_names; + + /* These fields were added in CURLVERSION_TWELFTH */ + const char *rtmp_version; /* human readable string. */ }; typedef struct curl_version_info_data curl_version_info_data; @@ -3129,7 +3172,7 @@ typedef struct curl_version_info_data curl_version_info_data; #define CURL_VERSION_GSASL (1<<29) /* libgsasl is supported */ #define CURL_VERSION_THREADSAFE (1<<30) /* libcurl API is thread-safe */ - /* +/* * NAME curl_version_info() * * DESCRIPTION @@ -3145,7 +3188,7 @@ CURL_EXTERN curl_version_info_data *curl_version_info(CURLversion); * DESCRIPTION * * The curl_easy_strerror function may be used to turn a CURLcode value - * into the equivalent human readable error string. This is useful + * into the equivalent human readable error string. This is useful * for printing meaningful error messages. */ CURL_EXTERN const char *curl_easy_strerror(CURLcode); @@ -3156,7 +3199,7 @@ CURL_EXTERN const char *curl_easy_strerror(CURLcode); * DESCRIPTION * * The curl_share_strerror function may be used to turn a CURLSHcode value - * into the equivalent human readable error string. This is useful + * into the equivalent human readable error string. This is useful * for printing meaningful error messages. */ CURL_EXTERN const char *curl_share_strerror(CURLSHcode); @@ -3193,8 +3236,11 @@ CURL_EXTERN CURLcode curl_easy_pause(CURL *handle, int bitmask); #include "options.h" #include "header.h" #include "websockets.h" +#ifndef CURL_SKIP_INCLUDE_MPRINTF +#include "mprintf.h" +#endif -/* the typechecker doesn't work in C++ (yet) */ +/* the typechecker does not work in C++ (yet) */ #if defined(__GNUC__) && defined(__GNUC_MINOR__) && \ ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) && \ !defined(__cplusplus) && !defined(CURL_DISABLE_TYPECHECK) diff --git a/ktor-client/ktor-client-curl/desktop/interop/linuxArm64/include/curl/curlver.h b/ktor-client/ktor-client-curl/desktop/interop/include/curl/curlver.h old mode 100755 new mode 100644 similarity index 91% rename from ktor-client/ktor-client-curl/desktop/interop/linuxArm64/include/curl/curlver.h rename to ktor-client/ktor-client-curl/desktop/interop/include/curl/curlver.h index d5953712095..45ecdcef748 --- a/ktor-client/ktor-client-curl/desktop/interop/linuxArm64/include/curl/curlver.h +++ b/ktor-client/ktor-client-curl/desktop/interop/include/curl/curlver.h @@ -32,12 +32,12 @@ /* This is the version number of the libcurl package from which this header file origins: */ -#define LIBCURL_VERSION "7.88.1" +#define LIBCURL_VERSION "8.10.1" /* The numeric version number is also available "in parts" by using these defines: */ -#define LIBCURL_VERSION_MAJOR 7 -#define LIBCURL_VERSION_MINOR 88 +#define LIBCURL_VERSION_MAJOR 8 +#define LIBCURL_VERSION_MINOR 10 #define LIBCURL_VERSION_PATCH 1 /* This is the numeric version of the libcurl version number, meant for easier @@ -48,7 +48,7 @@ Where XX, YY and ZZ are the main version, release and patch numbers in hexadecimal (using 8 bits each). All three numbers are always represented - using two digits. 1.2 would appear as "0x010200" while version 9.11.7 + using two digits. 1.2 would appear as "0x010200" while version 9.11.7 appears as "0x090b07". This 6-digit (24 bits) hexadecimal number does not show pre-release number, @@ -59,7 +59,7 @@ CURL_VERSION_BITS() macro since curl's own configure script greps for it and needs it to contain the full number. */ -#define LIBCURL_VERSION_NUM 0x075801 +#define LIBCURL_VERSION_NUM 0x080a01 /* * This is the date and time when the full source package was created. The @@ -70,7 +70,7 @@ * * "2007-11-23" */ -#define LIBCURL_TIMESTAMP "2023-02-20" +#define LIBCURL_TIMESTAMP "2024-09-18" #define CURL_VERSION_BITS(x,y,z) ((x)<<16|(y)<<8|(z)) #define CURL_AT_LEAST_VERSION(x,y,z) \ diff --git a/ktor-client/ktor-client-curl/desktop/interop/linuxArm64/include/curl/easy.h b/ktor-client/ktor-client-curl/desktop/interop/include/curl/easy.h old mode 100755 new mode 100644 similarity index 89% rename from ktor-client/ktor-client-curl/desktop/interop/linuxArm64/include/curl/easy.h rename to ktor-client/ktor-client-curl/desktop/interop/include/curl/easy.h index 394668a8fa7..71b8dd4674e --- a/ktor-client/ktor-client-curl/desktop/interop/linuxArm64/include/curl/easy.h +++ b/ktor-client/ktor-client-curl/desktop/interop/include/curl/easy.h @@ -48,13 +48,13 @@ CURL_EXTERN void curl_easy_cleanup(CURL *curl); * * DESCRIPTION * - * Request internal information from the curl session with this function. The - * third argument MUST be a pointer to a long, a pointer to a char * or a - * pointer to a double (as the documentation describes elsewhere). The data - * pointed to will be filled in accordingly and can be relied upon only if the - * function returns CURLE_OK. This function is intended to get used *AFTER* a - * performed transfer, all results from this function are undefined until the - * transfer is completed. + * Request internal information from the curl session with this function. + * The third argument MUST be pointing to the specific type of the used option + * which is documented in each manpage of the option. The data pointed to + * will be filled in accordingly and can be relied upon only if the function + * returns CURLE_OK. This function is intended to get used *AFTER* a performed + * transfer, all results from this function are undefined until the transfer + * is completed. */ CURL_EXTERN CURLcode curl_easy_getinfo(CURL *curl, CURLINFO info, ...); diff --git a/ktor-client/ktor-client-curl/desktop/interop/linuxArm64/include/curl/header.h b/ktor-client/ktor-client-curl/desktop/interop/include/curl/header.h old mode 100755 new mode 100644 similarity index 100% rename from ktor-client/ktor-client-curl/desktop/interop/linuxArm64/include/curl/header.h rename to ktor-client/ktor-client-curl/desktop/interop/include/curl/header.h diff --git a/ktor-client/ktor-client-curl/desktop/interop/linuxArm64/include/curl/mprintf.h b/ktor-client/ktor-client-curl/desktop/interop/include/curl/mprintf.h old mode 100755 new mode 100644 similarity index 59% rename from ktor-client/ktor-client-curl/desktop/interop/linuxArm64/include/curl/mprintf.h rename to ktor-client/ktor-client-curl/desktop/interop/include/curl/mprintf.h index e652a6520e6..88059c851fb --- a/ktor-client/ktor-client-curl/desktop/interop/linuxArm64/include/curl/mprintf.h +++ b/ktor-client/ktor-client-curl/desktop/interop/include/curl/mprintf.h @@ -32,18 +32,51 @@ extern "C" { #endif -CURL_EXTERN int curl_mprintf(const char *format, ...); -CURL_EXTERN int curl_mfprintf(FILE *fd, const char *format, ...); -CURL_EXTERN int curl_msprintf(char *buffer, const char *format, ...); +#ifndef CURL_TEMP_PRINTF +#if (defined(__GNUC__) || defined(__clang__) || \ + defined(__IAR_SYSTEMS_ICC__)) && \ + defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ + !defined(CURL_NO_FMT_CHECKS) +#if defined(__MINGW32__) && !defined(__clang__) +#if defined(__MINGW_PRINTF_FORMAT) /* mingw-w64 3.0.0+. Needs stdio.h. */ +#define CURL_TEMP_PRINTF(fmt, arg) \ + __attribute__((format(__MINGW_PRINTF_FORMAT, fmt, arg))) +#else +#define CURL_TEMP_PRINTF(fmt, arg) +#endif +#else +#define CURL_TEMP_PRINTF(fmt, arg) \ + __attribute__((format(printf, fmt, arg))) +#endif +#else +#define CURL_TEMP_PRINTF(fmt, arg) +#endif +#endif + +CURL_EXTERN int curl_mprintf(const char *format, ...) + CURL_TEMP_PRINTF(1, 2); +CURL_EXTERN int curl_mfprintf(FILE *fd, const char *format, ...) + CURL_TEMP_PRINTF(2, 3); +CURL_EXTERN int curl_msprintf(char *buffer, const char *format, ...) + CURL_TEMP_PRINTF(2, 3); CURL_EXTERN int curl_msnprintf(char *buffer, size_t maxlength, - const char *format, ...); -CURL_EXTERN int curl_mvprintf(const char *format, va_list args); -CURL_EXTERN int curl_mvfprintf(FILE *fd, const char *format, va_list args); -CURL_EXTERN int curl_mvsprintf(char *buffer, const char *format, va_list args); + const char *format, ...) + CURL_TEMP_PRINTF(3, 4); +CURL_EXTERN int curl_mvprintf(const char *format, va_list args) + CURL_TEMP_PRINTF(1, 0); +CURL_EXTERN int curl_mvfprintf(FILE *fd, const char *format, va_list args) + CURL_TEMP_PRINTF(2, 0); +CURL_EXTERN int curl_mvsprintf(char *buffer, const char *format, va_list args) + CURL_TEMP_PRINTF(2, 0); CURL_EXTERN int curl_mvsnprintf(char *buffer, size_t maxlength, - const char *format, va_list args); -CURL_EXTERN char *curl_maprintf(const char *format, ...); -CURL_EXTERN char *curl_mvaprintf(const char *format, va_list args); + const char *format, va_list args) + CURL_TEMP_PRINTF(3, 0); +CURL_EXTERN char *curl_maprintf(const char *format, ...) + CURL_TEMP_PRINTF(1, 2); +CURL_EXTERN char *curl_mvaprintf(const char *format, va_list args) + CURL_TEMP_PRINTF(1, 0); + +#undef CURL_TEMP_PRINTF #ifdef __cplusplus } /* end of extern "C" */ diff --git a/ktor-client/ktor-client-curl/desktop/interop/linuxArm64/include/curl/multi.h b/ktor-client/ktor-client-curl/desktop/interop/include/curl/multi.h old mode 100755 new mode 100644 similarity index 91% rename from ktor-client/ktor-client-curl/desktop/interop/linuxArm64/include/curl/multi.h rename to ktor-client/ktor-client-curl/desktop/interop/include/curl/multi.h index 30a3d930177..7b6c351ada7 --- a/ktor-client/ktor-client-curl/desktop/interop/linuxArm64/include/curl/multi.h +++ b/ktor-client/ktor-client-curl/desktop/interop/include/curl/multi.h @@ -24,7 +24,7 @@ * ***************************************************************************/ /* - This is an "external" header file. Don't give away any internals here! + This is an "external" header file. Do not give away any internals here! GOALS @@ -66,7 +66,7 @@ typedef enum { CURLM_OK, CURLM_BAD_HANDLE, /* the passed-in handle is not a valid CURLM handle */ CURLM_BAD_EASY_HANDLE, /* an easy handle was not good/valid */ - CURLM_OUT_OF_MEMORY, /* if you ever get this, you're in deep sh*t */ + CURLM_OUT_OF_MEMORY, /* if you ever get this, you are in deep sh*t */ CURLM_INTERNAL_ERROR, /* this is a libcurl bug */ CURLM_BAD_SOCKET, /* the passed in socket argument did not match */ CURLM_UNKNOWN_OPTION, /* curl_multi_setopt() with unsupported option */ @@ -109,7 +109,7 @@ struct CURLMsg { typedef struct CURLMsg CURLMsg; /* Based on poll(2) structure and values. - * We don't use pollfd and POLL* constants explicitly + * We do not use pollfd and POLL* constants explicitly * to cover platforms without poll(). */ #define CURL_WAIT_POLLIN 0x0001 #define CURL_WAIT_POLLPRI 0x0002 @@ -118,7 +118,7 @@ typedef struct CURLMsg CURLMsg; struct curl_waitfd { curl_socket_t fd; short events; - short revents; /* not supported yet */ + short revents; }; /* @@ -205,7 +205,7 @@ CURL_EXTERN CURLMcode curl_multi_wakeup(CURLM *multi_handle); /* * Name: curl_multi_perform() * - * Desc: When the app thinks there's data available for curl it calls this + * Desc: When the app thinks there is data available for curl it calls this * function to read/write whatever there is right now. This returns * as soon as the reads and writes are done. This function does not * require that there actually is data available for reading or that @@ -236,7 +236,7 @@ CURL_EXTERN CURLMcode curl_multi_cleanup(CURLM *multi_handle); /* * Name: curl_multi_info_read() * - * Desc: Ask the multi handle if there's any messages/informationals from + * Desc: Ask the multi handle if there is any messages/informationals from * the individual transfers. Messages include informationals such as * error code from the transfer or just the fact that a transfer is * completed. More details on these should be written down as well. @@ -253,7 +253,7 @@ CURL_EXTERN CURLMcode curl_multi_cleanup(CURLM *multi_handle); * we will provide the particular "transfer handle" in that struct * and that should/could/would be used in subsequent * curl_easy_getinfo() calls (or similar). The point being that we - * must never expose complex structs to applications, as then we'll + * must never expose complex structs to applications, as then we will * undoubtably get backwards compatibility problems in the future. * * Returns: A pointer to a filled-in struct, or NULL if it failed or ran out @@ -268,7 +268,7 @@ CURL_EXTERN CURLMsg *curl_multi_info_read(CURLM *multi_handle, * Name: curl_multi_strerror() * * Desc: The curl_multi_strerror function may be used to turn a CURLMcode - * value into the equivalent human readable error string. This is + * value into the equivalent human readable error string. This is * useful for printing meaningful error messages. * * Returns: A pointer to a null-terminated error message. @@ -282,7 +282,7 @@ CURL_EXTERN const char *curl_multi_strerror(CURLMcode); * Desc: An alternative version of curl_multi_perform() that allows the * application to pass in one of the file descriptors that have been * detected to have "action" on them and let libcurl perform. - * See man page for details. + * See manpage for details. */ #define CURL_POLL_NONE 0 #define CURL_POLL_IN 1 @@ -426,6 +426,17 @@ CURL_EXTERN CURLMcode curl_multi_setopt(CURLM *multi_handle, CURL_EXTERN CURLMcode curl_multi_assign(CURLM *multi_handle, curl_socket_t sockfd, void *sockp); +/* + * Name: curl_multi_get_handles() + * + * Desc: Returns an allocated array holding all handles currently added to + * the multi handle. Marks the final entry with a NULL pointer. If + * there is no easy handle added to the multi handle, this function + * returns an array with the first entry as a NULL pointer. + * + * Returns: NULL on failure, otherwise a CURL **array pointer + */ +CURL_EXTERN CURL **curl_multi_get_handles(CURLM *multi_handle); /* * Name: curl_push_callback @@ -453,6 +464,20 @@ typedef int (*curl_push_callback)(CURL *parent, struct curl_pushheaders *headers, void *userp); +/* + * Name: curl_multi_waitfds() + * + * Desc: Ask curl for fds for polling. The app can use these to poll on. + * We want curl_multi_perform() called as soon as one of them are + * ready. Passing zero size allows to get just a number of fds. + * + * Returns: CURLMcode type, general multi error code. + */ +CURL_EXTERN CURLMcode curl_multi_waitfds(CURLM *multi, + struct curl_waitfd *ufds, + unsigned int size, + unsigned int *fd_count); + #ifdef __cplusplus } /* end of extern "C" */ #endif diff --git a/ktor-client/ktor-client-curl/desktop/interop/linuxArm64/include/curl/options.h b/ktor-client/ktor-client-curl/desktop/interop/include/curl/options.h old mode 100755 new mode 100644 similarity index 100% rename from ktor-client/ktor-client-curl/desktop/interop/linuxArm64/include/curl/options.h rename to ktor-client/ktor-client-curl/desktop/interop/include/curl/options.h diff --git a/ktor-client/ktor-client-curl/desktop/interop/linuxArm64/include/curl/stdcheaders.h b/ktor-client/ktor-client-curl/desktop/interop/include/curl/stdcheaders.h old mode 100755 new mode 100644 similarity index 100% rename from ktor-client/ktor-client-curl/desktop/interop/linuxArm64/include/curl/stdcheaders.h rename to ktor-client/ktor-client-curl/desktop/interop/include/curl/stdcheaders.h diff --git a/ktor-client/ktor-client-curl/desktop/interop/linuxArm64/include/curl/system.h b/ktor-client/ktor-client-curl/desktop/interop/include/curl/system.h old mode 100755 new mode 100644 similarity index 89% rename from ktor-client/ktor-client-curl/desktop/interop/linuxArm64/include/curl/system.h rename to ktor-client/ktor-client-curl/desktop/interop/include/curl/system.h index def7739242d..e5be2568455 --- a/ktor-client/ktor-client-curl/desktop/interop/linuxArm64/include/curl/system.h +++ b/ktor-client/ktor-client-curl/desktop/interop/include/curl/system.h @@ -31,7 +31,7 @@ * changed. * * In order to differentiate between platforms/compilers/architectures use - * only compiler built in predefined preprocessor symbols. + * only compiler built-in predefined preprocessor symbols. * * curl_off_t * ---------- @@ -46,7 +46,7 @@ * As a general rule, curl_off_t shall not be mapped to off_t. This rule shall * only be violated if off_t is the only 64-bit data type available and the * size of off_t is independent of large file support settings. Keep your - * build on the safe side avoiding an off_t gating. If you have a 64-bit + * build on the safe side avoiding an off_t gating. If you have a 64-bit * off_t then take for sure that another 64-bit data type exists, dig deeper * and you will find it. * @@ -141,29 +141,6 @@ # define CURL_TYPEOF_CURL_SOCKLEN_T int # endif -#elif defined(__SYMBIAN32__) -# if defined(__EABI__) /* Treat all ARM compilers equally */ -# define CURL_TYPEOF_CURL_OFF_T long long -# define CURL_FORMAT_CURL_OFF_T "lld" -# define CURL_FORMAT_CURL_OFF_TU "llu" -# define CURL_SUFFIX_CURL_OFF_T LL -# define CURL_SUFFIX_CURL_OFF_TU ULL -# elif defined(__CW32__) -# pragma longlong on -# define CURL_TYPEOF_CURL_OFF_T long long -# define CURL_FORMAT_CURL_OFF_T "lld" -# define CURL_FORMAT_CURL_OFF_TU "llu" -# define CURL_SUFFIX_CURL_OFF_T LL -# define CURL_SUFFIX_CURL_OFF_TU ULL -# elif defined(__VC32__) -# define CURL_TYPEOF_CURL_OFF_T __int64 -# define CURL_FORMAT_CURL_OFF_T "lld" -# define CURL_FORMAT_CURL_OFF_TU "llu" -# define CURL_SUFFIX_CURL_OFF_T LL -# define CURL_SUFFIX_CURL_OFF_TU ULL -# endif -# define CURL_TYPEOF_CURL_SOCKLEN_T unsigned int - #elif defined(macintosh) # include # if TYPE_LONGLONG @@ -201,14 +178,14 @@ # define CURL_TYPEOF_CURL_SOCKLEN_T int #elif defined(__MINGW32__) +# include # define CURL_TYPEOF_CURL_OFF_T long long -# define CURL_FORMAT_CURL_OFF_T "I64d" -# define CURL_FORMAT_CURL_OFF_TU "I64u" +# define CURL_FORMAT_CURL_OFF_T PRId64 +# define CURL_FORMAT_CURL_OFF_TU PRIu64 # define CURL_SUFFIX_CURL_OFF_T LL # define CURL_SUFFIX_CURL_OFF_TU ULL -# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t +# define CURL_TYPEOF_CURL_SOCKLEN_T int # define CURL_PULL_SYS_TYPES_H 1 -# define CURL_PULL_WS2TCPIP_H 1 #elif defined(__VMS) # if defined(__VAX) @@ -237,33 +214,28 @@ # define CURL_PULL_SYS_SOCKET_H 1 #elif defined(__MVS__) -# if defined(__IBMC__) || defined(__IBMCPP__) -# if defined(_ILP32) -# elif defined(_LP64) -# endif -# if defined(_LONG_LONG) -# define CURL_TYPEOF_CURL_OFF_T long long -# define CURL_FORMAT_CURL_OFF_T "lld" -# define CURL_FORMAT_CURL_OFF_TU "llu" -# define CURL_SUFFIX_CURL_OFF_T LL -# define CURL_SUFFIX_CURL_OFF_TU ULL -# elif defined(_LP64) -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# else -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# endif -# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t -# define CURL_PULL_SYS_TYPES_H 1 -# define CURL_PULL_SYS_SOCKET_H 1 +# if defined(_LONG_LONG) +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# elif defined(_LP64) +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# else +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL # endif +# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t +# define CURL_PULL_SYS_TYPES_H 1 +# define CURL_PULL_SYS_SOCKET_H 1 #elif defined(__370__) # if defined(__IBMC__) || defined(__IBMCPP__) @@ -352,12 +324,37 @@ # define CURL_PULL_SYS_TYPES_H 1 # define CURL_PULL_SYS_SOCKET_H 1 +#elif defined(__hpux) /* HP aCC compiler */ +# if !defined(_LP64) +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# else +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# endif +# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t +# define CURL_PULL_SYS_TYPES_H 1 +# define CURL_PULL_SYS_SOCKET_H 1 + /* ===================================== */ /* KEEP MSVC THE PENULTIMATE ENTRY */ /* ===================================== */ #elif defined(_MSC_VER) -# if (_MSC_VER >= 900) && (_INTEGRAL_MAX_BITS >= 64) +# if (_MSC_VER >= 1800) +# include +# define CURL_TYPEOF_CURL_OFF_T __int64 +# define CURL_FORMAT_CURL_OFF_T PRId64 +# define CURL_FORMAT_CURL_OFF_TU PRIu64 +# define CURL_SUFFIX_CURL_OFF_T i64 +# define CURL_SUFFIX_CURL_OFF_TU ui64 +# elif (_MSC_VER >= 900) && (_INTEGRAL_MAX_BITS >= 64) # define CURL_TYPEOF_CURL_OFF_T __int64 # define CURL_FORMAT_CURL_OFF_T "I64d" # define CURL_FORMAT_CURL_OFF_TU "I64u" @@ -405,7 +402,7 @@ # define CURL_PULL_SYS_SOCKET_H 1 #else -/* generic "safe guess" on old 32 bit style */ +/* generic "safe guess" on old 32-bit style */ # define CURL_TYPEOF_CURL_OFF_T long # define CURL_FORMAT_CURL_OFF_T "ld" # define CURL_FORMAT_CURL_OFF_TU "lu" @@ -419,15 +416,6 @@ #define CURL_PULL_SYS_POLL_H #endif - -/* CURL_PULL_WS2TCPIP_H is defined above when inclusion of header file */ -/* ws2tcpip.h is required here to properly make type definitions below. */ -#ifdef CURL_PULL_WS2TCPIP_H -# include -# include -# include -#endif - /* CURL_PULL_SYS_TYPES_H is defined above when inclusion of header file */ /* sys/types.h is required here to properly make type definitions below. */ #ifdef CURL_PULL_SYS_TYPES_H diff --git a/ktor-client/ktor-client-curl/desktop/interop/linuxArm64/include/curl/typecheck-gcc.h b/ktor-client/ktor-client-curl/desktop/interop/include/curl/typecheck-gcc.h old mode 100755 new mode 100644 similarity index 99% rename from ktor-client/ktor-client-curl/desktop/interop/linuxArm64/include/curl/typecheck-gcc.h rename to ktor-client/ktor-client-curl/desktop/interop/include/curl/typecheck-gcc.h index bc8d7a78ce9..e532e6997db --- a/ktor-client/ktor-client-curl/desktop/interop/linuxArm64/include/curl/typecheck-gcc.h +++ b/ktor-client/ktor-client-curl/desktop/interop/include/curl/typecheck-gcc.h @@ -34,11 +34,11 @@ * _curl_easy_setopt_err_sometype below * * NOTE: We use two nested 'if' statements here instead of the && operator, in - * order to work around gcc bug #32061. It affects only gcc 4.3.x/4.4.x + * order to work around gcc bug #32061. It affects only gcc 4.3.x/4.4.x * when compiling with -Wlogical-op. * - * To add an option that uses the same type as an existing option, you'll just - * need to extend the appropriate _curl_*_option macro + * To add an option that uses the same type as an existing option, you will + * just need to extend the appropriate _curl_*_option macro */ #define curl_easy_setopt(handle, option, value) \ __extension__({ \ @@ -245,7 +245,7 @@ CURLWARNING(_curl_easy_getinfo_err_curl_off_t, /* To add a new option to one of the groups, just add * (option) == CURLOPT_SOMETHING - * to the or-expression. If the option takes a long or curl_off_t, you don't + * to the or-expression. If the option takes a long or curl_off_t, you do not * have to do anything */ @@ -275,11 +275,13 @@ CURLWARNING(_curl_easy_getinfo_err_curl_off_t, (option) == CURLOPT_DNS_LOCAL_IP6 || \ (option) == CURLOPT_DNS_SERVERS || \ (option) == CURLOPT_DOH_URL || \ + (option) == CURLOPT_ECH || \ (option) == CURLOPT_EGDSOCKET || \ (option) == CURLOPT_FTP_ACCOUNT || \ (option) == CURLOPT_FTP_ALTERNATIVE_TO_USER || \ (option) == CURLOPT_FTPPORT || \ (option) == CURLOPT_HSTS || \ + (option) == CURLOPT_HAPROXY_CLIENT_IP || \ (option) == CURLOPT_INTERFACE || \ (option) == CURLOPT_ISSUERCERT || \ (option) == CURLOPT_KEYPASSWD || \ @@ -676,7 +678,7 @@ typedef CURLcode (*_curl_ssl_ctx_callback4)(CURL *, const void *, const void *); #ifdef HEADER_SSL_H /* hack: if we included OpenSSL's ssl.h, we know about SSL_CTX - * this will of course break if we're included before OpenSSL headers... + * this will of course break if we are included before OpenSSL headers... */ typedef CURLcode (*_curl_ssl_ctx_callback5)(CURL *, SSL_CTX *, void *); typedef CURLcode (*_curl_ssl_ctx_callback6)(CURL *, SSL_CTX *, const void *); diff --git a/ktor-client/ktor-client-curl/desktop/interop/linuxArm64/include/curl/urlapi.h b/ktor-client/ktor-client-curl/desktop/interop/include/curl/urlapi.h old mode 100755 new mode 100644 similarity index 88% rename from ktor-client/ktor-client-curl/desktop/interop/linuxArm64/include/curl/urlapi.h rename to ktor-client/ktor-client-curl/desktop/interop/include/curl/urlapi.h index b97b53475a9..b4a6e5d5670 --- a/ktor-client/ktor-client-curl/desktop/interop/linuxArm64/include/curl/urlapi.h +++ b/ktor-client/ktor-client-curl/desktop/interop/include/curl/urlapi.h @@ -63,6 +63,7 @@ typedef enum { CURLUE_BAD_SLASHES, /* 28 */ CURLUE_BAD_USER, /* 29 */ CURLUE_LACKS_IDN, /* 30 */ + CURLUE_TOO_LARGE, /* 31 */ CURLUE_LAST } CURLUcode; @@ -96,7 +97,12 @@ typedef enum { #define CURLU_NO_AUTHORITY (1<<10) /* Allow empty authority when the scheme is unknown. */ #define CURLU_ALLOW_SPACE (1<<11) /* Allow spaces in the URL */ -#define CURLU_PUNYCODE (1<<12) /* get the host name in pynycode */ +#define CURLU_PUNYCODE (1<<12) /* get the hostname in punycode */ +#define CURLU_PUNY2IDN (1<<13) /* punycode => IDN conversion */ +#define CURLU_GET_EMPTY (1<<14) /* allow empty queries and fragments + when extracting the URL or the + components */ +#define CURLU_NO_GUESS_SCHEME (1<<15) /* for get, do not accept a guess */ typedef struct Curl_URL CURLU; @@ -117,14 +123,14 @@ CURL_EXTERN void curl_url_cleanup(CURLU *handle); * curl_url_dup() duplicates a CURLU handle and returns a new copy. The new * handle must also be freed with curl_url_cleanup(). */ -CURL_EXTERN CURLU *curl_url_dup(CURLU *in); +CURL_EXTERN CURLU *curl_url_dup(const CURLU *in); /* * curl_url_get() extracts a specific part of the URL from a CURLU * handle. Returns error code. The returned pointer MUST be freed with * curl_free() afterwards. */ -CURL_EXTERN CURLUcode curl_url_get(CURLU *handle, CURLUPart what, +CURL_EXTERN CURLUcode curl_url_get(const CURLU *handle, CURLUPart what, char **part, unsigned int flags); /* @@ -137,7 +143,7 @@ CURL_EXTERN CURLUcode curl_url_set(CURLU *handle, CURLUPart what, /* * curl_url_strerror() turns a CURLUcode value into the equivalent human - * readable error string. This is useful for printing meaningful error + * readable error string. This is useful for printing meaningful error * messages. */ CURL_EXTERN const char *curl_url_strerror(CURLUcode); diff --git a/ktor-client/ktor-client-curl/desktop/interop/linuxArm64/include/curl/websockets.h b/ktor-client/ktor-client-curl/desktop/interop/include/curl/websockets.h old mode 100755 new mode 100644 similarity index 89% rename from ktor-client/ktor-client-curl/desktop/interop/linuxArm64/include/curl/websockets.h rename to ktor-client/ktor-client-curl/desktop/interop/include/curl/websockets.h index fd6a916547d..6ef6a2bc92e --- a/ktor-client/ktor-client-curl/desktop/interop/linuxArm64/include/curl/websockets.h +++ b/ktor-client/ktor-client-curl/desktop/interop/include/curl/websockets.h @@ -54,13 +54,13 @@ struct curl_ws_frame { */ CURL_EXTERN CURLcode curl_ws_recv(CURL *curl, void *buffer, size_t buflen, size_t *recv, - struct curl_ws_frame **metap); + const struct curl_ws_frame **metap); -/* sendflags for curl_ws_send() */ +/* flags for curl_ws_send() */ #define CURLWS_PONG (1<<6) /* - * NAME curl_easy_send() + * NAME curl_ws_send() * * DESCRIPTION * @@ -69,13 +69,13 @@ CURL_EXTERN CURLcode curl_ws_recv(CURL *curl, void *buffer, size_t buflen, */ CURL_EXTERN CURLcode curl_ws_send(CURL *curl, const void *buffer, size_t buflen, size_t *sent, - curl_off_t framesize, - unsigned int sendflags); + curl_off_t fragsize, + unsigned int flags); /* bits for the CURLOPT_WS_OPTIONS bitmask: */ #define CURLWS_RAW_MODE (1<<0) -CURL_EXTERN struct curl_ws_frame *curl_ws_meta(CURL *curl); +CURL_EXTERN const struct curl_ws_frame *curl_ws_meta(CURL *curl); #ifdef __cplusplus } diff --git a/ktor-client/ktor-client-curl/desktop/interop/lib/linuxArm64/libcrypto.a b/ktor-client/ktor-client-curl/desktop/interop/lib/linuxArm64/libcrypto.a new file mode 100644 index 00000000000..3d3f47ded49 Binary files /dev/null and b/ktor-client/ktor-client-curl/desktop/interop/lib/linuxArm64/libcrypto.a differ diff --git a/ktor-client/ktor-client-curl/desktop/interop/lib/linuxArm64/libcurl.a b/ktor-client/ktor-client-curl/desktop/interop/lib/linuxArm64/libcurl.a new file mode 100644 index 00000000000..ef11e71f941 Binary files /dev/null and b/ktor-client/ktor-client-curl/desktop/interop/lib/linuxArm64/libcurl.a differ diff --git a/ktor-client/ktor-client-curl/desktop/interop/lib/linuxArm64/libssl.a b/ktor-client/ktor-client-curl/desktop/interop/lib/linuxArm64/libssl.a new file mode 100644 index 00000000000..17ad051860f Binary files /dev/null and b/ktor-client/ktor-client-curl/desktop/interop/lib/linuxArm64/libssl.a differ diff --git a/ktor-client/ktor-client-curl/desktop/interop/lib/linuxX64/libcrypto.a b/ktor-client/ktor-client-curl/desktop/interop/lib/linuxX64/libcrypto.a new file mode 100644 index 00000000000..6497aad88e9 Binary files /dev/null and b/ktor-client/ktor-client-curl/desktop/interop/lib/linuxX64/libcrypto.a differ diff --git a/ktor-client/ktor-client-curl/desktop/interop/lib/linuxX64/libcurl.a b/ktor-client/ktor-client-curl/desktop/interop/lib/linuxX64/libcurl.a new file mode 100644 index 00000000000..e8fddf9caa6 Binary files /dev/null and b/ktor-client/ktor-client-curl/desktop/interop/lib/linuxX64/libcurl.a differ diff --git a/ktor-client/ktor-client-curl/desktop/interop/lib/linuxX64/libssl.a b/ktor-client/ktor-client-curl/desktop/interop/lib/linuxX64/libssl.a new file mode 100644 index 00000000000..613f5471f7d Binary files /dev/null and b/ktor-client/ktor-client-curl/desktop/interop/lib/linuxX64/libssl.a differ diff --git a/ktor-client/ktor-client-curl/desktop/interop/lib/macosArm64/libcurl.a b/ktor-client/ktor-client-curl/desktop/interop/lib/macosArm64/libcurl.a new file mode 100644 index 00000000000..87c62edd03f Binary files /dev/null and b/ktor-client/ktor-client-curl/desktop/interop/lib/macosArm64/libcurl.a differ diff --git a/ktor-client/ktor-client-curl/desktop/interop/lib/macosX64/libcurl.a b/ktor-client/ktor-client-curl/desktop/interop/lib/macosX64/libcurl.a new file mode 100644 index 00000000000..15296500ffd Binary files /dev/null and b/ktor-client/ktor-client-curl/desktop/interop/lib/macosX64/libcurl.a differ diff --git a/ktor-client/ktor-client-curl/desktop/interop/lib/mingwX64/libcrypto.a b/ktor-client/ktor-client-curl/desktop/interop/lib/mingwX64/libcrypto.a new file mode 100644 index 00000000000..4e07f76eefd Binary files /dev/null and b/ktor-client/ktor-client-curl/desktop/interop/lib/mingwX64/libcrypto.a differ diff --git a/ktor-client/ktor-client-curl/desktop/interop/lib/mingwX64/libcurl.a b/ktor-client/ktor-client-curl/desktop/interop/lib/mingwX64/libcurl.a new file mode 100644 index 00000000000..0789c09fa60 Binary files /dev/null and b/ktor-client/ktor-client-curl/desktop/interop/lib/mingwX64/libcurl.a differ diff --git a/ktor-client/ktor-client-curl/desktop/interop/lib/mingwX64/libssl.a b/ktor-client/ktor-client-curl/desktop/interop/lib/mingwX64/libssl.a new file mode 100644 index 00000000000..0f0d686caba Binary files /dev/null and b/ktor-client/ktor-client-curl/desktop/interop/lib/mingwX64/libssl.a differ diff --git a/ktor-client/ktor-client-curl/desktop/interop/lib/mingwX64/libz.a b/ktor-client/ktor-client-curl/desktop/interop/lib/mingwX64/libz.a new file mode 100644 index 00000000000..779cbd23558 Binary files /dev/null and b/ktor-client/ktor-client-curl/desktop/interop/lib/mingwX64/libz.a differ diff --git a/ktor-client/ktor-client-curl/desktop/interop/libcurl.def b/ktor-client/ktor-client-curl/desktop/interop/libcurl.def index c2ba37ccbe1..b3e2dfbfa59 100644 --- a/ktor-client/ktor-client-curl/desktop/interop/libcurl.def +++ b/ktor-client/ktor-client-curl/desktop/interop/libcurl.def @@ -1,56 +1,15 @@ +# curl version = 8.10.1 package = libcurl headers = curl/curl.h headerFilter = curl/* -compilerOpts.mingw_x64 = -DCURL_STATICLIB -linkerOpts.osx = -lcurl \ - -L/usr/lib64 \ - -L/usr/lib/x86_64-linux-gnu \ - -L/opt/local/lib \ - -L/usr/local/opt/curl/lib \ - -L/opt/homebrew/opt/curl/lib +# there is no libz by default installed on windows, so we need to include it statically +staticLibraries.mingw = libcurl.a libssl.a libcrypto.a libz.a +compilerOpts.mingw = -DCURL_STATICLIB -compilerOpts.osx = -I/opt/local/include/ \ - -I/usr/bin/ \ - -I/usr/local/include/ \ - -I/usr/include/ \ - -I/usr/local/Cellar/curl/7.83.1/include/ \ - -I/usr/local/Cellar/curl/7.81.0/include/ \ - -I/usr/local/Cellar/curl/7.80.0_1/include/ \ - -I/usr/local/Cellar/curl/7.80.0/include/ \ - -I/usr/local/Cellar/curl/7.62.0/include/ \ - -I/usr/local/Cellar/curl/7.63.0/include/ \ - -I/usr/local/Cellar/curl/7.65.3/include/ \ - -I/usr/local/Cellar/curl/7.66.0/include/ \ - -I/opt/homebrew/opt/curl/include/ +# there is no need to use openssl on macos, as curl is built using out-of-the-box security framework +staticLibraries.osx = libcurl.a +linkerOpts.osx = -framework Security -framework SystemConfiguration -linkerOpts.linux = -lcurl \ - -L/usr/lib64 \ - -L/usr/lib/x86_64-linux-gnu \ - -L/opt/local/lib \ - -L/usr/local/opt/curl/lib \ - -L/opt/homebrew/opt/curl/lib - -compilerOpts.linux = -I/usr/include/ \ - -I/usr/include/x86_64-linux-gnu/ \ - -I/opt/homebrew/opt/curl/include/ - -staticLibraries.mingw_x64 = \ -libcurl.a \ -libssh2.a \ -libidn2.a \ -libpsl.a \ -libbrotlidec.a \ -libbrotlicommon.a \ -libunistring.a \ -libzstd.a \ - -libraryPaths = desktop/interop/mingwX64/lib - -linkerOpts.mingw_x64 = -Wl,-Bstatic -lstdc++ -static \ --lbcrypt \ --lcrypt32 \ --liconv \ --lwldap32 \ --lws2_32 \ --lz +staticLibraries.linux = libcurl.a libssl.a libcrypto.a +linkerOpts.linux = -lz diff --git a/ktor-client/ktor-client-curl/desktop/interop/libcurl_arm64.def b/ktor-client/ktor-client-curl/desktop/interop/libcurl_arm64.def deleted file mode 100644 index 9e89b6010b3..00000000000 --- a/ktor-client/ktor-client-curl/desktop/interop/libcurl_arm64.def +++ /dev/null @@ -1,24 +0,0 @@ -package = libcurl -headers = curl/curl.h -headerFilter = curl/* - -linkerOpts.osx = -lcurl \ - -L/usr/lib64 \ - -L/usr/lib/x86_64-linux-gnu \ - -L/opt/local/lib \ - -L/usr/local/lib \ - -L/opt/homebrew/opt/curl/lib \ - -L/usr/local/opt/curl/lib - -compilerOpts.osx = -I/opt/homebrew/opt/curl/include/ \ - -I/usr/bin/ \ - -I/usr/local/include/ \ - -I/usr/include/ \ - -I/usr/local/Cellar/curl/7.83.1/include/ \ - -I/usr/local/Cellar/curl/7.81.0/include/ \ - -I/usr/local/Cellar/curl/7.80.0_1/include/ \ - -I/usr/local/Cellar/curl/7.80.0/include/ \ - -I/usr/local/Cellar/curl/7.62.0/include/ \ - -I/usr/local/Cellar/curl/7.63.0/include/ \ - -I/usr/local/Cellar/curl/7.65.3/include/ \ - -I/usr/local/Cellar/curl/7.66.0/include/ diff --git a/ktor-client/ktor-client-curl/desktop/interop/libcurl_linux_arm64.def b/ktor-client/ktor-client-curl/desktop/interop/libcurl_linux_arm64.def deleted file mode 100644 index 8571a02ec96..00000000000 --- a/ktor-client/ktor-client-curl/desktop/interop/libcurl_linux_arm64.def +++ /dev/null @@ -1,7 +0,0 @@ -package = libcurl -headers = curl/curl.h -headerFilter = curl/* - -staticLibraries = libcurl.a - -libraryPaths = desktop/interop/linuxArm64/lib diff --git a/ktor-client/ktor-client-curl/desktop/interop/linuxArm64/lib/libcurl.a b/ktor-client/ktor-client-curl/desktop/interop/linuxArm64/lib/libcurl.a deleted file mode 100755 index 9cba4c80472..00000000000 Binary files a/ktor-client/ktor-client-curl/desktop/interop/linuxArm64/lib/libcurl.a and /dev/null differ diff --git a/ktor-client/ktor-client-curl/desktop/interop/mingwX64/include/curl/curl.h b/ktor-client/ktor-client-curl/desktop/interop/mingwX64/include/curl/curl.h deleted file mode 100644 index b00648e791e..00000000000 --- a/ktor-client/ktor-client-curl/desktop/interop/mingwX64/include/curl/curl.h +++ /dev/null @@ -1,3116 +0,0 @@ -#ifndef CURLINC_CURL_H -#define CURLINC_CURL_H -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 1998 - 2022, Daniel Stenberg, , et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at https://curl.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - * SPDX-License-Identifier: curl - * - ***************************************************************************/ - -/* - * If you have libcurl problems, all docs and details are found here: - * https://curl.se/libcurl/ - */ - -#ifdef CURL_NO_OLDIES -#define CURL_STRICTER -#endif - -#include "curlver.h" /* libcurl version defines */ -#include "system.h" /* determine things run-time */ - -/* - * Define CURL_WIN32 when build target is Win32 API - */ - -#if (defined(_WIN32) || defined(__WIN32__) || defined(WIN32)) && \ - !defined(__SYMBIAN32__) -#define CURL_WIN32 -#endif - -#include -#include - -#if (defined(__FreeBSD__) && (__FreeBSD__ >= 2)) || defined(__MidnightBSD__) -/* Needed for __FreeBSD_version or __MidnightBSD_version symbol definition */ -#include -#endif - -/* The include stuff here below is mainly for time_t! */ -#include -#include - -#if defined(CURL_WIN32) && !defined(_WIN32_WCE) && !defined(__CYGWIN__) -#if !(defined(_WINSOCKAPI_) || defined(_WINSOCK_H) || \ - defined(__LWIP_OPT_H__) || defined(LWIP_HDR_OPT_H)) -/* The check above prevents the winsock2 inclusion if winsock.h already was - included, since they can't co-exist without problems */ -#include -#include -#endif -#endif - -/* HP-UX systems version 9, 10 and 11 lack sys/select.h and so does oldish - libc5-based Linux systems. Only include it on systems that are known to - require it! */ -#if defined(_AIX) || defined(__NOVELL_LIBC__) || defined(__NetBSD__) || \ - defined(__minix) || defined(__SYMBIAN32__) || defined(__INTEGRITY) || \ - defined(ANDROID) || defined(__ANDROID__) || defined(__OpenBSD__) || \ - defined(__CYGWIN__) || defined(AMIGA) || defined(__NuttX__) || \ - (defined(__FreeBSD_version) && (__FreeBSD_version < 800000)) || \ - (defined(__MidnightBSD_version) && (__MidnightBSD_version < 100000)) -#include -#endif - -#if !defined(CURL_WIN32) && !defined(_WIN32_WCE) -#include -#endif - -#if !defined(CURL_WIN32) -#include -#endif - -/* Compatibility for non-Clang compilers */ -#ifndef __has_declspec_attribute -# define __has_declspec_attribute(x) 0 -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -#if defined(BUILDING_LIBCURL) || defined(CURL_STRICTER) -typedef struct Curl_easy CURL; -typedef struct Curl_share CURLSH; -#else -typedef void CURL; -typedef void CURLSH; -#endif - -/* - * libcurl external API function linkage decorations. - */ - -#ifdef CURL_STATICLIB -# define CURL_EXTERN -#elif defined(CURL_WIN32) || defined(__SYMBIAN32__) || \ - (__has_declspec_attribute(dllexport) && \ - __has_declspec_attribute(dllimport)) -# if defined(BUILDING_LIBCURL) -# define CURL_EXTERN __declspec(dllexport) -# else -# define CURL_EXTERN __declspec(dllimport) -# endif -#elif defined(BUILDING_LIBCURL) && defined(CURL_HIDDEN_SYMBOLS) -# define CURL_EXTERN CURL_EXTERN_SYMBOL -#else -# define CURL_EXTERN -#endif - -#ifndef curl_socket_typedef -/* socket typedef */ -#if defined(CURL_WIN32) && !defined(__LWIP_OPT_H__) && !defined(LWIP_HDR_OPT_H) -typedef SOCKET curl_socket_t; -#define CURL_SOCKET_BAD INVALID_SOCKET -#else -typedef int curl_socket_t; -#define CURL_SOCKET_BAD -1 -#endif -#define curl_socket_typedef -#endif /* curl_socket_typedef */ - -/* enum for the different supported SSL backends */ -typedef enum { - CURLSSLBACKEND_NONE = 0, - CURLSSLBACKEND_OPENSSL = 1, - CURLSSLBACKEND_GNUTLS = 2, - CURLSSLBACKEND_NSS = 3, - CURLSSLBACKEND_OBSOLETE4 = 4, /* Was QSOSSL. */ - CURLSSLBACKEND_GSKIT = 5, - CURLSSLBACKEND_POLARSSL = 6, - CURLSSLBACKEND_WOLFSSL = 7, - CURLSSLBACKEND_SCHANNEL = 8, - CURLSSLBACKEND_SECURETRANSPORT = 9, - CURLSSLBACKEND_AXTLS = 10, /* never used since 7.63.0 */ - CURLSSLBACKEND_MBEDTLS = 11, - CURLSSLBACKEND_MESALINK = 12, - CURLSSLBACKEND_BEARSSL = 13, - CURLSSLBACKEND_RUSTLS = 14 -} curl_sslbackend; - -/* aliases for library clones and renames */ -#define CURLSSLBACKEND_LIBRESSL CURLSSLBACKEND_OPENSSL -#define CURLSSLBACKEND_BORINGSSL CURLSSLBACKEND_OPENSSL - -/* deprecated names: */ -#define CURLSSLBACKEND_CYASSL CURLSSLBACKEND_WOLFSSL -#define CURLSSLBACKEND_DARWINSSL CURLSSLBACKEND_SECURETRANSPORT - -struct curl_httppost { - struct curl_httppost *next; /* next entry in the list */ - char *name; /* pointer to allocated name */ - long namelength; /* length of name length */ - char *contents; /* pointer to allocated data contents */ - long contentslength; /* length of contents field, see also - CURL_HTTPPOST_LARGE */ - char *buffer; /* pointer to allocated buffer contents */ - long bufferlength; /* length of buffer field */ - char *contenttype; /* Content-Type */ - struct curl_slist *contentheader; /* list of extra headers for this form */ - struct curl_httppost *more; /* if one field name has more than one - file, this link should link to following - files */ - long flags; /* as defined below */ - -/* specified content is a file name */ -#define CURL_HTTPPOST_FILENAME (1<<0) -/* specified content is a file name */ -#define CURL_HTTPPOST_READFILE (1<<1) -/* name is only stored pointer do not free in formfree */ -#define CURL_HTTPPOST_PTRNAME (1<<2) -/* contents is only stored pointer do not free in formfree */ -#define CURL_HTTPPOST_PTRCONTENTS (1<<3) -/* upload file from buffer */ -#define CURL_HTTPPOST_BUFFER (1<<4) -/* upload file from pointer contents */ -#define CURL_HTTPPOST_PTRBUFFER (1<<5) -/* upload file contents by using the regular read callback to get the data and - pass the given pointer as custom pointer */ -#define CURL_HTTPPOST_CALLBACK (1<<6) -/* use size in 'contentlen', added in 7.46.0 */ -#define CURL_HTTPPOST_LARGE (1<<7) - - char *showfilename; /* The file name to show. If not set, the - actual file name will be used (if this - is a file part) */ - void *userp; /* custom pointer used for - HTTPPOST_CALLBACK posts */ - curl_off_t contentlen; /* alternative length of contents - field. Used if CURL_HTTPPOST_LARGE is - set. Added in 7.46.0 */ -}; - - -/* This is a return code for the progress callback that, when returned, will - signal libcurl to continue executing the default progress function */ -#define CURL_PROGRESSFUNC_CONTINUE 0x10000001 - -/* This is the CURLOPT_PROGRESSFUNCTION callback prototype. It is now - considered deprecated but was the only choice up until 7.31.0 */ -typedef int (*curl_progress_callback)(void *clientp, - double dltotal, - double dlnow, - double ultotal, - double ulnow); - -/* This is the CURLOPT_XFERINFOFUNCTION callback prototype. It was introduced - in 7.32.0, avoids the use of floating point numbers and provides more - detailed information. */ -typedef int (*curl_xferinfo_callback)(void *clientp, - curl_off_t dltotal, - curl_off_t dlnow, - curl_off_t ultotal, - curl_off_t ulnow); - -#ifndef CURL_MAX_READ_SIZE - /* The maximum receive buffer size configurable via CURLOPT_BUFFERSIZE. */ -#define CURL_MAX_READ_SIZE 524288 -#endif - -#ifndef CURL_MAX_WRITE_SIZE - /* Tests have proven that 20K is a very bad buffer size for uploads on - Windows, while 16K for some odd reason performed a lot better. - We do the ifndef check to allow this value to easier be changed at build - time for those who feel adventurous. The practical minimum is about - 400 bytes since libcurl uses a buffer of this size as a scratch area - (unrelated to network send operations). */ -#define CURL_MAX_WRITE_SIZE 16384 -#endif - -#ifndef CURL_MAX_HTTP_HEADER -/* The only reason to have a max limit for this is to avoid the risk of a bad - server feeding libcurl with a never-ending header that will cause reallocs - infinitely */ -#define CURL_MAX_HTTP_HEADER (100*1024) -#endif - -/* This is a magic return code for the write callback that, when returned, - will signal libcurl to pause receiving on the current transfer. */ -#define CURL_WRITEFUNC_PAUSE 0x10000001 - -typedef size_t (*curl_write_callback)(char *buffer, - size_t size, - size_t nitems, - void *outstream); - -/* This callback will be called when a new resolver request is made */ -typedef int (*curl_resolver_start_callback)(void *resolver_state, - void *reserved, void *userdata); - -/* enumeration of file types */ -typedef enum { - CURLFILETYPE_FILE = 0, - CURLFILETYPE_DIRECTORY, - CURLFILETYPE_SYMLINK, - CURLFILETYPE_DEVICE_BLOCK, - CURLFILETYPE_DEVICE_CHAR, - CURLFILETYPE_NAMEDPIPE, - CURLFILETYPE_SOCKET, - CURLFILETYPE_DOOR, /* is possible only on Sun Solaris now */ - - CURLFILETYPE_UNKNOWN /* should never occur */ -} curlfiletype; - -#define CURLFINFOFLAG_KNOWN_FILENAME (1<<0) -#define CURLFINFOFLAG_KNOWN_FILETYPE (1<<1) -#define CURLFINFOFLAG_KNOWN_TIME (1<<2) -#define CURLFINFOFLAG_KNOWN_PERM (1<<3) -#define CURLFINFOFLAG_KNOWN_UID (1<<4) -#define CURLFINFOFLAG_KNOWN_GID (1<<5) -#define CURLFINFOFLAG_KNOWN_SIZE (1<<6) -#define CURLFINFOFLAG_KNOWN_HLINKCOUNT (1<<7) - -/* Information about a single file, used when doing FTP wildcard matching */ -struct curl_fileinfo { - char *filename; - curlfiletype filetype; - time_t time; /* always zero! */ - unsigned int perm; - int uid; - int gid; - curl_off_t size; - long int hardlinks; - - struct { - /* If some of these fields is not NULL, it is a pointer to b_data. */ - char *time; - char *perm; - char *user; - char *group; - char *target; /* pointer to the target filename of a symlink */ - } strings; - - unsigned int flags; - - /* used internally */ - char *b_data; - size_t b_size; - size_t b_used; -}; - -/* return codes for CURLOPT_CHUNK_BGN_FUNCTION */ -#define CURL_CHUNK_BGN_FUNC_OK 0 -#define CURL_CHUNK_BGN_FUNC_FAIL 1 /* tell the lib to end the task */ -#define CURL_CHUNK_BGN_FUNC_SKIP 2 /* skip this chunk over */ - -/* if splitting of data transfer is enabled, this callback is called before - download of an individual chunk started. Note that parameter "remains" works - only for FTP wildcard downloading (for now), otherwise is not used */ -typedef long (*curl_chunk_bgn_callback)(const void *transfer_info, - void *ptr, - int remains); - -/* return codes for CURLOPT_CHUNK_END_FUNCTION */ -#define CURL_CHUNK_END_FUNC_OK 0 -#define CURL_CHUNK_END_FUNC_FAIL 1 /* tell the lib to end the task */ - -/* If splitting of data transfer is enabled this callback is called after - download of an individual chunk finished. - Note! After this callback was set then it have to be called FOR ALL chunks. - Even if downloading of this chunk was skipped in CHUNK_BGN_FUNC. - This is the reason why we don't need "transfer_info" parameter in this - callback and we are not interested in "remains" parameter too. */ -typedef long (*curl_chunk_end_callback)(void *ptr); - -/* return codes for FNMATCHFUNCTION */ -#define CURL_FNMATCHFUNC_MATCH 0 /* string corresponds to the pattern */ -#define CURL_FNMATCHFUNC_NOMATCH 1 /* pattern doesn't match the string */ -#define CURL_FNMATCHFUNC_FAIL 2 /* an error occurred */ - -/* callback type for wildcard downloading pattern matching. If the - string matches the pattern, return CURL_FNMATCHFUNC_MATCH value, etc. */ -typedef int (*curl_fnmatch_callback)(void *ptr, - const char *pattern, - const char *string); - -/* These are the return codes for the seek callbacks */ -#define CURL_SEEKFUNC_OK 0 -#define CURL_SEEKFUNC_FAIL 1 /* fail the entire transfer */ -#define CURL_SEEKFUNC_CANTSEEK 2 /* tell libcurl seeking can't be done, so - libcurl might try other means instead */ -typedef int (*curl_seek_callback)(void *instream, - curl_off_t offset, - int origin); /* 'whence' */ - -/* This is a return code for the read callback that, when returned, will - signal libcurl to immediately abort the current transfer. */ -#define CURL_READFUNC_ABORT 0x10000000 -/* This is a return code for the read callback that, when returned, will - signal libcurl to pause sending data on the current transfer. */ -#define CURL_READFUNC_PAUSE 0x10000001 - -/* Return code for when the trailing headers' callback has terminated - without any errors*/ -#define CURL_TRAILERFUNC_OK 0 -/* Return code for when was an error in the trailing header's list and we - want to abort the request */ -#define CURL_TRAILERFUNC_ABORT 1 - -typedef size_t (*curl_read_callback)(char *buffer, - size_t size, - size_t nitems, - void *instream); - -typedef int (*curl_trailer_callback)(struct curl_slist **list, - void *userdata); - -typedef enum { - CURLSOCKTYPE_IPCXN, /* socket created for a specific IP connection */ - CURLSOCKTYPE_ACCEPT, /* socket created by accept() call */ - CURLSOCKTYPE_LAST /* never use */ -} curlsocktype; - -/* The return code from the sockopt_callback can signal information back - to libcurl: */ -#define CURL_SOCKOPT_OK 0 -#define CURL_SOCKOPT_ERROR 1 /* causes libcurl to abort and return - CURLE_ABORTED_BY_CALLBACK */ -#define CURL_SOCKOPT_ALREADY_CONNECTED 2 - -typedef int (*curl_sockopt_callback)(void *clientp, - curl_socket_t curlfd, - curlsocktype purpose); - -struct curl_sockaddr { - int family; - int socktype; - int protocol; - unsigned int addrlen; /* addrlen was a socklen_t type before 7.18.0 but it - turned really ugly and painful on the systems that - lack this type */ - struct sockaddr addr; -}; - -typedef curl_socket_t -(*curl_opensocket_callback)(void *clientp, - curlsocktype purpose, - struct curl_sockaddr *address); - -typedef int -(*curl_closesocket_callback)(void *clientp, curl_socket_t item); - -typedef enum { - CURLIOE_OK, /* I/O operation successful */ - CURLIOE_UNKNOWNCMD, /* command was unknown to callback */ - CURLIOE_FAILRESTART, /* failed to restart the read */ - CURLIOE_LAST /* never use */ -} curlioerr; - -typedef enum { - CURLIOCMD_NOP, /* no operation */ - CURLIOCMD_RESTARTREAD, /* restart the read stream from start */ - CURLIOCMD_LAST /* never use */ -} curliocmd; - -typedef curlioerr (*curl_ioctl_callback)(CURL *handle, - int cmd, - void *clientp); - -#ifndef CURL_DID_MEMORY_FUNC_TYPEDEFS -/* - * The following typedef's are signatures of malloc, free, realloc, strdup and - * calloc respectively. Function pointers of these types can be passed to the - * curl_global_init_mem() function to set user defined memory management - * callback routines. - */ -typedef void *(*curl_malloc_callback)(size_t size); -typedef void (*curl_free_callback)(void *ptr); -typedef void *(*curl_realloc_callback)(void *ptr, size_t size); -typedef char *(*curl_strdup_callback)(const char *str); -typedef void *(*curl_calloc_callback)(size_t nmemb, size_t size); - -#define CURL_DID_MEMORY_FUNC_TYPEDEFS -#endif - -/* the kind of data that is passed to information_callback*/ -typedef enum { - CURLINFO_TEXT = 0, - CURLINFO_HEADER_IN, /* 1 */ - CURLINFO_HEADER_OUT, /* 2 */ - CURLINFO_DATA_IN, /* 3 */ - CURLINFO_DATA_OUT, /* 4 */ - CURLINFO_SSL_DATA_IN, /* 5 */ - CURLINFO_SSL_DATA_OUT, /* 6 */ - CURLINFO_END -} curl_infotype; - -typedef int (*curl_debug_callback) - (CURL *handle, /* the handle/transfer this concerns */ - curl_infotype type, /* what kind of data */ - char *data, /* points to the data */ - size_t size, /* size of the data pointed to */ - void *userptr); /* whatever the user please */ - -/* This is the CURLOPT_PREREQFUNCTION callback prototype. */ -typedef int (*curl_prereq_callback)(void *clientp, - char *conn_primary_ip, - char *conn_local_ip, - int conn_primary_port, - int conn_local_port); - -/* Return code for when the pre-request callback has terminated without - any errors */ -#define CURL_PREREQFUNC_OK 0 -/* Return code for when the pre-request callback wants to abort the - request */ -#define CURL_PREREQFUNC_ABORT 1 - -/* All possible error codes from all sorts of curl functions. Future versions - may return other values, stay prepared. - - Always add new return codes last. Never *EVER* remove any. The return - codes must remain the same! - */ - -typedef enum { - CURLE_OK = 0, - CURLE_UNSUPPORTED_PROTOCOL, /* 1 */ - CURLE_FAILED_INIT, /* 2 */ - CURLE_URL_MALFORMAT, /* 3 */ - CURLE_NOT_BUILT_IN, /* 4 - [was obsoleted in August 2007 for - 7.17.0, reused in April 2011 for 7.21.5] */ - CURLE_COULDNT_RESOLVE_PROXY, /* 5 */ - CURLE_COULDNT_RESOLVE_HOST, /* 6 */ - CURLE_COULDNT_CONNECT, /* 7 */ - CURLE_WEIRD_SERVER_REPLY, /* 8 */ - CURLE_REMOTE_ACCESS_DENIED, /* 9 a service was denied by the server - due to lack of access - when login fails - this is not returned. */ - CURLE_FTP_ACCEPT_FAILED, /* 10 - [was obsoleted in April 2006 for - 7.15.4, reused in Dec 2011 for 7.24.0]*/ - CURLE_FTP_WEIRD_PASS_REPLY, /* 11 */ - CURLE_FTP_ACCEPT_TIMEOUT, /* 12 - timeout occurred accepting server - [was obsoleted in August 2007 for 7.17.0, - reused in Dec 2011 for 7.24.0]*/ - CURLE_FTP_WEIRD_PASV_REPLY, /* 13 */ - CURLE_FTP_WEIRD_227_FORMAT, /* 14 */ - CURLE_FTP_CANT_GET_HOST, /* 15 */ - CURLE_HTTP2, /* 16 - A problem in the http2 framing layer. - [was obsoleted in August 2007 for 7.17.0, - reused in July 2014 for 7.38.0] */ - CURLE_FTP_COULDNT_SET_TYPE, /* 17 */ - CURLE_PARTIAL_FILE, /* 18 */ - CURLE_FTP_COULDNT_RETR_FILE, /* 19 */ - CURLE_OBSOLETE20, /* 20 - NOT USED */ - CURLE_QUOTE_ERROR, /* 21 - quote command failure */ - CURLE_HTTP_RETURNED_ERROR, /* 22 */ - CURLE_WRITE_ERROR, /* 23 */ - CURLE_OBSOLETE24, /* 24 - NOT USED */ - CURLE_UPLOAD_FAILED, /* 25 - failed upload "command" */ - CURLE_READ_ERROR, /* 26 - couldn't open/read from file */ - CURLE_OUT_OF_MEMORY, /* 27 */ - CURLE_OPERATION_TIMEDOUT, /* 28 - the timeout time was reached */ - CURLE_OBSOLETE29, /* 29 - NOT USED */ - CURLE_FTP_PORT_FAILED, /* 30 - FTP PORT operation failed */ - CURLE_FTP_COULDNT_USE_REST, /* 31 - the REST command failed */ - CURLE_OBSOLETE32, /* 32 - NOT USED */ - CURLE_RANGE_ERROR, /* 33 - RANGE "command" didn't work */ - CURLE_HTTP_POST_ERROR, /* 34 */ - CURLE_SSL_CONNECT_ERROR, /* 35 - wrong when connecting with SSL */ - CURLE_BAD_DOWNLOAD_RESUME, /* 36 - couldn't resume download */ - CURLE_FILE_COULDNT_READ_FILE, /* 37 */ - CURLE_LDAP_CANNOT_BIND, /* 38 */ - CURLE_LDAP_SEARCH_FAILED, /* 39 */ - CURLE_OBSOLETE40, /* 40 - NOT USED */ - CURLE_FUNCTION_NOT_FOUND, /* 41 - NOT USED starting with 7.53.0 */ - CURLE_ABORTED_BY_CALLBACK, /* 42 */ - CURLE_BAD_FUNCTION_ARGUMENT, /* 43 */ - CURLE_OBSOLETE44, /* 44 - NOT USED */ - CURLE_INTERFACE_FAILED, /* 45 - CURLOPT_INTERFACE failed */ - CURLE_OBSOLETE46, /* 46 - NOT USED */ - CURLE_TOO_MANY_REDIRECTS, /* 47 - catch endless re-direct loops */ - CURLE_UNKNOWN_OPTION, /* 48 - User specified an unknown option */ - CURLE_SETOPT_OPTION_SYNTAX, /* 49 - Malformed setopt option */ - CURLE_OBSOLETE50, /* 50 - NOT USED */ - CURLE_OBSOLETE51, /* 51 - NOT USED */ - CURLE_GOT_NOTHING, /* 52 - when this is a specific error */ - CURLE_SSL_ENGINE_NOTFOUND, /* 53 - SSL crypto engine not found */ - CURLE_SSL_ENGINE_SETFAILED, /* 54 - can not set SSL crypto engine as - default */ - CURLE_SEND_ERROR, /* 55 - failed sending network data */ - CURLE_RECV_ERROR, /* 56 - failure in receiving network data */ - CURLE_OBSOLETE57, /* 57 - NOT IN USE */ - CURLE_SSL_CERTPROBLEM, /* 58 - problem with the local certificate */ - CURLE_SSL_CIPHER, /* 59 - couldn't use specified cipher */ - CURLE_PEER_FAILED_VERIFICATION, /* 60 - peer's certificate or fingerprint - wasn't verified fine */ - CURLE_BAD_CONTENT_ENCODING, /* 61 - Unrecognized/bad encoding */ - CURLE_OBSOLETE62, /* 62 - NOT IN USE since 7.82.0 */ - CURLE_FILESIZE_EXCEEDED, /* 63 - Maximum file size exceeded */ - CURLE_USE_SSL_FAILED, /* 64 - Requested FTP SSL level failed */ - CURLE_SEND_FAIL_REWIND, /* 65 - Sending the data requires a rewind - that failed */ - CURLE_SSL_ENGINE_INITFAILED, /* 66 - failed to initialise ENGINE */ - CURLE_LOGIN_DENIED, /* 67 - user, password or similar was not - accepted and we failed to login */ - CURLE_TFTP_NOTFOUND, /* 68 - file not found on server */ - CURLE_TFTP_PERM, /* 69 - permission problem on server */ - CURLE_REMOTE_DISK_FULL, /* 70 - out of disk space on server */ - CURLE_TFTP_ILLEGAL, /* 71 - Illegal TFTP operation */ - CURLE_TFTP_UNKNOWNID, /* 72 - Unknown transfer ID */ - CURLE_REMOTE_FILE_EXISTS, /* 73 - File already exists */ - CURLE_TFTP_NOSUCHUSER, /* 74 - No such user */ - CURLE_CONV_FAILED, /* 75 - conversion failed */ - CURLE_OBSOLETE76, /* 76 - NOT IN USE since 7.82.0 */ - CURLE_SSL_CACERT_BADFILE, /* 77 - could not load CACERT file, missing - or wrong format */ - CURLE_REMOTE_FILE_NOT_FOUND, /* 78 - remote file not found */ - CURLE_SSH, /* 79 - error from the SSH layer, somewhat - generic so the error message will be of - interest when this has happened */ - - CURLE_SSL_SHUTDOWN_FAILED, /* 80 - Failed to shut down the SSL - connection */ - CURLE_AGAIN, /* 81 - socket is not ready for send/recv, - wait till it's ready and try again (Added - in 7.18.2) */ - CURLE_SSL_CRL_BADFILE, /* 82 - could not load CRL file, missing or - wrong format (Added in 7.19.0) */ - CURLE_SSL_ISSUER_ERROR, /* 83 - Issuer check failed. (Added in - 7.19.0) */ - CURLE_FTP_PRET_FAILED, /* 84 - a PRET command failed */ - CURLE_RTSP_CSEQ_ERROR, /* 85 - mismatch of RTSP CSeq numbers */ - CURLE_RTSP_SESSION_ERROR, /* 86 - mismatch of RTSP Session Ids */ - CURLE_FTP_BAD_FILE_LIST, /* 87 - unable to parse FTP file list */ - CURLE_CHUNK_FAILED, /* 88 - chunk callback reported error */ - CURLE_NO_CONNECTION_AVAILABLE, /* 89 - No connection available, the - session will be queued */ - CURLE_SSL_PINNEDPUBKEYNOTMATCH, /* 90 - specified pinned public key did not - match */ - CURLE_SSL_INVALIDCERTSTATUS, /* 91 - invalid certificate status */ - CURLE_HTTP2_STREAM, /* 92 - stream error in HTTP/2 framing layer - */ - CURLE_RECURSIVE_API_CALL, /* 93 - an api function was called from - inside a callback */ - CURLE_AUTH_ERROR, /* 94 - an authentication function returned an - error */ - CURLE_HTTP3, /* 95 - An HTTP/3 layer problem */ - CURLE_QUIC_CONNECT_ERROR, /* 96 - QUIC connection error */ - CURLE_PROXY, /* 97 - proxy handshake error */ - CURLE_SSL_CLIENTCERT, /* 98 - client-side certificate required */ - CURLE_UNRECOVERABLE_POLL, /* 99 - poll/select returned fatal error */ - CURL_LAST /* never use! */ -} CURLcode; - -#ifndef CURL_NO_OLDIES /* define this to test if your app builds with all - the obsolete stuff removed! */ - -/* Previously obsolete error code re-used in 7.38.0 */ -#define CURLE_OBSOLETE16 CURLE_HTTP2 - -/* Previously obsolete error codes re-used in 7.24.0 */ -#define CURLE_OBSOLETE10 CURLE_FTP_ACCEPT_FAILED -#define CURLE_OBSOLETE12 CURLE_FTP_ACCEPT_TIMEOUT - -/* compatibility with older names */ -#define CURLOPT_ENCODING CURLOPT_ACCEPT_ENCODING -#define CURLE_FTP_WEIRD_SERVER_REPLY CURLE_WEIRD_SERVER_REPLY - -/* The following were added in 7.62.0 */ -#define CURLE_SSL_CACERT CURLE_PEER_FAILED_VERIFICATION - -/* The following were added in 7.21.5, April 2011 */ -#define CURLE_UNKNOWN_TELNET_OPTION CURLE_UNKNOWN_OPTION - -/* Added for 7.78.0 */ -#define CURLE_TELNET_OPTION_SYNTAX CURLE_SETOPT_OPTION_SYNTAX - -/* The following were added in 7.17.1 */ -/* These are scheduled to disappear by 2009 */ -#define CURLE_SSL_PEER_CERTIFICATE CURLE_PEER_FAILED_VERIFICATION - -/* The following were added in 7.17.0 */ -/* These are scheduled to disappear by 2009 */ -#define CURLE_OBSOLETE CURLE_OBSOLETE50 /* no one should be using this! */ -#define CURLE_BAD_PASSWORD_ENTERED CURLE_OBSOLETE46 -#define CURLE_BAD_CALLING_ORDER CURLE_OBSOLETE44 -#define CURLE_FTP_USER_PASSWORD_INCORRECT CURLE_OBSOLETE10 -#define CURLE_FTP_CANT_RECONNECT CURLE_OBSOLETE16 -#define CURLE_FTP_COULDNT_GET_SIZE CURLE_OBSOLETE32 -#define CURLE_FTP_COULDNT_SET_ASCII CURLE_OBSOLETE29 -#define CURLE_FTP_WEIRD_USER_REPLY CURLE_OBSOLETE12 -#define CURLE_FTP_WRITE_ERROR CURLE_OBSOLETE20 -#define CURLE_LIBRARY_NOT_FOUND CURLE_OBSOLETE40 -#define CURLE_MALFORMAT_USER CURLE_OBSOLETE24 -#define CURLE_SHARE_IN_USE CURLE_OBSOLETE57 -#define CURLE_URL_MALFORMAT_USER CURLE_NOT_BUILT_IN - -#define CURLE_FTP_ACCESS_DENIED CURLE_REMOTE_ACCESS_DENIED -#define CURLE_FTP_COULDNT_SET_BINARY CURLE_FTP_COULDNT_SET_TYPE -#define CURLE_FTP_QUOTE_ERROR CURLE_QUOTE_ERROR -#define CURLE_TFTP_DISKFULL CURLE_REMOTE_DISK_FULL -#define CURLE_TFTP_EXISTS CURLE_REMOTE_FILE_EXISTS -#define CURLE_HTTP_RANGE_ERROR CURLE_RANGE_ERROR -#define CURLE_FTP_SSL_FAILED CURLE_USE_SSL_FAILED - -/* The following were added earlier */ - -#define CURLE_OPERATION_TIMEOUTED CURLE_OPERATION_TIMEDOUT -#define CURLE_HTTP_NOT_FOUND CURLE_HTTP_RETURNED_ERROR -#define CURLE_HTTP_PORT_FAILED CURLE_INTERFACE_FAILED -#define CURLE_FTP_COULDNT_STOR_FILE CURLE_UPLOAD_FAILED -#define CURLE_FTP_PARTIAL_FILE CURLE_PARTIAL_FILE -#define CURLE_FTP_BAD_DOWNLOAD_RESUME CURLE_BAD_DOWNLOAD_RESUME -#define CURLE_LDAP_INVALID_URL CURLE_OBSOLETE62 -#define CURLE_CONV_REQD CURLE_OBSOLETE76 - -/* This was the error code 50 in 7.7.3 and a few earlier versions, this - is no longer used by libcurl but is instead #defined here only to not - make programs break */ -#define CURLE_ALREADY_COMPLETE 99999 - -/* Provide defines for really old option names */ -#define CURLOPT_FILE CURLOPT_WRITEDATA /* name changed in 7.9.7 */ -#define CURLOPT_INFILE CURLOPT_READDATA /* name changed in 7.9.7 */ -#define CURLOPT_WRITEHEADER CURLOPT_HEADERDATA - -/* Since long deprecated options with no code in the lib that does anything - with them. */ -#define CURLOPT_WRITEINFO CURLOPT_OBSOLETE40 -#define CURLOPT_CLOSEPOLICY CURLOPT_OBSOLETE72 - -#endif /*!CURL_NO_OLDIES*/ - -/* - * Proxy error codes. Returned in CURLINFO_PROXY_ERROR if CURLE_PROXY was - * return for the transfers. - */ -typedef enum { - CURLPX_OK, - CURLPX_BAD_ADDRESS_TYPE, - CURLPX_BAD_VERSION, - CURLPX_CLOSED, - CURLPX_GSSAPI, - CURLPX_GSSAPI_PERMSG, - CURLPX_GSSAPI_PROTECTION, - CURLPX_IDENTD, - CURLPX_IDENTD_DIFFER, - CURLPX_LONG_HOSTNAME, - CURLPX_LONG_PASSWD, - CURLPX_LONG_USER, - CURLPX_NO_AUTH, - CURLPX_RECV_ADDRESS, - CURLPX_RECV_AUTH, - CURLPX_RECV_CONNECT, - CURLPX_RECV_REQACK, - CURLPX_REPLY_ADDRESS_TYPE_NOT_SUPPORTED, - CURLPX_REPLY_COMMAND_NOT_SUPPORTED, - CURLPX_REPLY_CONNECTION_REFUSED, - CURLPX_REPLY_GENERAL_SERVER_FAILURE, - CURLPX_REPLY_HOST_UNREACHABLE, - CURLPX_REPLY_NETWORK_UNREACHABLE, - CURLPX_REPLY_NOT_ALLOWED, - CURLPX_REPLY_TTL_EXPIRED, - CURLPX_REPLY_UNASSIGNED, - CURLPX_REQUEST_FAILED, - CURLPX_RESOLVE_HOST, - CURLPX_SEND_AUTH, - CURLPX_SEND_CONNECT, - CURLPX_SEND_REQUEST, - CURLPX_UNKNOWN_FAIL, - CURLPX_UNKNOWN_MODE, - CURLPX_USER_REJECTED, - CURLPX_LAST /* never use */ -} CURLproxycode; - -/* This prototype applies to all conversion callbacks */ -typedef CURLcode (*curl_conv_callback)(char *buffer, size_t length); - -typedef CURLcode (*curl_ssl_ctx_callback)(CURL *curl, /* easy handle */ - void *ssl_ctx, /* actually an OpenSSL - or WolfSSL SSL_CTX, - or an mbedTLS - mbedtls_ssl_config */ - void *userptr); - -typedef enum { - CURLPROXY_HTTP = 0, /* added in 7.10, new in 7.19.4 default is to use - CONNECT HTTP/1.1 */ - CURLPROXY_HTTP_1_0 = 1, /* added in 7.19.4, force to use CONNECT - HTTP/1.0 */ - CURLPROXY_HTTPS = 2, /* added in 7.52.0 */ - CURLPROXY_SOCKS4 = 4, /* support added in 7.15.2, enum existed already - in 7.10 */ - CURLPROXY_SOCKS5 = 5, /* added in 7.10 */ - CURLPROXY_SOCKS4A = 6, /* added in 7.18.0 */ - CURLPROXY_SOCKS5_HOSTNAME = 7 /* Use the SOCKS5 protocol but pass along the - host name rather than the IP address. added - in 7.18.0 */ -} curl_proxytype; /* this enum was added in 7.10 */ - -/* - * Bitmasks for CURLOPT_HTTPAUTH and CURLOPT_PROXYAUTH options: - * - * CURLAUTH_NONE - No HTTP authentication - * CURLAUTH_BASIC - HTTP Basic authentication (default) - * CURLAUTH_DIGEST - HTTP Digest authentication - * CURLAUTH_NEGOTIATE - HTTP Negotiate (SPNEGO) authentication - * CURLAUTH_GSSNEGOTIATE - Alias for CURLAUTH_NEGOTIATE (deprecated) - * CURLAUTH_NTLM - HTTP NTLM authentication - * CURLAUTH_DIGEST_IE - HTTP Digest authentication with IE flavour - * CURLAUTH_NTLM_WB - HTTP NTLM authentication delegated to winbind helper - * CURLAUTH_BEARER - HTTP Bearer token authentication - * CURLAUTH_ONLY - Use together with a single other type to force no - * authentication or just that single type - * CURLAUTH_ANY - All fine types set - * CURLAUTH_ANYSAFE - All fine types except Basic - */ - -#define CURLAUTH_NONE ((unsigned long)0) -#define CURLAUTH_BASIC (((unsigned long)1)<<0) -#define CURLAUTH_DIGEST (((unsigned long)1)<<1) -#define CURLAUTH_NEGOTIATE (((unsigned long)1)<<2) -/* Deprecated since the advent of CURLAUTH_NEGOTIATE */ -#define CURLAUTH_GSSNEGOTIATE CURLAUTH_NEGOTIATE -/* Used for CURLOPT_SOCKS5_AUTH to stay terminologically correct */ -#define CURLAUTH_GSSAPI CURLAUTH_NEGOTIATE -#define CURLAUTH_NTLM (((unsigned long)1)<<3) -#define CURLAUTH_DIGEST_IE (((unsigned long)1)<<4) -#define CURLAUTH_NTLM_WB (((unsigned long)1)<<5) -#define CURLAUTH_BEARER (((unsigned long)1)<<6) -#define CURLAUTH_AWS_SIGV4 (((unsigned long)1)<<7) -#define CURLAUTH_ONLY (((unsigned long)1)<<31) -#define CURLAUTH_ANY (~CURLAUTH_DIGEST_IE) -#define CURLAUTH_ANYSAFE (~(CURLAUTH_BASIC|CURLAUTH_DIGEST_IE)) - -#define CURLSSH_AUTH_ANY ~0 /* all types supported by the server */ -#define CURLSSH_AUTH_NONE 0 /* none allowed, silly but complete */ -#define CURLSSH_AUTH_PUBLICKEY (1<<0) /* public/private key files */ -#define CURLSSH_AUTH_PASSWORD (1<<1) /* password */ -#define CURLSSH_AUTH_HOST (1<<2) /* host key files */ -#define CURLSSH_AUTH_KEYBOARD (1<<3) /* keyboard interactive */ -#define CURLSSH_AUTH_AGENT (1<<4) /* agent (ssh-agent, pageant...) */ -#define CURLSSH_AUTH_GSSAPI (1<<5) /* gssapi (kerberos, ...) */ -#define CURLSSH_AUTH_DEFAULT CURLSSH_AUTH_ANY - -#define CURLGSSAPI_DELEGATION_NONE 0 /* no delegation (default) */ -#define CURLGSSAPI_DELEGATION_POLICY_FLAG (1<<0) /* if permitted by policy */ -#define CURLGSSAPI_DELEGATION_FLAG (1<<1) /* delegate always */ - -#define CURL_ERROR_SIZE 256 - -enum curl_khtype { - CURLKHTYPE_UNKNOWN, - CURLKHTYPE_RSA1, - CURLKHTYPE_RSA, - CURLKHTYPE_DSS, - CURLKHTYPE_ECDSA, - CURLKHTYPE_ED25519 -}; - -struct curl_khkey { - const char *key; /* points to a null-terminated string encoded with base64 - if len is zero, otherwise to the "raw" data */ - size_t len; - enum curl_khtype keytype; -}; - -/* this is the set of return values expected from the curl_sshkeycallback - callback */ -enum curl_khstat { - CURLKHSTAT_FINE_ADD_TO_FILE, - CURLKHSTAT_FINE, - CURLKHSTAT_REJECT, /* reject the connection, return an error */ - CURLKHSTAT_DEFER, /* do not accept it, but we can't answer right now so - this causes a CURLE_DEFER error but otherwise the - connection will be left intact etc */ - CURLKHSTAT_FINE_REPLACE, /* accept and replace the wrong key*/ - CURLKHSTAT_LAST /* not for use, only a marker for last-in-list */ -}; - -/* this is the set of status codes pass in to the callback */ -enum curl_khmatch { - CURLKHMATCH_OK, /* match */ - CURLKHMATCH_MISMATCH, /* host found, key mismatch! */ - CURLKHMATCH_MISSING, /* no matching host/key found */ - CURLKHMATCH_LAST /* not for use, only a marker for last-in-list */ -}; - -typedef int - (*curl_sshkeycallback) (CURL *easy, /* easy handle */ - const struct curl_khkey *knownkey, /* known */ - const struct curl_khkey *foundkey, /* found */ - enum curl_khmatch, /* libcurl's view on the keys */ - void *clientp); /* custom pointer passed with */ - /* CURLOPT_SSH_KEYDATA */ - -typedef int - (*curl_sshhostkeycallback) (void *clientp,/* custom pointer passed*/ - /* with CURLOPT_SSH_HOSTKEYDATA */ - int keytype, /* CURLKHTYPE */ - const char *key, /*hostkey to check*/ - size_t keylen); /*length of the key*/ - /*return CURLE_OK to accept*/ - /*or something else to refuse*/ - - -/* parameter for the CURLOPT_USE_SSL option */ -typedef enum { - CURLUSESSL_NONE, /* do not attempt to use SSL */ - CURLUSESSL_TRY, /* try using SSL, proceed anyway otherwise */ - CURLUSESSL_CONTROL, /* SSL for the control connection or fail */ - CURLUSESSL_ALL, /* SSL for all communication or fail */ - CURLUSESSL_LAST /* not an option, never use */ -} curl_usessl; - -/* Definition of bits for the CURLOPT_SSL_OPTIONS argument: */ - -/* - ALLOW_BEAST tells libcurl to allow the BEAST SSL vulnerability in the - name of improving interoperability with older servers. Some SSL libraries - have introduced work-arounds for this flaw but those work-arounds sometimes - make the SSL communication fail. To regain functionality with those broken - servers, a user can this way allow the vulnerability back. */ -#define CURLSSLOPT_ALLOW_BEAST (1<<0) - -/* - NO_REVOKE tells libcurl to disable certificate revocation checks for those - SSL backends where such behavior is present. */ -#define CURLSSLOPT_NO_REVOKE (1<<1) - -/* - NO_PARTIALCHAIN tells libcurl to *NOT* accept a partial certificate chain - if possible. The OpenSSL backend has this ability. */ -#define CURLSSLOPT_NO_PARTIALCHAIN (1<<2) - -/* - REVOKE_BEST_EFFORT tells libcurl to ignore certificate revocation offline - checks and ignore missing revocation list for those SSL backends where such - behavior is present. */ -#define CURLSSLOPT_REVOKE_BEST_EFFORT (1<<3) - -/* - CURLSSLOPT_NATIVE_CA tells libcurl to use standard certificate store of - operating system. Currently implemented under MS-Windows. */ -#define CURLSSLOPT_NATIVE_CA (1<<4) - -/* - CURLSSLOPT_AUTO_CLIENT_CERT tells libcurl to automatically locate and use - a client certificate for authentication. (Schannel) */ -#define CURLSSLOPT_AUTO_CLIENT_CERT (1<<5) - -/* The default connection attempt delay in milliseconds for happy eyeballs. - CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS.3 and happy-eyeballs-timeout-ms.d document - this value, keep them in sync. */ -#define CURL_HET_DEFAULT 200L - -/* The default connection upkeep interval in milliseconds. */ -#define CURL_UPKEEP_INTERVAL_DEFAULT 60000L - -#ifndef CURL_NO_OLDIES /* define this to test if your app builds with all - the obsolete stuff removed! */ - -/* Backwards compatibility with older names */ -/* These are scheduled to disappear by 2009 */ - -#define CURLFTPSSL_NONE CURLUSESSL_NONE -#define CURLFTPSSL_TRY CURLUSESSL_TRY -#define CURLFTPSSL_CONTROL CURLUSESSL_CONTROL -#define CURLFTPSSL_ALL CURLUSESSL_ALL -#define CURLFTPSSL_LAST CURLUSESSL_LAST -#define curl_ftpssl curl_usessl -#endif /*!CURL_NO_OLDIES*/ - -/* parameter for the CURLOPT_FTP_SSL_CCC option */ -typedef enum { - CURLFTPSSL_CCC_NONE, /* do not send CCC */ - CURLFTPSSL_CCC_PASSIVE, /* Let the server initiate the shutdown */ - CURLFTPSSL_CCC_ACTIVE, /* Initiate the shutdown */ - CURLFTPSSL_CCC_LAST /* not an option, never use */ -} curl_ftpccc; - -/* parameter for the CURLOPT_FTPSSLAUTH option */ -typedef enum { - CURLFTPAUTH_DEFAULT, /* let libcurl decide */ - CURLFTPAUTH_SSL, /* use "AUTH SSL" */ - CURLFTPAUTH_TLS, /* use "AUTH TLS" */ - CURLFTPAUTH_LAST /* not an option, never use */ -} curl_ftpauth; - -/* parameter for the CURLOPT_FTP_CREATE_MISSING_DIRS option */ -typedef enum { - CURLFTP_CREATE_DIR_NONE, /* do NOT create missing dirs! */ - CURLFTP_CREATE_DIR, /* (FTP/SFTP) if CWD fails, try MKD and then CWD - again if MKD succeeded, for SFTP this does - similar magic */ - CURLFTP_CREATE_DIR_RETRY, /* (FTP only) if CWD fails, try MKD and then CWD - again even if MKD failed! */ - CURLFTP_CREATE_DIR_LAST /* not an option, never use */ -} curl_ftpcreatedir; - -/* parameter for the CURLOPT_FTP_FILEMETHOD option */ -typedef enum { - CURLFTPMETHOD_DEFAULT, /* let libcurl pick */ - CURLFTPMETHOD_MULTICWD, /* single CWD operation for each path part */ - CURLFTPMETHOD_NOCWD, /* no CWD at all */ - CURLFTPMETHOD_SINGLECWD, /* one CWD to full dir, then work on file */ - CURLFTPMETHOD_LAST /* not an option, never use */ -} curl_ftpmethod; - -/* bitmask defines for CURLOPT_HEADEROPT */ -#define CURLHEADER_UNIFIED 0 -#define CURLHEADER_SEPARATE (1<<0) - -/* CURLALTSVC_* are bits for the CURLOPT_ALTSVC_CTRL option */ -#define CURLALTSVC_READONLYFILE (1<<2) -#define CURLALTSVC_H1 (1<<3) -#define CURLALTSVC_H2 (1<<4) -#define CURLALTSVC_H3 (1<<5) - - -struct curl_hstsentry { - char *name; - size_t namelen; - unsigned int includeSubDomains:1; - char expire[18]; /* YYYYMMDD HH:MM:SS [null-terminated] */ -}; - -struct curl_index { - size_t index; /* the provided entry's "index" or count */ - size_t total; /* total number of entries to save */ -}; - -typedef enum { - CURLSTS_OK, - CURLSTS_DONE, - CURLSTS_FAIL -} CURLSTScode; - -typedef CURLSTScode (*curl_hstsread_callback)(CURL *easy, - struct curl_hstsentry *e, - void *userp); -typedef CURLSTScode (*curl_hstswrite_callback)(CURL *easy, - struct curl_hstsentry *e, - struct curl_index *i, - void *userp); - -/* CURLHSTS_* are bits for the CURLOPT_HSTS option */ -#define CURLHSTS_ENABLE (long)(1<<0) -#define CURLHSTS_READONLYFILE (long)(1<<1) - -/* CURLPROTO_ defines are for the CURLOPT_*PROTOCOLS options */ -#define CURLPROTO_HTTP (1<<0) -#define CURLPROTO_HTTPS (1<<1) -#define CURLPROTO_FTP (1<<2) -#define CURLPROTO_FTPS (1<<3) -#define CURLPROTO_SCP (1<<4) -#define CURLPROTO_SFTP (1<<5) -#define CURLPROTO_TELNET (1<<6) -#define CURLPROTO_LDAP (1<<7) -#define CURLPROTO_LDAPS (1<<8) -#define CURLPROTO_DICT (1<<9) -#define CURLPROTO_FILE (1<<10) -#define CURLPROTO_TFTP (1<<11) -#define CURLPROTO_IMAP (1<<12) -#define CURLPROTO_IMAPS (1<<13) -#define CURLPROTO_POP3 (1<<14) -#define CURLPROTO_POP3S (1<<15) -#define CURLPROTO_SMTP (1<<16) -#define CURLPROTO_SMTPS (1<<17) -#define CURLPROTO_RTSP (1<<18) -#define CURLPROTO_RTMP (1<<19) -#define CURLPROTO_RTMPT (1<<20) -#define CURLPROTO_RTMPE (1<<21) -#define CURLPROTO_RTMPTE (1<<22) -#define CURLPROTO_RTMPS (1<<23) -#define CURLPROTO_RTMPTS (1<<24) -#define CURLPROTO_GOPHER (1<<25) -#define CURLPROTO_SMB (1<<26) -#define CURLPROTO_SMBS (1<<27) -#define CURLPROTO_MQTT (1<<28) -#define CURLPROTO_GOPHERS (1<<29) -#define CURLPROTO_ALL (~0) /* enable everything */ - -/* long may be 32 or 64 bits, but we should never depend on anything else - but 32 */ -#define CURLOPTTYPE_LONG 0 -#define CURLOPTTYPE_OBJECTPOINT 10000 -#define CURLOPTTYPE_FUNCTIONPOINT 20000 -#define CURLOPTTYPE_OFF_T 30000 -#define CURLOPTTYPE_BLOB 40000 - -/* *STRINGPOINT is an alias for OBJECTPOINT to allow tools to extract the - string options from the header file */ - - -#define CURLOPT(na,t,nu) na = t + nu - -/* CURLOPT aliases that make no run-time difference */ - -/* 'char *' argument to a string with a trailing zero */ -#define CURLOPTTYPE_STRINGPOINT CURLOPTTYPE_OBJECTPOINT - -/* 'struct curl_slist *' argument */ -#define CURLOPTTYPE_SLISTPOINT CURLOPTTYPE_OBJECTPOINT - -/* 'void *' argument passed untouched to callback */ -#define CURLOPTTYPE_CBPOINT CURLOPTTYPE_OBJECTPOINT - -/* 'long' argument with a set of values/bitmask */ -#define CURLOPTTYPE_VALUES CURLOPTTYPE_LONG - -/* - * All CURLOPT_* values. - */ - -typedef enum { - /* This is the FILE * or void * the regular output should be written to. */ - CURLOPT(CURLOPT_WRITEDATA, CURLOPTTYPE_CBPOINT, 1), - - /* The full URL to get/put */ - CURLOPT(CURLOPT_URL, CURLOPTTYPE_STRINGPOINT, 2), - - /* Port number to connect to, if other than default. */ - CURLOPT(CURLOPT_PORT, CURLOPTTYPE_LONG, 3), - - /* Name of proxy to use. */ - CURLOPT(CURLOPT_PROXY, CURLOPTTYPE_STRINGPOINT, 4), - - /* "user:password;options" to use when fetching. */ - CURLOPT(CURLOPT_USERPWD, CURLOPTTYPE_STRINGPOINT, 5), - - /* "user:password" to use with proxy. */ - CURLOPT(CURLOPT_PROXYUSERPWD, CURLOPTTYPE_STRINGPOINT, 6), - - /* Range to get, specified as an ASCII string. */ - CURLOPT(CURLOPT_RANGE, CURLOPTTYPE_STRINGPOINT, 7), - - /* not used */ - - /* Specified file stream to upload from (use as input): */ - CURLOPT(CURLOPT_READDATA, CURLOPTTYPE_CBPOINT, 9), - - /* Buffer to receive error messages in, must be at least CURL_ERROR_SIZE - * bytes big. */ - CURLOPT(CURLOPT_ERRORBUFFER, CURLOPTTYPE_OBJECTPOINT, 10), - - /* Function that will be called to store the output (instead of fwrite). The - * parameters will use fwrite() syntax, make sure to follow them. */ - CURLOPT(CURLOPT_WRITEFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 11), - - /* Function that will be called to read the input (instead of fread). The - * parameters will use fread() syntax, make sure to follow them. */ - CURLOPT(CURLOPT_READFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 12), - - /* Time-out the read operation after this amount of seconds */ - CURLOPT(CURLOPT_TIMEOUT, CURLOPTTYPE_LONG, 13), - - /* If the CURLOPT_INFILE is used, this can be used to inform libcurl about - * how large the file being sent really is. That allows better error - * checking and better verifies that the upload was successful. -1 means - * unknown size. - * - * For large file support, there is also a _LARGE version of the key - * which takes an off_t type, allowing platforms with larger off_t - * sizes to handle larger files. See below for INFILESIZE_LARGE. - */ - CURLOPT(CURLOPT_INFILESIZE, CURLOPTTYPE_LONG, 14), - - /* POST static input fields. */ - CURLOPT(CURLOPT_POSTFIELDS, CURLOPTTYPE_OBJECTPOINT, 15), - - /* Set the referrer page (needed by some CGIs) */ - CURLOPT(CURLOPT_REFERER, CURLOPTTYPE_STRINGPOINT, 16), - - /* Set the FTP PORT string (interface name, named or numerical IP address) - Use i.e '-' to use default address. */ - CURLOPT(CURLOPT_FTPPORT, CURLOPTTYPE_STRINGPOINT, 17), - - /* Set the User-Agent string (examined by some CGIs) */ - CURLOPT(CURLOPT_USERAGENT, CURLOPTTYPE_STRINGPOINT, 18), - - /* If the download receives less than "low speed limit" bytes/second - * during "low speed time" seconds, the operations is aborted. - * You could i.e if you have a pretty high speed connection, abort if - * it is less than 2000 bytes/sec during 20 seconds. - */ - - /* Set the "low speed limit" */ - CURLOPT(CURLOPT_LOW_SPEED_LIMIT, CURLOPTTYPE_LONG, 19), - - /* Set the "low speed time" */ - CURLOPT(CURLOPT_LOW_SPEED_TIME, CURLOPTTYPE_LONG, 20), - - /* Set the continuation offset. - * - * Note there is also a _LARGE version of this key which uses - * off_t types, allowing for large file offsets on platforms which - * use larger-than-32-bit off_t's. Look below for RESUME_FROM_LARGE. - */ - CURLOPT(CURLOPT_RESUME_FROM, CURLOPTTYPE_LONG, 21), - - /* Set cookie in request: */ - CURLOPT(CURLOPT_COOKIE, CURLOPTTYPE_STRINGPOINT, 22), - - /* This points to a linked list of headers, struct curl_slist kind. This - list is also used for RTSP (in spite of its name) */ - CURLOPT(CURLOPT_HTTPHEADER, CURLOPTTYPE_SLISTPOINT, 23), - - /* This points to a linked list of post entries, struct curl_httppost */ - CURLOPT(CURLOPT_HTTPPOST, CURLOPTTYPE_OBJECTPOINT, 24), - - /* name of the file keeping your private SSL-certificate */ - CURLOPT(CURLOPT_SSLCERT, CURLOPTTYPE_STRINGPOINT, 25), - - /* password for the SSL or SSH private key */ - CURLOPT(CURLOPT_KEYPASSWD, CURLOPTTYPE_STRINGPOINT, 26), - - /* send TYPE parameter? */ - CURLOPT(CURLOPT_CRLF, CURLOPTTYPE_LONG, 27), - - /* send linked-list of QUOTE commands */ - CURLOPT(CURLOPT_QUOTE, CURLOPTTYPE_SLISTPOINT, 28), - - /* send FILE * or void * to store headers to, if you use a callback it - is simply passed to the callback unmodified */ - CURLOPT(CURLOPT_HEADERDATA, CURLOPTTYPE_CBPOINT, 29), - - /* point to a file to read the initial cookies from, also enables - "cookie awareness" */ - CURLOPT(CURLOPT_COOKIEFILE, CURLOPTTYPE_STRINGPOINT, 31), - - /* What version to specifically try to use. - See CURL_SSLVERSION defines below. */ - CURLOPT(CURLOPT_SSLVERSION, CURLOPTTYPE_VALUES, 32), - - /* What kind of HTTP time condition to use, see defines */ - CURLOPT(CURLOPT_TIMECONDITION, CURLOPTTYPE_VALUES, 33), - - /* Time to use with the above condition. Specified in number of seconds - since 1 Jan 1970 */ - CURLOPT(CURLOPT_TIMEVALUE, CURLOPTTYPE_LONG, 34), - - /* 35 = OBSOLETE */ - - /* Custom request, for customizing the get command like - HTTP: DELETE, TRACE and others - FTP: to use a different list command - */ - CURLOPT(CURLOPT_CUSTOMREQUEST, CURLOPTTYPE_STRINGPOINT, 36), - - /* FILE handle to use instead of stderr */ - CURLOPT(CURLOPT_STDERR, CURLOPTTYPE_OBJECTPOINT, 37), - - /* 38 is not used */ - - /* send linked-list of post-transfer QUOTE commands */ - CURLOPT(CURLOPT_POSTQUOTE, CURLOPTTYPE_SLISTPOINT, 39), - - /* OBSOLETE, do not use! */ - CURLOPT(CURLOPT_OBSOLETE40, CURLOPTTYPE_OBJECTPOINT, 40), - - /* talk a lot */ - CURLOPT(CURLOPT_VERBOSE, CURLOPTTYPE_LONG, 41), - - /* throw the header out too */ - CURLOPT(CURLOPT_HEADER, CURLOPTTYPE_LONG, 42), - - /* shut off the progress meter */ - CURLOPT(CURLOPT_NOPROGRESS, CURLOPTTYPE_LONG, 43), - - /* use HEAD to get http document */ - CURLOPT(CURLOPT_NOBODY, CURLOPTTYPE_LONG, 44), - - /* no output on http error codes >= 400 */ - CURLOPT(CURLOPT_FAILONERROR, CURLOPTTYPE_LONG, 45), - - /* this is an upload */ - CURLOPT(CURLOPT_UPLOAD, CURLOPTTYPE_LONG, 46), - - /* HTTP POST method */ - CURLOPT(CURLOPT_POST, CURLOPTTYPE_LONG, 47), - - /* bare names when listing directories */ - CURLOPT(CURLOPT_DIRLISTONLY, CURLOPTTYPE_LONG, 48), - - /* Append instead of overwrite on upload! */ - CURLOPT(CURLOPT_APPEND, CURLOPTTYPE_LONG, 50), - - /* Specify whether to read the user+password from the .netrc or the URL. - * This must be one of the CURL_NETRC_* enums below. */ - CURLOPT(CURLOPT_NETRC, CURLOPTTYPE_VALUES, 51), - - /* use Location: Luke! */ - CURLOPT(CURLOPT_FOLLOWLOCATION, CURLOPTTYPE_LONG, 52), - - /* transfer data in text/ASCII format */ - CURLOPT(CURLOPT_TRANSFERTEXT, CURLOPTTYPE_LONG, 53), - - /* HTTP PUT */ - CURLOPT(CURLOPT_PUT, CURLOPTTYPE_LONG, 54), - - /* 55 = OBSOLETE */ - - /* DEPRECATED - * Function that will be called instead of the internal progress display - * function. This function should be defined as the curl_progress_callback - * prototype defines. */ - CURLOPT(CURLOPT_PROGRESSFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 56), - - /* Data passed to the CURLOPT_PROGRESSFUNCTION and CURLOPT_XFERINFOFUNCTION - callbacks */ - CURLOPT(CURLOPT_XFERINFODATA, CURLOPTTYPE_CBPOINT, 57), -#define CURLOPT_PROGRESSDATA CURLOPT_XFERINFODATA - - /* We want the referrer field set automatically when following locations */ - CURLOPT(CURLOPT_AUTOREFERER, CURLOPTTYPE_LONG, 58), - - /* Port of the proxy, can be set in the proxy string as well with: - "[host]:[port]" */ - CURLOPT(CURLOPT_PROXYPORT, CURLOPTTYPE_LONG, 59), - - /* size of the POST input data, if strlen() is not good to use */ - CURLOPT(CURLOPT_POSTFIELDSIZE, CURLOPTTYPE_LONG, 60), - - /* tunnel non-http operations through a HTTP proxy */ - CURLOPT(CURLOPT_HTTPPROXYTUNNEL, CURLOPTTYPE_LONG, 61), - - /* Set the interface string to use as outgoing network interface */ - CURLOPT(CURLOPT_INTERFACE, CURLOPTTYPE_STRINGPOINT, 62), - - /* Set the krb4/5 security level, this also enables krb4/5 awareness. This - * is a string, 'clear', 'safe', 'confidential' or 'private'. If the string - * is set but doesn't match one of these, 'private' will be used. */ - CURLOPT(CURLOPT_KRBLEVEL, CURLOPTTYPE_STRINGPOINT, 63), - - /* Set if we should verify the peer in ssl handshake, set 1 to verify. */ - CURLOPT(CURLOPT_SSL_VERIFYPEER, CURLOPTTYPE_LONG, 64), - - /* The CApath or CAfile used to validate the peer certificate - this option is used only if SSL_VERIFYPEER is true */ - CURLOPT(CURLOPT_CAINFO, CURLOPTTYPE_STRINGPOINT, 65), - - /* 66 = OBSOLETE */ - /* 67 = OBSOLETE */ - - /* Maximum number of http redirects to follow */ - CURLOPT(CURLOPT_MAXREDIRS, CURLOPTTYPE_LONG, 68), - - /* Pass a long set to 1 to get the date of the requested document (if - possible)! Pass a zero to shut it off. */ - CURLOPT(CURLOPT_FILETIME, CURLOPTTYPE_LONG, 69), - - /* This points to a linked list of telnet options */ - CURLOPT(CURLOPT_TELNETOPTIONS, CURLOPTTYPE_SLISTPOINT, 70), - - /* Max amount of cached alive connections */ - CURLOPT(CURLOPT_MAXCONNECTS, CURLOPTTYPE_LONG, 71), - - /* OBSOLETE, do not use! */ - CURLOPT(CURLOPT_OBSOLETE72, CURLOPTTYPE_LONG, 72), - - /* 73 = OBSOLETE */ - - /* Set to explicitly use a new connection for the upcoming transfer. - Do not use this unless you're absolutely sure of this, as it makes the - operation slower and is less friendly for the network. */ - CURLOPT(CURLOPT_FRESH_CONNECT, CURLOPTTYPE_LONG, 74), - - /* Set to explicitly forbid the upcoming transfer's connection to be re-used - when done. Do not use this unless you're absolutely sure of this, as it - makes the operation slower and is less friendly for the network. */ - CURLOPT(CURLOPT_FORBID_REUSE, CURLOPTTYPE_LONG, 75), - - /* Set to a file name that contains random data for libcurl to use to - seed the random engine when doing SSL connects. */ - CURLOPT(CURLOPT_RANDOM_FILE, CURLOPTTYPE_STRINGPOINT, 76), - - /* Set to the Entropy Gathering Daemon socket pathname */ - CURLOPT(CURLOPT_EGDSOCKET, CURLOPTTYPE_STRINGPOINT, 77), - - /* Time-out connect operations after this amount of seconds, if connects are - OK within this time, then fine... This only aborts the connect phase. */ - CURLOPT(CURLOPT_CONNECTTIMEOUT, CURLOPTTYPE_LONG, 78), - - /* Function that will be called to store headers (instead of fwrite). The - * parameters will use fwrite() syntax, make sure to follow them. */ - CURLOPT(CURLOPT_HEADERFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 79), - - /* Set this to force the HTTP request to get back to GET. Only really usable - if POST, PUT or a custom request have been used first. - */ - CURLOPT(CURLOPT_HTTPGET, CURLOPTTYPE_LONG, 80), - - /* Set if we should verify the Common name from the peer certificate in ssl - * handshake, set 1 to check existence, 2 to ensure that it matches the - * provided hostname. */ - CURLOPT(CURLOPT_SSL_VERIFYHOST, CURLOPTTYPE_LONG, 81), - - /* Specify which file name to write all known cookies in after completed - operation. Set file name to "-" (dash) to make it go to stdout. */ - CURLOPT(CURLOPT_COOKIEJAR, CURLOPTTYPE_STRINGPOINT, 82), - - /* Specify which SSL ciphers to use */ - CURLOPT(CURLOPT_SSL_CIPHER_LIST, CURLOPTTYPE_STRINGPOINT, 83), - - /* Specify which HTTP version to use! This must be set to one of the - CURL_HTTP_VERSION* enums set below. */ - CURLOPT(CURLOPT_HTTP_VERSION, CURLOPTTYPE_VALUES, 84), - - /* Specifically switch on or off the FTP engine's use of the EPSV command. By - default, that one will always be attempted before the more traditional - PASV command. */ - CURLOPT(CURLOPT_FTP_USE_EPSV, CURLOPTTYPE_LONG, 85), - - /* type of the file keeping your SSL-certificate ("DER", "PEM", "ENG") */ - CURLOPT(CURLOPT_SSLCERTTYPE, CURLOPTTYPE_STRINGPOINT, 86), - - /* name of the file keeping your private SSL-key */ - CURLOPT(CURLOPT_SSLKEY, CURLOPTTYPE_STRINGPOINT, 87), - - /* type of the file keeping your private SSL-key ("DER", "PEM", "ENG") */ - CURLOPT(CURLOPT_SSLKEYTYPE, CURLOPTTYPE_STRINGPOINT, 88), - - /* crypto engine for the SSL-sub system */ - CURLOPT(CURLOPT_SSLENGINE, CURLOPTTYPE_STRINGPOINT, 89), - - /* set the crypto engine for the SSL-sub system as default - the param has no meaning... - */ - CURLOPT(CURLOPT_SSLENGINE_DEFAULT, CURLOPTTYPE_LONG, 90), - - /* Non-zero value means to use the global dns cache */ - /* DEPRECATED, do not use! */ - CURLOPT(CURLOPT_DNS_USE_GLOBAL_CACHE, CURLOPTTYPE_LONG, 91), - - /* DNS cache timeout */ - CURLOPT(CURLOPT_DNS_CACHE_TIMEOUT, CURLOPTTYPE_LONG, 92), - - /* send linked-list of pre-transfer QUOTE commands */ - CURLOPT(CURLOPT_PREQUOTE, CURLOPTTYPE_SLISTPOINT, 93), - - /* set the debug function */ - CURLOPT(CURLOPT_DEBUGFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 94), - - /* set the data for the debug function */ - CURLOPT(CURLOPT_DEBUGDATA, CURLOPTTYPE_CBPOINT, 95), - - /* mark this as start of a cookie session */ - CURLOPT(CURLOPT_COOKIESESSION, CURLOPTTYPE_LONG, 96), - - /* The CApath directory used to validate the peer certificate - this option is used only if SSL_VERIFYPEER is true */ - CURLOPT(CURLOPT_CAPATH, CURLOPTTYPE_STRINGPOINT, 97), - - /* Instruct libcurl to use a smaller receive buffer */ - CURLOPT(CURLOPT_BUFFERSIZE, CURLOPTTYPE_LONG, 98), - - /* Instruct libcurl to not use any signal/alarm handlers, even when using - timeouts. This option is useful for multi-threaded applications. - See libcurl-the-guide for more background information. */ - CURLOPT(CURLOPT_NOSIGNAL, CURLOPTTYPE_LONG, 99), - - /* Provide a CURLShare for mutexing non-ts data */ - CURLOPT(CURLOPT_SHARE, CURLOPTTYPE_OBJECTPOINT, 100), - - /* indicates type of proxy. accepted values are CURLPROXY_HTTP (default), - CURLPROXY_HTTPS, CURLPROXY_SOCKS4, CURLPROXY_SOCKS4A and - CURLPROXY_SOCKS5. */ - CURLOPT(CURLOPT_PROXYTYPE, CURLOPTTYPE_VALUES, 101), - - /* Set the Accept-Encoding string. Use this to tell a server you would like - the response to be compressed. Before 7.21.6, this was known as - CURLOPT_ENCODING */ - CURLOPT(CURLOPT_ACCEPT_ENCODING, CURLOPTTYPE_STRINGPOINT, 102), - - /* Set pointer to private data */ - CURLOPT(CURLOPT_PRIVATE, CURLOPTTYPE_OBJECTPOINT, 103), - - /* Set aliases for HTTP 200 in the HTTP Response header */ - CURLOPT(CURLOPT_HTTP200ALIASES, CURLOPTTYPE_SLISTPOINT, 104), - - /* Continue to send authentication (user+password) when following locations, - even when hostname changed. This can potentially send off the name - and password to whatever host the server decides. */ - CURLOPT(CURLOPT_UNRESTRICTED_AUTH, CURLOPTTYPE_LONG, 105), - - /* Specifically switch on or off the FTP engine's use of the EPRT command ( - it also disables the LPRT attempt). By default, those ones will always be - attempted before the good old traditional PORT command. */ - CURLOPT(CURLOPT_FTP_USE_EPRT, CURLOPTTYPE_LONG, 106), - - /* Set this to a bitmask value to enable the particular authentications - methods you like. Use this in combination with CURLOPT_USERPWD. - Note that setting multiple bits may cause extra network round-trips. */ - CURLOPT(CURLOPT_HTTPAUTH, CURLOPTTYPE_VALUES, 107), - - /* Set the ssl context callback function, currently only for OpenSSL or - WolfSSL ssl_ctx, or mbedTLS mbedtls_ssl_config in the second argument. - The function must match the curl_ssl_ctx_callback prototype. */ - CURLOPT(CURLOPT_SSL_CTX_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 108), - - /* Set the userdata for the ssl context callback function's third - argument */ - CURLOPT(CURLOPT_SSL_CTX_DATA, CURLOPTTYPE_CBPOINT, 109), - - /* FTP Option that causes missing dirs to be created on the remote server. - In 7.19.4 we introduced the convenience enums for this option using the - CURLFTP_CREATE_DIR prefix. - */ - CURLOPT(CURLOPT_FTP_CREATE_MISSING_DIRS, CURLOPTTYPE_LONG, 110), - - /* Set this to a bitmask value to enable the particular authentications - methods you like. Use this in combination with CURLOPT_PROXYUSERPWD. - Note that setting multiple bits may cause extra network round-trips. */ - CURLOPT(CURLOPT_PROXYAUTH, CURLOPTTYPE_VALUES, 111), - - /* FTP option that changes the timeout, in seconds, associated with - getting a response. This is different from transfer timeout time and - essentially places a demand on the FTP server to acknowledge commands - in a timely manner. */ - CURLOPT(CURLOPT_FTP_RESPONSE_TIMEOUT, CURLOPTTYPE_LONG, 112), -#define CURLOPT_SERVER_RESPONSE_TIMEOUT CURLOPT_FTP_RESPONSE_TIMEOUT - - /* Set this option to one of the CURL_IPRESOLVE_* defines (see below) to - tell libcurl to use those IP versions only. This only has effect on - systems with support for more than one, i.e IPv4 _and_ IPv6. */ - CURLOPT(CURLOPT_IPRESOLVE, CURLOPTTYPE_VALUES, 113), - - /* Set this option to limit the size of a file that will be downloaded from - an HTTP or FTP server. - - Note there is also _LARGE version which adds large file support for - platforms which have larger off_t sizes. See MAXFILESIZE_LARGE below. */ - CURLOPT(CURLOPT_MAXFILESIZE, CURLOPTTYPE_LONG, 114), - - /* See the comment for INFILESIZE above, but in short, specifies - * the size of the file being uploaded. -1 means unknown. - */ - CURLOPT(CURLOPT_INFILESIZE_LARGE, CURLOPTTYPE_OFF_T, 115), - - /* Sets the continuation offset. There is also a CURLOPTTYPE_LONG version - * of this; look above for RESUME_FROM. - */ - CURLOPT(CURLOPT_RESUME_FROM_LARGE, CURLOPTTYPE_OFF_T, 116), - - /* Sets the maximum size of data that will be downloaded from - * an HTTP or FTP server. See MAXFILESIZE above for the LONG version. - */ - CURLOPT(CURLOPT_MAXFILESIZE_LARGE, CURLOPTTYPE_OFF_T, 117), - - /* Set this option to the file name of your .netrc file you want libcurl - to parse (using the CURLOPT_NETRC option). If not set, libcurl will do - a poor attempt to find the user's home directory and check for a .netrc - file in there. */ - CURLOPT(CURLOPT_NETRC_FILE, CURLOPTTYPE_STRINGPOINT, 118), - - /* Enable SSL/TLS for FTP, pick one of: - CURLUSESSL_TRY - try using SSL, proceed anyway otherwise - CURLUSESSL_CONTROL - SSL for the control connection or fail - CURLUSESSL_ALL - SSL for all communication or fail - */ - CURLOPT(CURLOPT_USE_SSL, CURLOPTTYPE_VALUES, 119), - - /* The _LARGE version of the standard POSTFIELDSIZE option */ - CURLOPT(CURLOPT_POSTFIELDSIZE_LARGE, CURLOPTTYPE_OFF_T, 120), - - /* Enable/disable the TCP Nagle algorithm */ - CURLOPT(CURLOPT_TCP_NODELAY, CURLOPTTYPE_LONG, 121), - - /* 122 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */ - /* 123 OBSOLETE. Gone in 7.16.0 */ - /* 124 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */ - /* 125 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */ - /* 126 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */ - /* 127 OBSOLETE. Gone in 7.16.0 */ - /* 128 OBSOLETE. Gone in 7.16.0 */ - - /* When FTP over SSL/TLS is selected (with CURLOPT_USE_SSL), this option - can be used to change libcurl's default action which is to first try - "AUTH SSL" and then "AUTH TLS" in this order, and proceed when a OK - response has been received. - - Available parameters are: - CURLFTPAUTH_DEFAULT - let libcurl decide - CURLFTPAUTH_SSL - try "AUTH SSL" first, then TLS - CURLFTPAUTH_TLS - try "AUTH TLS" first, then SSL - */ - CURLOPT(CURLOPT_FTPSSLAUTH, CURLOPTTYPE_VALUES, 129), - - CURLOPT(CURLOPT_IOCTLFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 130), - CURLOPT(CURLOPT_IOCTLDATA, CURLOPTTYPE_CBPOINT, 131), - - /* 132 OBSOLETE. Gone in 7.16.0 */ - /* 133 OBSOLETE. Gone in 7.16.0 */ - - /* null-terminated string for pass on to the FTP server when asked for - "account" info */ - CURLOPT(CURLOPT_FTP_ACCOUNT, CURLOPTTYPE_STRINGPOINT, 134), - - /* feed cookie into cookie engine */ - CURLOPT(CURLOPT_COOKIELIST, CURLOPTTYPE_STRINGPOINT, 135), - - /* ignore Content-Length */ - CURLOPT(CURLOPT_IGNORE_CONTENT_LENGTH, CURLOPTTYPE_LONG, 136), - - /* Set to non-zero to skip the IP address received in a 227 PASV FTP server - response. Typically used for FTP-SSL purposes but is not restricted to - that. libcurl will then instead use the same IP address it used for the - control connection. */ - CURLOPT(CURLOPT_FTP_SKIP_PASV_IP, CURLOPTTYPE_LONG, 137), - - /* Select "file method" to use when doing FTP, see the curl_ftpmethod - above. */ - CURLOPT(CURLOPT_FTP_FILEMETHOD, CURLOPTTYPE_VALUES, 138), - - /* Local port number to bind the socket to */ - CURLOPT(CURLOPT_LOCALPORT, CURLOPTTYPE_LONG, 139), - - /* Number of ports to try, including the first one set with LOCALPORT. - Thus, setting it to 1 will make no additional attempts but the first. - */ - CURLOPT(CURLOPT_LOCALPORTRANGE, CURLOPTTYPE_LONG, 140), - - /* no transfer, set up connection and let application use the socket by - extracting it with CURLINFO_LASTSOCKET */ - CURLOPT(CURLOPT_CONNECT_ONLY, CURLOPTTYPE_LONG, 141), - - /* Function that will be called to convert from the - network encoding (instead of using the iconv calls in libcurl) */ - CURLOPT(CURLOPT_CONV_FROM_NETWORK_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 142), - - /* Function that will be called to convert to the - network encoding (instead of using the iconv calls in libcurl) */ - CURLOPT(CURLOPT_CONV_TO_NETWORK_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 143), - - /* Function that will be called to convert from UTF8 - (instead of using the iconv calls in libcurl) - Note that this is used only for SSL certificate processing */ - CURLOPT(CURLOPT_CONV_FROM_UTF8_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 144), - - /* if the connection proceeds too quickly then need to slow it down */ - /* limit-rate: maximum number of bytes per second to send or receive */ - CURLOPT(CURLOPT_MAX_SEND_SPEED_LARGE, CURLOPTTYPE_OFF_T, 145), - CURLOPT(CURLOPT_MAX_RECV_SPEED_LARGE, CURLOPTTYPE_OFF_T, 146), - - /* Pointer to command string to send if USER/PASS fails. */ - CURLOPT(CURLOPT_FTP_ALTERNATIVE_TO_USER, CURLOPTTYPE_STRINGPOINT, 147), - - /* callback function for setting socket options */ - CURLOPT(CURLOPT_SOCKOPTFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 148), - CURLOPT(CURLOPT_SOCKOPTDATA, CURLOPTTYPE_CBPOINT, 149), - - /* set to 0 to disable session ID re-use for this transfer, default is - enabled (== 1) */ - CURLOPT(CURLOPT_SSL_SESSIONID_CACHE, CURLOPTTYPE_LONG, 150), - - /* allowed SSH authentication methods */ - CURLOPT(CURLOPT_SSH_AUTH_TYPES, CURLOPTTYPE_VALUES, 151), - - /* Used by scp/sftp to do public/private key authentication */ - CURLOPT(CURLOPT_SSH_PUBLIC_KEYFILE, CURLOPTTYPE_STRINGPOINT, 152), - CURLOPT(CURLOPT_SSH_PRIVATE_KEYFILE, CURLOPTTYPE_STRINGPOINT, 153), - - /* Send CCC (Clear Command Channel) after authentication */ - CURLOPT(CURLOPT_FTP_SSL_CCC, CURLOPTTYPE_LONG, 154), - - /* Same as TIMEOUT and CONNECTTIMEOUT, but with ms resolution */ - CURLOPT(CURLOPT_TIMEOUT_MS, CURLOPTTYPE_LONG, 155), - CURLOPT(CURLOPT_CONNECTTIMEOUT_MS, CURLOPTTYPE_LONG, 156), - - /* set to zero to disable the libcurl's decoding and thus pass the raw body - data to the application even when it is encoded/compressed */ - CURLOPT(CURLOPT_HTTP_TRANSFER_DECODING, CURLOPTTYPE_LONG, 157), - CURLOPT(CURLOPT_HTTP_CONTENT_DECODING, CURLOPTTYPE_LONG, 158), - - /* Permission used when creating new files and directories on the remote - server for protocols that support it, SFTP/SCP/FILE */ - CURLOPT(CURLOPT_NEW_FILE_PERMS, CURLOPTTYPE_LONG, 159), - CURLOPT(CURLOPT_NEW_DIRECTORY_PERMS, CURLOPTTYPE_LONG, 160), - - /* Set the behavior of POST when redirecting. Values must be set to one - of CURL_REDIR* defines below. This used to be called CURLOPT_POST301 */ - CURLOPT(CURLOPT_POSTREDIR, CURLOPTTYPE_VALUES, 161), - - /* used by scp/sftp to verify the host's public key */ - CURLOPT(CURLOPT_SSH_HOST_PUBLIC_KEY_MD5, CURLOPTTYPE_STRINGPOINT, 162), - - /* Callback function for opening socket (instead of socket(2)). Optionally, - callback is able change the address or refuse to connect returning - CURL_SOCKET_BAD. The callback should have type - curl_opensocket_callback */ - CURLOPT(CURLOPT_OPENSOCKETFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 163), - CURLOPT(CURLOPT_OPENSOCKETDATA, CURLOPTTYPE_CBPOINT, 164), - - /* POST volatile input fields. */ - CURLOPT(CURLOPT_COPYPOSTFIELDS, CURLOPTTYPE_OBJECTPOINT, 165), - - /* set transfer mode (;type=) when doing FTP via an HTTP proxy */ - CURLOPT(CURLOPT_PROXY_TRANSFER_MODE, CURLOPTTYPE_LONG, 166), - - /* Callback function for seeking in the input stream */ - CURLOPT(CURLOPT_SEEKFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 167), - CURLOPT(CURLOPT_SEEKDATA, CURLOPTTYPE_CBPOINT, 168), - - /* CRL file */ - CURLOPT(CURLOPT_CRLFILE, CURLOPTTYPE_STRINGPOINT, 169), - - /* Issuer certificate */ - CURLOPT(CURLOPT_ISSUERCERT, CURLOPTTYPE_STRINGPOINT, 170), - - /* (IPv6) Address scope */ - CURLOPT(CURLOPT_ADDRESS_SCOPE, CURLOPTTYPE_LONG, 171), - - /* Collect certificate chain info and allow it to get retrievable with - CURLINFO_CERTINFO after the transfer is complete. */ - CURLOPT(CURLOPT_CERTINFO, CURLOPTTYPE_LONG, 172), - - /* "name" and "pwd" to use when fetching. */ - CURLOPT(CURLOPT_USERNAME, CURLOPTTYPE_STRINGPOINT, 173), - CURLOPT(CURLOPT_PASSWORD, CURLOPTTYPE_STRINGPOINT, 174), - - /* "name" and "pwd" to use with Proxy when fetching. */ - CURLOPT(CURLOPT_PROXYUSERNAME, CURLOPTTYPE_STRINGPOINT, 175), - CURLOPT(CURLOPT_PROXYPASSWORD, CURLOPTTYPE_STRINGPOINT, 176), - - /* Comma separated list of hostnames defining no-proxy zones. These should - match both hostnames directly, and hostnames within a domain. For - example, local.com will match local.com and www.local.com, but NOT - notlocal.com or www.notlocal.com. For compatibility with other - implementations of this, .local.com will be considered to be the same as - local.com. A single * is the only valid wildcard, and effectively - disables the use of proxy. */ - CURLOPT(CURLOPT_NOPROXY, CURLOPTTYPE_STRINGPOINT, 177), - - /* block size for TFTP transfers */ - CURLOPT(CURLOPT_TFTP_BLKSIZE, CURLOPTTYPE_LONG, 178), - - /* Socks Service */ - /* DEPRECATED, do not use! */ - CURLOPT(CURLOPT_SOCKS5_GSSAPI_SERVICE, CURLOPTTYPE_STRINGPOINT, 179), - - /* Socks Service */ - CURLOPT(CURLOPT_SOCKS5_GSSAPI_NEC, CURLOPTTYPE_LONG, 180), - - /* set the bitmask for the protocols that are allowed to be used for the - transfer, which thus helps the app which takes URLs from users or other - external inputs and want to restrict what protocol(s) to deal - with. Defaults to CURLPROTO_ALL. */ - CURLOPT(CURLOPT_PROTOCOLS, CURLOPTTYPE_LONG, 181), - - /* set the bitmask for the protocols that libcurl is allowed to follow to, - as a subset of the CURLOPT_PROTOCOLS ones. That means the protocol needs - to be set in both bitmasks to be allowed to get redirected to. */ - CURLOPT(CURLOPT_REDIR_PROTOCOLS, CURLOPTTYPE_LONG, 182), - - /* set the SSH knownhost file name to use */ - CURLOPT(CURLOPT_SSH_KNOWNHOSTS, CURLOPTTYPE_STRINGPOINT, 183), - - /* set the SSH host key callback, must point to a curl_sshkeycallback - function */ - CURLOPT(CURLOPT_SSH_KEYFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 184), - - /* set the SSH host key callback custom pointer */ - CURLOPT(CURLOPT_SSH_KEYDATA, CURLOPTTYPE_CBPOINT, 185), - - /* set the SMTP mail originator */ - CURLOPT(CURLOPT_MAIL_FROM, CURLOPTTYPE_STRINGPOINT, 186), - - /* set the list of SMTP mail receiver(s) */ - CURLOPT(CURLOPT_MAIL_RCPT, CURLOPTTYPE_SLISTPOINT, 187), - - /* FTP: send PRET before PASV */ - CURLOPT(CURLOPT_FTP_USE_PRET, CURLOPTTYPE_LONG, 188), - - /* RTSP request method (OPTIONS, SETUP, PLAY, etc...) */ - CURLOPT(CURLOPT_RTSP_REQUEST, CURLOPTTYPE_VALUES, 189), - - /* The RTSP session identifier */ - CURLOPT(CURLOPT_RTSP_SESSION_ID, CURLOPTTYPE_STRINGPOINT, 190), - - /* The RTSP stream URI */ - CURLOPT(CURLOPT_RTSP_STREAM_URI, CURLOPTTYPE_STRINGPOINT, 191), - - /* The Transport: header to use in RTSP requests */ - CURLOPT(CURLOPT_RTSP_TRANSPORT, CURLOPTTYPE_STRINGPOINT, 192), - - /* Manually initialize the client RTSP CSeq for this handle */ - CURLOPT(CURLOPT_RTSP_CLIENT_CSEQ, CURLOPTTYPE_LONG, 193), - - /* Manually initialize the server RTSP CSeq for this handle */ - CURLOPT(CURLOPT_RTSP_SERVER_CSEQ, CURLOPTTYPE_LONG, 194), - - /* The stream to pass to INTERLEAVEFUNCTION. */ - CURLOPT(CURLOPT_INTERLEAVEDATA, CURLOPTTYPE_CBPOINT, 195), - - /* Let the application define a custom write method for RTP data */ - CURLOPT(CURLOPT_INTERLEAVEFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 196), - - /* Turn on wildcard matching */ - CURLOPT(CURLOPT_WILDCARDMATCH, CURLOPTTYPE_LONG, 197), - - /* Directory matching callback called before downloading of an - individual file (chunk) started */ - CURLOPT(CURLOPT_CHUNK_BGN_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 198), - - /* Directory matching callback called after the file (chunk) - was downloaded, or skipped */ - CURLOPT(CURLOPT_CHUNK_END_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 199), - - /* Change match (fnmatch-like) callback for wildcard matching */ - CURLOPT(CURLOPT_FNMATCH_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 200), - - /* Let the application define custom chunk data pointer */ - CURLOPT(CURLOPT_CHUNK_DATA, CURLOPTTYPE_CBPOINT, 201), - - /* FNMATCH_FUNCTION user pointer */ - CURLOPT(CURLOPT_FNMATCH_DATA, CURLOPTTYPE_CBPOINT, 202), - - /* send linked-list of name:port:address sets */ - CURLOPT(CURLOPT_RESOLVE, CURLOPTTYPE_SLISTPOINT, 203), - - /* Set a username for authenticated TLS */ - CURLOPT(CURLOPT_TLSAUTH_USERNAME, CURLOPTTYPE_STRINGPOINT, 204), - - /* Set a password for authenticated TLS */ - CURLOPT(CURLOPT_TLSAUTH_PASSWORD, CURLOPTTYPE_STRINGPOINT, 205), - - /* Set authentication type for authenticated TLS */ - CURLOPT(CURLOPT_TLSAUTH_TYPE, CURLOPTTYPE_STRINGPOINT, 206), - - /* Set to 1 to enable the "TE:" header in HTTP requests to ask for - compressed transfer-encoded responses. Set to 0 to disable the use of TE: - in outgoing requests. The current default is 0, but it might change in a - future libcurl release. - - libcurl will ask for the compressed methods it knows of, and if that - isn't any, it will not ask for transfer-encoding at all even if this - option is set to 1. - - */ - CURLOPT(CURLOPT_TRANSFER_ENCODING, CURLOPTTYPE_LONG, 207), - - /* Callback function for closing socket (instead of close(2)). The callback - should have type curl_closesocket_callback */ - CURLOPT(CURLOPT_CLOSESOCKETFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 208), - CURLOPT(CURLOPT_CLOSESOCKETDATA, CURLOPTTYPE_CBPOINT, 209), - - /* allow GSSAPI credential delegation */ - CURLOPT(CURLOPT_GSSAPI_DELEGATION, CURLOPTTYPE_VALUES, 210), - - /* Set the name servers to use for DNS resolution */ - CURLOPT(CURLOPT_DNS_SERVERS, CURLOPTTYPE_STRINGPOINT, 211), - - /* Time-out accept operations (currently for FTP only) after this amount - of milliseconds. */ - CURLOPT(CURLOPT_ACCEPTTIMEOUT_MS, CURLOPTTYPE_LONG, 212), - - /* Set TCP keepalive */ - CURLOPT(CURLOPT_TCP_KEEPALIVE, CURLOPTTYPE_LONG, 213), - - /* non-universal keepalive knobs (Linux, AIX, HP-UX, more) */ - CURLOPT(CURLOPT_TCP_KEEPIDLE, CURLOPTTYPE_LONG, 214), - CURLOPT(CURLOPT_TCP_KEEPINTVL, CURLOPTTYPE_LONG, 215), - - /* Enable/disable specific SSL features with a bitmask, see CURLSSLOPT_* */ - CURLOPT(CURLOPT_SSL_OPTIONS, CURLOPTTYPE_VALUES, 216), - - /* Set the SMTP auth originator */ - CURLOPT(CURLOPT_MAIL_AUTH, CURLOPTTYPE_STRINGPOINT, 217), - - /* Enable/disable SASL initial response */ - CURLOPT(CURLOPT_SASL_IR, CURLOPTTYPE_LONG, 218), - - /* Function that will be called instead of the internal progress display - * function. This function should be defined as the curl_xferinfo_callback - * prototype defines. (Deprecates CURLOPT_PROGRESSFUNCTION) */ - CURLOPT(CURLOPT_XFERINFOFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 219), - - /* The XOAUTH2 bearer token */ - CURLOPT(CURLOPT_XOAUTH2_BEARER, CURLOPTTYPE_STRINGPOINT, 220), - - /* Set the interface string to use as outgoing network - * interface for DNS requests. - * Only supported by the c-ares DNS backend */ - CURLOPT(CURLOPT_DNS_INTERFACE, CURLOPTTYPE_STRINGPOINT, 221), - - /* Set the local IPv4 address to use for outgoing DNS requests. - * Only supported by the c-ares DNS backend */ - CURLOPT(CURLOPT_DNS_LOCAL_IP4, CURLOPTTYPE_STRINGPOINT, 222), - - /* Set the local IPv6 address to use for outgoing DNS requests. - * Only supported by the c-ares DNS backend */ - CURLOPT(CURLOPT_DNS_LOCAL_IP6, CURLOPTTYPE_STRINGPOINT, 223), - - /* Set authentication options directly */ - CURLOPT(CURLOPT_LOGIN_OPTIONS, CURLOPTTYPE_STRINGPOINT, 224), - - /* Enable/disable TLS NPN extension (http2 over ssl might fail without) */ - CURLOPT(CURLOPT_SSL_ENABLE_NPN, CURLOPTTYPE_LONG, 225), - - /* Enable/disable TLS ALPN extension (http2 over ssl might fail without) */ - CURLOPT(CURLOPT_SSL_ENABLE_ALPN, CURLOPTTYPE_LONG, 226), - - /* Time to wait for a response to a HTTP request containing an - * Expect: 100-continue header before sending the data anyway. */ - CURLOPT(CURLOPT_EXPECT_100_TIMEOUT_MS, CURLOPTTYPE_LONG, 227), - - /* This points to a linked list of headers used for proxy requests only, - struct curl_slist kind */ - CURLOPT(CURLOPT_PROXYHEADER, CURLOPTTYPE_SLISTPOINT, 228), - - /* Pass in a bitmask of "header options" */ - CURLOPT(CURLOPT_HEADEROPT, CURLOPTTYPE_VALUES, 229), - - /* The public key in DER form used to validate the peer public key - this option is used only if SSL_VERIFYPEER is true */ - CURLOPT(CURLOPT_PINNEDPUBLICKEY, CURLOPTTYPE_STRINGPOINT, 230), - - /* Path to Unix domain socket */ - CURLOPT(CURLOPT_UNIX_SOCKET_PATH, CURLOPTTYPE_STRINGPOINT, 231), - - /* Set if we should verify the certificate status. */ - CURLOPT(CURLOPT_SSL_VERIFYSTATUS, CURLOPTTYPE_LONG, 232), - - /* Set if we should enable TLS false start. */ - CURLOPT(CURLOPT_SSL_FALSESTART, CURLOPTTYPE_LONG, 233), - - /* Do not squash dot-dot sequences */ - CURLOPT(CURLOPT_PATH_AS_IS, CURLOPTTYPE_LONG, 234), - - /* Proxy Service Name */ - CURLOPT(CURLOPT_PROXY_SERVICE_NAME, CURLOPTTYPE_STRINGPOINT, 235), - - /* Service Name */ - CURLOPT(CURLOPT_SERVICE_NAME, CURLOPTTYPE_STRINGPOINT, 236), - - /* Wait/don't wait for pipe/mutex to clarify */ - CURLOPT(CURLOPT_PIPEWAIT, CURLOPTTYPE_LONG, 237), - - /* Set the protocol used when curl is given a URL without a protocol */ - CURLOPT(CURLOPT_DEFAULT_PROTOCOL, CURLOPTTYPE_STRINGPOINT, 238), - - /* Set stream weight, 1 - 256 (default is 16) */ - CURLOPT(CURLOPT_STREAM_WEIGHT, CURLOPTTYPE_LONG, 239), - - /* Set stream dependency on another CURL handle */ - CURLOPT(CURLOPT_STREAM_DEPENDS, CURLOPTTYPE_OBJECTPOINT, 240), - - /* Set E-xclusive stream dependency on another CURL handle */ - CURLOPT(CURLOPT_STREAM_DEPENDS_E, CURLOPTTYPE_OBJECTPOINT, 241), - - /* Do not send any tftp option requests to the server */ - CURLOPT(CURLOPT_TFTP_NO_OPTIONS, CURLOPTTYPE_LONG, 242), - - /* Linked-list of host:port:connect-to-host:connect-to-port, - overrides the URL's host:port (only for the network layer) */ - CURLOPT(CURLOPT_CONNECT_TO, CURLOPTTYPE_SLISTPOINT, 243), - - /* Set TCP Fast Open */ - CURLOPT(CURLOPT_TCP_FASTOPEN, CURLOPTTYPE_LONG, 244), - - /* Continue to send data if the server responds early with an - * HTTP status code >= 300 */ - CURLOPT(CURLOPT_KEEP_SENDING_ON_ERROR, CURLOPTTYPE_LONG, 245), - - /* The CApath or CAfile used to validate the proxy certificate - this option is used only if PROXY_SSL_VERIFYPEER is true */ - CURLOPT(CURLOPT_PROXY_CAINFO, CURLOPTTYPE_STRINGPOINT, 246), - - /* The CApath directory used to validate the proxy certificate - this option is used only if PROXY_SSL_VERIFYPEER is true */ - CURLOPT(CURLOPT_PROXY_CAPATH, CURLOPTTYPE_STRINGPOINT, 247), - - /* Set if we should verify the proxy in ssl handshake, - set 1 to verify. */ - CURLOPT(CURLOPT_PROXY_SSL_VERIFYPEER, CURLOPTTYPE_LONG, 248), - - /* Set if we should verify the Common name from the proxy certificate in ssl - * handshake, set 1 to check existence, 2 to ensure that it matches - * the provided hostname. */ - CURLOPT(CURLOPT_PROXY_SSL_VERIFYHOST, CURLOPTTYPE_LONG, 249), - - /* What version to specifically try to use for proxy. - See CURL_SSLVERSION defines below. */ - CURLOPT(CURLOPT_PROXY_SSLVERSION, CURLOPTTYPE_VALUES, 250), - - /* Set a username for authenticated TLS for proxy */ - CURLOPT(CURLOPT_PROXY_TLSAUTH_USERNAME, CURLOPTTYPE_STRINGPOINT, 251), - - /* Set a password for authenticated TLS for proxy */ - CURLOPT(CURLOPT_PROXY_TLSAUTH_PASSWORD, CURLOPTTYPE_STRINGPOINT, 252), - - /* Set authentication type for authenticated TLS for proxy */ - CURLOPT(CURLOPT_PROXY_TLSAUTH_TYPE, CURLOPTTYPE_STRINGPOINT, 253), - - /* name of the file keeping your private SSL-certificate for proxy */ - CURLOPT(CURLOPT_PROXY_SSLCERT, CURLOPTTYPE_STRINGPOINT, 254), - - /* type of the file keeping your SSL-certificate ("DER", "PEM", "ENG") for - proxy */ - CURLOPT(CURLOPT_PROXY_SSLCERTTYPE, CURLOPTTYPE_STRINGPOINT, 255), - - /* name of the file keeping your private SSL-key for proxy */ - CURLOPT(CURLOPT_PROXY_SSLKEY, CURLOPTTYPE_STRINGPOINT, 256), - - /* type of the file keeping your private SSL-key ("DER", "PEM", "ENG") for - proxy */ - CURLOPT(CURLOPT_PROXY_SSLKEYTYPE, CURLOPTTYPE_STRINGPOINT, 257), - - /* password for the SSL private key for proxy */ - CURLOPT(CURLOPT_PROXY_KEYPASSWD, CURLOPTTYPE_STRINGPOINT, 258), - - /* Specify which SSL ciphers to use for proxy */ - CURLOPT(CURLOPT_PROXY_SSL_CIPHER_LIST, CURLOPTTYPE_STRINGPOINT, 259), - - /* CRL file for proxy */ - CURLOPT(CURLOPT_PROXY_CRLFILE, CURLOPTTYPE_STRINGPOINT, 260), - - /* Enable/disable specific SSL features with a bitmask for proxy, see - CURLSSLOPT_* */ - CURLOPT(CURLOPT_PROXY_SSL_OPTIONS, CURLOPTTYPE_LONG, 261), - - /* Name of pre proxy to use. */ - CURLOPT(CURLOPT_PRE_PROXY, CURLOPTTYPE_STRINGPOINT, 262), - - /* The public key in DER form used to validate the proxy public key - this option is used only if PROXY_SSL_VERIFYPEER is true */ - CURLOPT(CURLOPT_PROXY_PINNEDPUBLICKEY, CURLOPTTYPE_STRINGPOINT, 263), - - /* Path to an abstract Unix domain socket */ - CURLOPT(CURLOPT_ABSTRACT_UNIX_SOCKET, CURLOPTTYPE_STRINGPOINT, 264), - - /* Suppress proxy CONNECT response headers from user callbacks */ - CURLOPT(CURLOPT_SUPPRESS_CONNECT_HEADERS, CURLOPTTYPE_LONG, 265), - - /* The request target, instead of extracted from the URL */ - CURLOPT(CURLOPT_REQUEST_TARGET, CURLOPTTYPE_STRINGPOINT, 266), - - /* bitmask of allowed auth methods for connections to SOCKS5 proxies */ - CURLOPT(CURLOPT_SOCKS5_AUTH, CURLOPTTYPE_LONG, 267), - - /* Enable/disable SSH compression */ - CURLOPT(CURLOPT_SSH_COMPRESSION, CURLOPTTYPE_LONG, 268), - - /* Post MIME data. */ - CURLOPT(CURLOPT_MIMEPOST, CURLOPTTYPE_OBJECTPOINT, 269), - - /* Time to use with the CURLOPT_TIMECONDITION. Specified in number of - seconds since 1 Jan 1970. */ - CURLOPT(CURLOPT_TIMEVALUE_LARGE, CURLOPTTYPE_OFF_T, 270), - - /* Head start in milliseconds to give happy eyeballs. */ - CURLOPT(CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS, CURLOPTTYPE_LONG, 271), - - /* Function that will be called before a resolver request is made */ - CURLOPT(CURLOPT_RESOLVER_START_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 272), - - /* User data to pass to the resolver start callback. */ - CURLOPT(CURLOPT_RESOLVER_START_DATA, CURLOPTTYPE_CBPOINT, 273), - - /* send HAProxy PROXY protocol header? */ - CURLOPT(CURLOPT_HAPROXYPROTOCOL, CURLOPTTYPE_LONG, 274), - - /* shuffle addresses before use when DNS returns multiple */ - CURLOPT(CURLOPT_DNS_SHUFFLE_ADDRESSES, CURLOPTTYPE_LONG, 275), - - /* Specify which TLS 1.3 ciphers suites to use */ - CURLOPT(CURLOPT_TLS13_CIPHERS, CURLOPTTYPE_STRINGPOINT, 276), - CURLOPT(CURLOPT_PROXY_TLS13_CIPHERS, CURLOPTTYPE_STRINGPOINT, 277), - - /* Disallow specifying username/login in URL. */ - CURLOPT(CURLOPT_DISALLOW_USERNAME_IN_URL, CURLOPTTYPE_LONG, 278), - - /* DNS-over-HTTPS URL */ - CURLOPT(CURLOPT_DOH_URL, CURLOPTTYPE_STRINGPOINT, 279), - - /* Preferred buffer size to use for uploads */ - CURLOPT(CURLOPT_UPLOAD_BUFFERSIZE, CURLOPTTYPE_LONG, 280), - - /* Time in ms between connection upkeep calls for long-lived connections. */ - CURLOPT(CURLOPT_UPKEEP_INTERVAL_MS, CURLOPTTYPE_LONG, 281), - - /* Specify URL using CURL URL API. */ - CURLOPT(CURLOPT_CURLU, CURLOPTTYPE_OBJECTPOINT, 282), - - /* add trailing data just after no more data is available */ - CURLOPT(CURLOPT_TRAILERFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 283), - - /* pointer to be passed to HTTP_TRAILER_FUNCTION */ - CURLOPT(CURLOPT_TRAILERDATA, CURLOPTTYPE_CBPOINT, 284), - - /* set this to 1L to allow HTTP/0.9 responses or 0L to disallow */ - CURLOPT(CURLOPT_HTTP09_ALLOWED, CURLOPTTYPE_LONG, 285), - - /* alt-svc control bitmask */ - CURLOPT(CURLOPT_ALTSVC_CTRL, CURLOPTTYPE_LONG, 286), - - /* alt-svc cache file name to possibly read from/write to */ - CURLOPT(CURLOPT_ALTSVC, CURLOPTTYPE_STRINGPOINT, 287), - - /* maximum age (idle time) of a connection to consider it for reuse - * (in seconds) */ - CURLOPT(CURLOPT_MAXAGE_CONN, CURLOPTTYPE_LONG, 288), - - /* SASL authorization identity */ - CURLOPT(CURLOPT_SASL_AUTHZID, CURLOPTTYPE_STRINGPOINT, 289), - - /* allow RCPT TO command to fail for some recipients */ - CURLOPT(CURLOPT_MAIL_RCPT_ALLLOWFAILS, CURLOPTTYPE_LONG, 290), - - /* the private SSL-certificate as a "blob" */ - CURLOPT(CURLOPT_SSLCERT_BLOB, CURLOPTTYPE_BLOB, 291), - CURLOPT(CURLOPT_SSLKEY_BLOB, CURLOPTTYPE_BLOB, 292), - CURLOPT(CURLOPT_PROXY_SSLCERT_BLOB, CURLOPTTYPE_BLOB, 293), - CURLOPT(CURLOPT_PROXY_SSLKEY_BLOB, CURLOPTTYPE_BLOB, 294), - CURLOPT(CURLOPT_ISSUERCERT_BLOB, CURLOPTTYPE_BLOB, 295), - - /* Issuer certificate for proxy */ - CURLOPT(CURLOPT_PROXY_ISSUERCERT, CURLOPTTYPE_STRINGPOINT, 296), - CURLOPT(CURLOPT_PROXY_ISSUERCERT_BLOB, CURLOPTTYPE_BLOB, 297), - - /* the EC curves requested by the TLS client (RFC 8422, 5.1); - * OpenSSL support via 'set_groups'/'set_curves': - * https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set1_groups.html - */ - CURLOPT(CURLOPT_SSL_EC_CURVES, CURLOPTTYPE_STRINGPOINT, 298), - - /* HSTS bitmask */ - CURLOPT(CURLOPT_HSTS_CTRL, CURLOPTTYPE_LONG, 299), - /* HSTS file name */ - CURLOPT(CURLOPT_HSTS, CURLOPTTYPE_STRINGPOINT, 300), - - /* HSTS read callback */ - CURLOPT(CURLOPT_HSTSREADFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 301), - CURLOPT(CURLOPT_HSTSREADDATA, CURLOPTTYPE_CBPOINT, 302), - - /* HSTS write callback */ - CURLOPT(CURLOPT_HSTSWRITEFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 303), - CURLOPT(CURLOPT_HSTSWRITEDATA, CURLOPTTYPE_CBPOINT, 304), - - /* Parameters for V4 signature */ - CURLOPT(CURLOPT_AWS_SIGV4, CURLOPTTYPE_STRINGPOINT, 305), - - /* Same as CURLOPT_SSL_VERIFYPEER but for DoH (DNS-over-HTTPS) servers. */ - CURLOPT(CURLOPT_DOH_SSL_VERIFYPEER, CURLOPTTYPE_LONG, 306), - - /* Same as CURLOPT_SSL_VERIFYHOST but for DoH (DNS-over-HTTPS) servers. */ - CURLOPT(CURLOPT_DOH_SSL_VERIFYHOST, CURLOPTTYPE_LONG, 307), - - /* Same as CURLOPT_SSL_VERIFYSTATUS but for DoH (DNS-over-HTTPS) servers. */ - CURLOPT(CURLOPT_DOH_SSL_VERIFYSTATUS, CURLOPTTYPE_LONG, 308), - - /* The CA certificates as "blob" used to validate the peer certificate - this option is used only if SSL_VERIFYPEER is true */ - CURLOPT(CURLOPT_CAINFO_BLOB, CURLOPTTYPE_BLOB, 309), - - /* The CA certificates as "blob" used to validate the proxy certificate - this option is used only if PROXY_SSL_VERIFYPEER is true */ - CURLOPT(CURLOPT_PROXY_CAINFO_BLOB, CURLOPTTYPE_BLOB, 310), - - /* used by scp/sftp to verify the host's public key */ - CURLOPT(CURLOPT_SSH_HOST_PUBLIC_KEY_SHA256, CURLOPTTYPE_STRINGPOINT, 311), - - /* Function that will be called immediately before the initial request - is made on a connection (after any protocol negotiation step). */ - CURLOPT(CURLOPT_PREREQFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 312), - - /* Data passed to the CURLOPT_PREREQFUNCTION callback */ - CURLOPT(CURLOPT_PREREQDATA, CURLOPTTYPE_CBPOINT, 313), - - /* maximum age (since creation) of a connection to consider it for reuse - * (in seconds) */ - CURLOPT(CURLOPT_MAXLIFETIME_CONN, CURLOPTTYPE_LONG, 314), - - /* Set MIME option flags. */ - CURLOPT(CURLOPT_MIME_OPTIONS, CURLOPTTYPE_LONG, 315), - - /* set the SSH host key callback, must point to a curl_sshkeycallback - function */ - CURLOPT(CURLOPT_SSH_HOSTKEYFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 316), - - /* set the SSH host key callback custom pointer */ - CURLOPT(CURLOPT_SSH_HOSTKEYDATA, CURLOPTTYPE_CBPOINT, 317), - - CURLOPT_LASTENTRY /* the last unused */ -} CURLoption; - -#ifndef CURL_NO_OLDIES /* define this to test if your app builds with all - the obsolete stuff removed! */ - -/* Backwards compatibility with older names */ -/* These are scheduled to disappear by 2011 */ - -/* This was added in version 7.19.1 */ -#define CURLOPT_POST301 CURLOPT_POSTREDIR - -/* These are scheduled to disappear by 2009 */ - -/* The following were added in 7.17.0 */ -#define CURLOPT_SSLKEYPASSWD CURLOPT_KEYPASSWD -#define CURLOPT_FTPAPPEND CURLOPT_APPEND -#define CURLOPT_FTPLISTONLY CURLOPT_DIRLISTONLY -#define CURLOPT_FTP_SSL CURLOPT_USE_SSL - -/* The following were added earlier */ - -#define CURLOPT_SSLCERTPASSWD CURLOPT_KEYPASSWD -#define CURLOPT_KRB4LEVEL CURLOPT_KRBLEVEL - -#else -/* This is set if CURL_NO_OLDIES is defined at compile-time */ -#undef CURLOPT_DNS_USE_GLOBAL_CACHE /* soon obsolete */ -#endif - - - /* Below here follows defines for the CURLOPT_IPRESOLVE option. If a host - name resolves addresses using more than one IP protocol version, this - option might be handy to force libcurl to use a specific IP version. */ -#define CURL_IPRESOLVE_WHATEVER 0 /* default, uses addresses to all IP - versions that your system allows */ -#define CURL_IPRESOLVE_V4 1 /* uses only IPv4 addresses/connections */ -#define CURL_IPRESOLVE_V6 2 /* uses only IPv6 addresses/connections */ - - /* three convenient "aliases" that follow the name scheme better */ -#define CURLOPT_RTSPHEADER CURLOPT_HTTPHEADER - - /* These enums are for use with the CURLOPT_HTTP_VERSION option. */ -enum { - CURL_HTTP_VERSION_NONE, /* setting this means we don't care, and that we'd - like the library to choose the best possible - for us! */ - CURL_HTTP_VERSION_1_0, /* please use HTTP 1.0 in the request */ - CURL_HTTP_VERSION_1_1, /* please use HTTP 1.1 in the request */ - CURL_HTTP_VERSION_2_0, /* please use HTTP 2 in the request */ - CURL_HTTP_VERSION_2TLS, /* use version 2 for HTTPS, version 1.1 for HTTP */ - CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE, /* please use HTTP 2 without HTTP/1.1 - Upgrade */ - CURL_HTTP_VERSION_3 = 30, /* Makes use of explicit HTTP/3 without fallback. - Use CURLOPT_ALTSVC to enable HTTP/3 upgrade */ - CURL_HTTP_VERSION_LAST /* *ILLEGAL* http version */ -}; - -/* Convenience definition simple because the name of the version is HTTP/2 and - not 2.0. The 2_0 version of the enum name was set while the version was - still planned to be 2.0 and we stick to it for compatibility. */ -#define CURL_HTTP_VERSION_2 CURL_HTTP_VERSION_2_0 - -/* - * Public API enums for RTSP requests - */ -enum { - CURL_RTSPREQ_NONE, /* first in list */ - CURL_RTSPREQ_OPTIONS, - CURL_RTSPREQ_DESCRIBE, - CURL_RTSPREQ_ANNOUNCE, - CURL_RTSPREQ_SETUP, - CURL_RTSPREQ_PLAY, - CURL_RTSPREQ_PAUSE, - CURL_RTSPREQ_TEARDOWN, - CURL_RTSPREQ_GET_PARAMETER, - CURL_RTSPREQ_SET_PARAMETER, - CURL_RTSPREQ_RECORD, - CURL_RTSPREQ_RECEIVE, - CURL_RTSPREQ_LAST /* last in list */ -}; - - /* These enums are for use with the CURLOPT_NETRC option. */ -enum CURL_NETRC_OPTION { - CURL_NETRC_IGNORED, /* The .netrc will never be read. - * This is the default. */ - CURL_NETRC_OPTIONAL, /* A user:password in the URL will be preferred - * to one in the .netrc. */ - CURL_NETRC_REQUIRED, /* A user:password in the URL will be ignored. - * Unless one is set programmatically, the .netrc - * will be queried. */ - CURL_NETRC_LAST -}; - -enum { - CURL_SSLVERSION_DEFAULT, - CURL_SSLVERSION_TLSv1, /* TLS 1.x */ - CURL_SSLVERSION_SSLv2, - CURL_SSLVERSION_SSLv3, - CURL_SSLVERSION_TLSv1_0, - CURL_SSLVERSION_TLSv1_1, - CURL_SSLVERSION_TLSv1_2, - CURL_SSLVERSION_TLSv1_3, - - CURL_SSLVERSION_LAST /* never use, keep last */ -}; - -enum { - CURL_SSLVERSION_MAX_NONE = 0, - CURL_SSLVERSION_MAX_DEFAULT = (CURL_SSLVERSION_TLSv1 << 16), - CURL_SSLVERSION_MAX_TLSv1_0 = (CURL_SSLVERSION_TLSv1_0 << 16), - CURL_SSLVERSION_MAX_TLSv1_1 = (CURL_SSLVERSION_TLSv1_1 << 16), - CURL_SSLVERSION_MAX_TLSv1_2 = (CURL_SSLVERSION_TLSv1_2 << 16), - CURL_SSLVERSION_MAX_TLSv1_3 = (CURL_SSLVERSION_TLSv1_3 << 16), - - /* never use, keep last */ - CURL_SSLVERSION_MAX_LAST = (CURL_SSLVERSION_LAST << 16) -}; - -enum CURL_TLSAUTH { - CURL_TLSAUTH_NONE, - CURL_TLSAUTH_SRP, - CURL_TLSAUTH_LAST /* never use, keep last */ -}; - -/* symbols to use with CURLOPT_POSTREDIR. - CURL_REDIR_POST_301, CURL_REDIR_POST_302 and CURL_REDIR_POST_303 - can be bitwise ORed so that CURL_REDIR_POST_301 | CURL_REDIR_POST_302 - | CURL_REDIR_POST_303 == CURL_REDIR_POST_ALL */ - -#define CURL_REDIR_GET_ALL 0 -#define CURL_REDIR_POST_301 1 -#define CURL_REDIR_POST_302 2 -#define CURL_REDIR_POST_303 4 -#define CURL_REDIR_POST_ALL \ - (CURL_REDIR_POST_301|CURL_REDIR_POST_302|CURL_REDIR_POST_303) - -typedef enum { - CURL_TIMECOND_NONE, - - CURL_TIMECOND_IFMODSINCE, - CURL_TIMECOND_IFUNMODSINCE, - CURL_TIMECOND_LASTMOD, - - CURL_TIMECOND_LAST -} curl_TimeCond; - -/* Special size_t value signaling a null-terminated string. */ -#define CURL_ZERO_TERMINATED ((size_t) -1) - -/* curl_strequal() and curl_strnequal() are subject for removal in a future - release */ -CURL_EXTERN int curl_strequal(const char *s1, const char *s2); -CURL_EXTERN int curl_strnequal(const char *s1, const char *s2, size_t n); - -/* Mime/form handling support. */ -typedef struct curl_mime curl_mime; /* Mime context. */ -typedef struct curl_mimepart curl_mimepart; /* Mime part context. */ - -/* CURLMIMEOPT_ defines are for the CURLOPT_MIME_OPTIONS option. */ -#define CURLMIMEOPT_FORMESCAPE (1<<0) /* Use backslash-escaping for forms. */ - -/* - * NAME curl_mime_init() - * - * DESCRIPTION - * - * Create a mime context and return its handle. The easy parameter is the - * target handle. - */ -CURL_EXTERN curl_mime *curl_mime_init(CURL *easy); - -/* - * NAME curl_mime_free() - * - * DESCRIPTION - * - * release a mime handle and its substructures. - */ -CURL_EXTERN void curl_mime_free(curl_mime *mime); - -/* - * NAME curl_mime_addpart() - * - * DESCRIPTION - * - * Append a new empty part to the given mime context and return a handle to - * the created part. - */ -CURL_EXTERN curl_mimepart *curl_mime_addpart(curl_mime *mime); - -/* - * NAME curl_mime_name() - * - * DESCRIPTION - * - * Set mime/form part name. - */ -CURL_EXTERN CURLcode curl_mime_name(curl_mimepart *part, const char *name); - -/* - * NAME curl_mime_filename() - * - * DESCRIPTION - * - * Set mime part remote file name. - */ -CURL_EXTERN CURLcode curl_mime_filename(curl_mimepart *part, - const char *filename); - -/* - * NAME curl_mime_type() - * - * DESCRIPTION - * - * Set mime part type. - */ -CURL_EXTERN CURLcode curl_mime_type(curl_mimepart *part, const char *mimetype); - -/* - * NAME curl_mime_encoder() - * - * DESCRIPTION - * - * Set mime data transfer encoder. - */ -CURL_EXTERN CURLcode curl_mime_encoder(curl_mimepart *part, - const char *encoding); - -/* - * NAME curl_mime_data() - * - * DESCRIPTION - * - * Set mime part data source from memory data, - */ -CURL_EXTERN CURLcode curl_mime_data(curl_mimepart *part, - const char *data, size_t datasize); - -/* - * NAME curl_mime_filedata() - * - * DESCRIPTION - * - * Set mime part data source from named file. - */ -CURL_EXTERN CURLcode curl_mime_filedata(curl_mimepart *part, - const char *filename); - -/* - * NAME curl_mime_data_cb() - * - * DESCRIPTION - * - * Set mime part data source from callback function. - */ -CURL_EXTERN CURLcode curl_mime_data_cb(curl_mimepart *part, - curl_off_t datasize, - curl_read_callback readfunc, - curl_seek_callback seekfunc, - curl_free_callback freefunc, - void *arg); - -/* - * NAME curl_mime_subparts() - * - * DESCRIPTION - * - * Set mime part data source from subparts. - */ -CURL_EXTERN CURLcode curl_mime_subparts(curl_mimepart *part, - curl_mime *subparts); -/* - * NAME curl_mime_headers() - * - * DESCRIPTION - * - * Set mime part headers. - */ -CURL_EXTERN CURLcode curl_mime_headers(curl_mimepart *part, - struct curl_slist *headers, - int take_ownership); - -typedef enum { - CURLFORM_NOTHING, /********* the first one is unused ************/ - CURLFORM_COPYNAME, - CURLFORM_PTRNAME, - CURLFORM_NAMELENGTH, - CURLFORM_COPYCONTENTS, - CURLFORM_PTRCONTENTS, - CURLFORM_CONTENTSLENGTH, - CURLFORM_FILECONTENT, - CURLFORM_ARRAY, - CURLFORM_OBSOLETE, - CURLFORM_FILE, - - CURLFORM_BUFFER, - CURLFORM_BUFFERPTR, - CURLFORM_BUFFERLENGTH, - - CURLFORM_CONTENTTYPE, - CURLFORM_CONTENTHEADER, - CURLFORM_FILENAME, - CURLFORM_END, - CURLFORM_OBSOLETE2, - - CURLFORM_STREAM, - CURLFORM_CONTENTLEN, /* added in 7.46.0, provide a curl_off_t length */ - - CURLFORM_LASTENTRY /* the last unused */ -} CURLformoption; - -/* structure to be used as parameter for CURLFORM_ARRAY */ -struct curl_forms { - CURLformoption option; - const char *value; -}; - -/* use this for multipart formpost building */ -/* Returns code for curl_formadd() - * - * Returns: - * CURL_FORMADD_OK on success - * CURL_FORMADD_MEMORY if the FormInfo allocation fails - * CURL_FORMADD_OPTION_TWICE if one option is given twice for one Form - * CURL_FORMADD_NULL if a null pointer was given for a char - * CURL_FORMADD_MEMORY if the allocation of a FormInfo struct failed - * CURL_FORMADD_UNKNOWN_OPTION if an unknown option was used - * CURL_FORMADD_INCOMPLETE if the some FormInfo is not complete (or error) - * CURL_FORMADD_MEMORY if a curl_httppost struct cannot be allocated - * CURL_FORMADD_MEMORY if some allocation for string copying failed. - * CURL_FORMADD_ILLEGAL_ARRAY if an illegal option is used in an array - * - ***************************************************************************/ -typedef enum { - CURL_FORMADD_OK, /* first, no error */ - - CURL_FORMADD_MEMORY, - CURL_FORMADD_OPTION_TWICE, - CURL_FORMADD_NULL, - CURL_FORMADD_UNKNOWN_OPTION, - CURL_FORMADD_INCOMPLETE, - CURL_FORMADD_ILLEGAL_ARRAY, - CURL_FORMADD_DISABLED, /* libcurl was built with this disabled */ - - CURL_FORMADD_LAST /* last */ -} CURLFORMcode; - -/* - * NAME curl_formadd() - * - * DESCRIPTION - * - * Pretty advanced function for building multi-part formposts. Each invoke - * adds one part that together construct a full post. Then use - * CURLOPT_HTTPPOST to send it off to libcurl. - */ -CURL_EXTERN CURLFORMcode curl_formadd(struct curl_httppost **httppost, - struct curl_httppost **last_post, - ...); - -/* - * callback function for curl_formget() - * The void *arg pointer will be the one passed as second argument to - * curl_formget(). - * The character buffer passed to it must not be freed. - * Should return the buffer length passed to it as the argument "len" on - * success. - */ -typedef size_t (*curl_formget_callback)(void *arg, const char *buf, - size_t len); - -/* - * NAME curl_formget() - * - * DESCRIPTION - * - * Serialize a curl_httppost struct built with curl_formadd(). - * Accepts a void pointer as second argument which will be passed to - * the curl_formget_callback function. - * Returns 0 on success. - */ -CURL_EXTERN int curl_formget(struct curl_httppost *form, void *arg, - curl_formget_callback append); -/* - * NAME curl_formfree() - * - * DESCRIPTION - * - * Free a multipart formpost previously built with curl_formadd(). - */ -CURL_EXTERN void curl_formfree(struct curl_httppost *form); - -/* - * NAME curl_getenv() - * - * DESCRIPTION - * - * Returns a malloc()'ed string that MUST be curl_free()ed after usage is - * complete. DEPRECATED - see lib/README.curlx - */ -CURL_EXTERN char *curl_getenv(const char *variable); - -/* - * NAME curl_version() - * - * DESCRIPTION - * - * Returns a static ascii string of the libcurl version. - */ -CURL_EXTERN char *curl_version(void); - -/* - * NAME curl_easy_escape() - * - * DESCRIPTION - * - * Escapes URL strings (converts all letters consider illegal in URLs to their - * %XX versions). This function returns a new allocated string or NULL if an - * error occurred. - */ -CURL_EXTERN char *curl_easy_escape(CURL *handle, - const char *string, - int length); - -/* the previous version: */ -CURL_EXTERN char *curl_escape(const char *string, - int length); - - -/* - * NAME curl_easy_unescape() - * - * DESCRIPTION - * - * Unescapes URL encoding in strings (converts all %XX codes to their 8bit - * versions). This function returns a new allocated string or NULL if an error - * occurred. - * Conversion Note: On non-ASCII platforms the ASCII %XX codes are - * converted into the host encoding. - */ -CURL_EXTERN char *curl_easy_unescape(CURL *handle, - const char *string, - int length, - int *outlength); - -/* the previous version */ -CURL_EXTERN char *curl_unescape(const char *string, - int length); - -/* - * NAME curl_free() - * - * DESCRIPTION - * - * Provided for de-allocation in the same translation unit that did the - * allocation. Added in libcurl 7.10 - */ -CURL_EXTERN void curl_free(void *p); - -/* - * NAME curl_global_init() - * - * DESCRIPTION - * - * curl_global_init() should be invoked exactly once for each application that - * uses libcurl and before any call of other libcurl functions. - - * This function is thread-safe if CURL_VERSION_THREADSAFE is set in the - * curl_version_info_data.features flag (fetch by curl_version_info()). - - */ -CURL_EXTERN CURLcode curl_global_init(long flags); - -/* - * NAME curl_global_init_mem() - * - * DESCRIPTION - * - * curl_global_init() or curl_global_init_mem() should be invoked exactly once - * for each application that uses libcurl. This function can be used to - * initialize libcurl and set user defined memory management callback - * functions. Users can implement memory management routines to check for - * memory leaks, check for mis-use of the curl library etc. User registered - * callback routines will be invoked by this library instead of the system - * memory management routines like malloc, free etc. - */ -CURL_EXTERN CURLcode curl_global_init_mem(long flags, - curl_malloc_callback m, - curl_free_callback f, - curl_realloc_callback r, - curl_strdup_callback s, - curl_calloc_callback c); - -/* - * NAME curl_global_cleanup() - * - * DESCRIPTION - * - * curl_global_cleanup() should be invoked exactly once for each application - * that uses libcurl - */ -CURL_EXTERN void curl_global_cleanup(void); - -/* linked-list structure for the CURLOPT_QUOTE option (and other) */ -struct curl_slist { - char *data; - struct curl_slist *next; -}; - -/* - * NAME curl_global_sslset() - * - * DESCRIPTION - * - * When built with multiple SSL backends, curl_global_sslset() allows to - * choose one. This function can only be called once, and it must be called - * *before* curl_global_init(). - * - * The backend can be identified by the id (e.g. CURLSSLBACKEND_OPENSSL). The - * backend can also be specified via the name parameter (passing -1 as id). - * If both id and name are specified, the name will be ignored. If neither id - * nor name are specified, the function will fail with - * CURLSSLSET_UNKNOWN_BACKEND and set the "avail" pointer to the - * NULL-terminated list of available backends. - * - * Upon success, the function returns CURLSSLSET_OK. - * - * If the specified SSL backend is not available, the function returns - * CURLSSLSET_UNKNOWN_BACKEND and sets the "avail" pointer to a NULL-terminated - * list of available SSL backends. - * - * The SSL backend can be set only once. If it has already been set, a - * subsequent attempt to change it will result in a CURLSSLSET_TOO_LATE. - */ - -struct curl_ssl_backend { - curl_sslbackend id; - const char *name; -}; -typedef struct curl_ssl_backend curl_ssl_backend; - -typedef enum { - CURLSSLSET_OK = 0, - CURLSSLSET_UNKNOWN_BACKEND, - CURLSSLSET_TOO_LATE, - CURLSSLSET_NO_BACKENDS /* libcurl was built without any SSL support */ -} CURLsslset; - -CURL_EXTERN CURLsslset curl_global_sslset(curl_sslbackend id, const char *name, - const curl_ssl_backend ***avail); - -/* - * NAME curl_slist_append() - * - * DESCRIPTION - * - * Appends a string to a linked list. If no list exists, it will be created - * first. Returns the new list, after appending. - */ -CURL_EXTERN struct curl_slist *curl_slist_append(struct curl_slist *, - const char *); - -/* - * NAME curl_slist_free_all() - * - * DESCRIPTION - * - * free a previously built curl_slist. - */ -CURL_EXTERN void curl_slist_free_all(struct curl_slist *); - -/* - * NAME curl_getdate() - * - * DESCRIPTION - * - * Returns the time, in seconds since 1 Jan 1970 of the time string given in - * the first argument. The time argument in the second parameter is unused - * and should be set to NULL. - */ -CURL_EXTERN time_t curl_getdate(const char *p, const time_t *unused); - -/* info about the certificate chain, only for OpenSSL, GnuTLS, Schannel, NSS - and GSKit builds. Asked for with CURLOPT_CERTINFO / CURLINFO_CERTINFO */ -struct curl_certinfo { - int num_of_certs; /* number of certificates with information */ - struct curl_slist **certinfo; /* for each index in this array, there's a - linked list with textual information in the - format "name: value" */ -}; - -/* Information about the SSL library used and the respective internal SSL - handle, which can be used to obtain further information regarding the - connection. Asked for with CURLINFO_TLS_SSL_PTR or CURLINFO_TLS_SESSION. */ -struct curl_tlssessioninfo { - curl_sslbackend backend; - void *internals; -}; - -#define CURLINFO_STRING 0x100000 -#define CURLINFO_LONG 0x200000 -#define CURLINFO_DOUBLE 0x300000 -#define CURLINFO_SLIST 0x400000 -#define CURLINFO_PTR 0x400000 /* same as SLIST */ -#define CURLINFO_SOCKET 0x500000 -#define CURLINFO_OFF_T 0x600000 -#define CURLINFO_MASK 0x0fffff -#define CURLINFO_TYPEMASK 0xf00000 - -typedef enum { - CURLINFO_NONE, /* first, never use this */ - CURLINFO_EFFECTIVE_URL = CURLINFO_STRING + 1, - CURLINFO_RESPONSE_CODE = CURLINFO_LONG + 2, - CURLINFO_TOTAL_TIME = CURLINFO_DOUBLE + 3, - CURLINFO_NAMELOOKUP_TIME = CURLINFO_DOUBLE + 4, - CURLINFO_CONNECT_TIME = CURLINFO_DOUBLE + 5, - CURLINFO_PRETRANSFER_TIME = CURLINFO_DOUBLE + 6, - CURLINFO_SIZE_UPLOAD = CURLINFO_DOUBLE + 7, - CURLINFO_SIZE_UPLOAD_T = CURLINFO_OFF_T + 7, - CURLINFO_SIZE_DOWNLOAD = CURLINFO_DOUBLE + 8, - CURLINFO_SIZE_DOWNLOAD_T = CURLINFO_OFF_T + 8, - CURLINFO_SPEED_DOWNLOAD = CURLINFO_DOUBLE + 9, - CURLINFO_SPEED_DOWNLOAD_T = CURLINFO_OFF_T + 9, - CURLINFO_SPEED_UPLOAD = CURLINFO_DOUBLE + 10, - CURLINFO_SPEED_UPLOAD_T = CURLINFO_OFF_T + 10, - CURLINFO_HEADER_SIZE = CURLINFO_LONG + 11, - CURLINFO_REQUEST_SIZE = CURLINFO_LONG + 12, - CURLINFO_SSL_VERIFYRESULT = CURLINFO_LONG + 13, - CURLINFO_FILETIME = CURLINFO_LONG + 14, - CURLINFO_FILETIME_T = CURLINFO_OFF_T + 14, - CURLINFO_CONTENT_LENGTH_DOWNLOAD = CURLINFO_DOUBLE + 15, - CURLINFO_CONTENT_LENGTH_DOWNLOAD_T = CURLINFO_OFF_T + 15, - CURLINFO_CONTENT_LENGTH_UPLOAD = CURLINFO_DOUBLE + 16, - CURLINFO_CONTENT_LENGTH_UPLOAD_T = CURLINFO_OFF_T + 16, - CURLINFO_STARTTRANSFER_TIME = CURLINFO_DOUBLE + 17, - CURLINFO_CONTENT_TYPE = CURLINFO_STRING + 18, - CURLINFO_REDIRECT_TIME = CURLINFO_DOUBLE + 19, - CURLINFO_REDIRECT_COUNT = CURLINFO_LONG + 20, - CURLINFO_PRIVATE = CURLINFO_STRING + 21, - CURLINFO_HTTP_CONNECTCODE = CURLINFO_LONG + 22, - CURLINFO_HTTPAUTH_AVAIL = CURLINFO_LONG + 23, - CURLINFO_PROXYAUTH_AVAIL = CURLINFO_LONG + 24, - CURLINFO_OS_ERRNO = CURLINFO_LONG + 25, - CURLINFO_NUM_CONNECTS = CURLINFO_LONG + 26, - CURLINFO_SSL_ENGINES = CURLINFO_SLIST + 27, - CURLINFO_COOKIELIST = CURLINFO_SLIST + 28, - CURLINFO_LASTSOCKET = CURLINFO_LONG + 29, - CURLINFO_FTP_ENTRY_PATH = CURLINFO_STRING + 30, - CURLINFO_REDIRECT_URL = CURLINFO_STRING + 31, - CURLINFO_PRIMARY_IP = CURLINFO_STRING + 32, - CURLINFO_APPCONNECT_TIME = CURLINFO_DOUBLE + 33, - CURLINFO_CERTINFO = CURLINFO_PTR + 34, - CURLINFO_CONDITION_UNMET = CURLINFO_LONG + 35, - CURLINFO_RTSP_SESSION_ID = CURLINFO_STRING + 36, - CURLINFO_RTSP_CLIENT_CSEQ = CURLINFO_LONG + 37, - CURLINFO_RTSP_SERVER_CSEQ = CURLINFO_LONG + 38, - CURLINFO_RTSP_CSEQ_RECV = CURLINFO_LONG + 39, - CURLINFO_PRIMARY_PORT = CURLINFO_LONG + 40, - CURLINFO_LOCAL_IP = CURLINFO_STRING + 41, - CURLINFO_LOCAL_PORT = CURLINFO_LONG + 42, - CURLINFO_TLS_SESSION = CURLINFO_PTR + 43, - CURLINFO_ACTIVESOCKET = CURLINFO_SOCKET + 44, - CURLINFO_TLS_SSL_PTR = CURLINFO_PTR + 45, - CURLINFO_HTTP_VERSION = CURLINFO_LONG + 46, - CURLINFO_PROXY_SSL_VERIFYRESULT = CURLINFO_LONG + 47, - CURLINFO_PROTOCOL = CURLINFO_LONG + 48, - CURLINFO_SCHEME = CURLINFO_STRING + 49, - CURLINFO_TOTAL_TIME_T = CURLINFO_OFF_T + 50, - CURLINFO_NAMELOOKUP_TIME_T = CURLINFO_OFF_T + 51, - CURLINFO_CONNECT_TIME_T = CURLINFO_OFF_T + 52, - CURLINFO_PRETRANSFER_TIME_T = CURLINFO_OFF_T + 53, - CURLINFO_STARTTRANSFER_TIME_T = CURLINFO_OFF_T + 54, - CURLINFO_REDIRECT_TIME_T = CURLINFO_OFF_T + 55, - CURLINFO_APPCONNECT_TIME_T = CURLINFO_OFF_T + 56, - CURLINFO_RETRY_AFTER = CURLINFO_OFF_T + 57, - CURLINFO_EFFECTIVE_METHOD = CURLINFO_STRING + 58, - CURLINFO_PROXY_ERROR = CURLINFO_LONG + 59, - CURLINFO_REFERER = CURLINFO_STRING + 60, - CURLINFO_CAINFO = CURLINFO_STRING + 61, - CURLINFO_CAPATH = CURLINFO_STRING + 62, - CURLINFO_LASTONE = 62 -} CURLINFO; - -/* CURLINFO_RESPONSE_CODE is the new name for the option previously known as - CURLINFO_HTTP_CODE */ -#define CURLINFO_HTTP_CODE CURLINFO_RESPONSE_CODE - -typedef enum { - CURLCLOSEPOLICY_NONE, /* first, never use this */ - - CURLCLOSEPOLICY_OLDEST, - CURLCLOSEPOLICY_LEAST_RECENTLY_USED, - CURLCLOSEPOLICY_LEAST_TRAFFIC, - CURLCLOSEPOLICY_SLOWEST, - CURLCLOSEPOLICY_CALLBACK, - - CURLCLOSEPOLICY_LAST /* last, never use this */ -} curl_closepolicy; - -#define CURL_GLOBAL_SSL (1<<0) /* no purpose since 7.57.0 */ -#define CURL_GLOBAL_WIN32 (1<<1) -#define CURL_GLOBAL_ALL (CURL_GLOBAL_SSL|CURL_GLOBAL_WIN32) -#define CURL_GLOBAL_NOTHING 0 -#define CURL_GLOBAL_DEFAULT CURL_GLOBAL_ALL -#define CURL_GLOBAL_ACK_EINTR (1<<2) - - -/***************************************************************************** - * Setup defines, protos etc for the sharing stuff. - */ - -/* Different data locks for a single share */ -typedef enum { - CURL_LOCK_DATA_NONE = 0, - /* CURL_LOCK_DATA_SHARE is used internally to say that - * the locking is just made to change the internal state of the share - * itself. - */ - CURL_LOCK_DATA_SHARE, - CURL_LOCK_DATA_COOKIE, - CURL_LOCK_DATA_DNS, - CURL_LOCK_DATA_SSL_SESSION, - CURL_LOCK_DATA_CONNECT, - CURL_LOCK_DATA_PSL, - CURL_LOCK_DATA_LAST -} curl_lock_data; - -/* Different lock access types */ -typedef enum { - CURL_LOCK_ACCESS_NONE = 0, /* unspecified action */ - CURL_LOCK_ACCESS_SHARED = 1, /* for read perhaps */ - CURL_LOCK_ACCESS_SINGLE = 2, /* for write perhaps */ - CURL_LOCK_ACCESS_LAST /* never use */ -} curl_lock_access; - -typedef void (*curl_lock_function)(CURL *handle, - curl_lock_data data, - curl_lock_access locktype, - void *userptr); -typedef void (*curl_unlock_function)(CURL *handle, - curl_lock_data data, - void *userptr); - - -typedef enum { - CURLSHE_OK, /* all is fine */ - CURLSHE_BAD_OPTION, /* 1 */ - CURLSHE_IN_USE, /* 2 */ - CURLSHE_INVALID, /* 3 */ - CURLSHE_NOMEM, /* 4 out of memory */ - CURLSHE_NOT_BUILT_IN, /* 5 feature not present in lib */ - CURLSHE_LAST /* never use */ -} CURLSHcode; - -typedef enum { - CURLSHOPT_NONE, /* don't use */ - CURLSHOPT_SHARE, /* specify a data type to share */ - CURLSHOPT_UNSHARE, /* specify which data type to stop sharing */ - CURLSHOPT_LOCKFUNC, /* pass in a 'curl_lock_function' pointer */ - CURLSHOPT_UNLOCKFUNC, /* pass in a 'curl_unlock_function' pointer */ - CURLSHOPT_USERDATA, /* pass in a user data pointer used in the lock/unlock - callback functions */ - CURLSHOPT_LAST /* never use */ -} CURLSHoption; - -CURL_EXTERN CURLSH *curl_share_init(void); -CURL_EXTERN CURLSHcode curl_share_setopt(CURLSH *, CURLSHoption option, ...); -CURL_EXTERN CURLSHcode curl_share_cleanup(CURLSH *); - -/**************************************************************************** - * Structures for querying information about the curl library at runtime. - */ - -typedef enum { - CURLVERSION_FIRST, - CURLVERSION_SECOND, - CURLVERSION_THIRD, - CURLVERSION_FOURTH, - CURLVERSION_FIFTH, - CURLVERSION_SIXTH, - CURLVERSION_SEVENTH, - CURLVERSION_EIGHTH, - CURLVERSION_NINTH, - CURLVERSION_TENTH, - CURLVERSION_LAST /* never actually use this */ -} CURLversion; - -/* The 'CURLVERSION_NOW' is the symbolic name meant to be used by - basically all programs ever that want to get version information. It is - meant to be a built-in version number for what kind of struct the caller - expects. If the struct ever changes, we redefine the NOW to another enum - from above. */ -#define CURLVERSION_NOW CURLVERSION_TENTH - -struct curl_version_info_data { - CURLversion age; /* age of the returned struct */ - const char *version; /* LIBCURL_VERSION */ - unsigned int version_num; /* LIBCURL_VERSION_NUM */ - const char *host; /* OS/host/cpu/machine when configured */ - int features; /* bitmask, see defines below */ - const char *ssl_version; /* human readable string */ - long ssl_version_num; /* not used anymore, always 0 */ - const char *libz_version; /* human readable string */ - /* protocols is terminated by an entry with a NULL protoname */ - const char * const *protocols; - - /* The fields below this were added in CURLVERSION_SECOND */ - const char *ares; - int ares_num; - - /* This field was added in CURLVERSION_THIRD */ - const char *libidn; - - /* These field were added in CURLVERSION_FOURTH */ - - /* Same as '_libiconv_version' if built with HAVE_ICONV */ - int iconv_ver_num; - - const char *libssh_version; /* human readable string */ - - /* These fields were added in CURLVERSION_FIFTH */ - unsigned int brotli_ver_num; /* Numeric Brotli version - (MAJOR << 24) | (MINOR << 12) | PATCH */ - const char *brotli_version; /* human readable string. */ - - /* These fields were added in CURLVERSION_SIXTH */ - unsigned int nghttp2_ver_num; /* Numeric nghttp2 version - (MAJOR << 16) | (MINOR << 8) | PATCH */ - const char *nghttp2_version; /* human readable string. */ - const char *quic_version; /* human readable quic (+ HTTP/3) library + - version or NULL */ - - /* These fields were added in CURLVERSION_SEVENTH */ - const char *cainfo; /* the built-in default CURLOPT_CAINFO, might - be NULL */ - const char *capath; /* the built-in default CURLOPT_CAPATH, might - be NULL */ - - /* These fields were added in CURLVERSION_EIGHTH */ - unsigned int zstd_ver_num; /* Numeric Zstd version - (MAJOR << 24) | (MINOR << 12) | PATCH */ - const char *zstd_version; /* human readable string. */ - - /* These fields were added in CURLVERSION_NINTH */ - const char *hyper_version; /* human readable string. */ - - /* These fields were added in CURLVERSION_TENTH */ - const char *gsasl_version; /* human readable string. */ -}; -typedef struct curl_version_info_data curl_version_info_data; - -#define CURL_VERSION_IPV6 (1<<0) /* IPv6-enabled */ -#define CURL_VERSION_KERBEROS4 (1<<1) /* Kerberos V4 auth is supported - (deprecated) */ -#define CURL_VERSION_SSL (1<<2) /* SSL options are present */ -#define CURL_VERSION_LIBZ (1<<3) /* libz features are present */ -#define CURL_VERSION_NTLM (1<<4) /* NTLM auth is supported */ -#define CURL_VERSION_GSSNEGOTIATE (1<<5) /* Negotiate auth is supported - (deprecated) */ -#define CURL_VERSION_DEBUG (1<<6) /* Built with debug capabilities */ -#define CURL_VERSION_ASYNCHDNS (1<<7) /* Asynchronous DNS resolves */ -#define CURL_VERSION_SPNEGO (1<<8) /* SPNEGO auth is supported */ -#define CURL_VERSION_LARGEFILE (1<<9) /* Supports files larger than 2GB */ -#define CURL_VERSION_IDN (1<<10) /* Internationized Domain Names are - supported */ -#define CURL_VERSION_SSPI (1<<11) /* Built against Windows SSPI */ -#define CURL_VERSION_CONV (1<<12) /* Character conversions supported */ -#define CURL_VERSION_CURLDEBUG (1<<13) /* Debug memory tracking supported */ -#define CURL_VERSION_TLSAUTH_SRP (1<<14) /* TLS-SRP auth is supported */ -#define CURL_VERSION_NTLM_WB (1<<15) /* NTLM delegation to winbind helper - is supported */ -#define CURL_VERSION_HTTP2 (1<<16) /* HTTP2 support built-in */ -#define CURL_VERSION_GSSAPI (1<<17) /* Built against a GSS-API library */ -#define CURL_VERSION_KERBEROS5 (1<<18) /* Kerberos V5 auth is supported */ -#define CURL_VERSION_UNIX_SOCKETS (1<<19) /* Unix domain sockets support */ -#define CURL_VERSION_PSL (1<<20) /* Mozilla's Public Suffix List, used - for cookie domain verification */ -#define CURL_VERSION_HTTPS_PROXY (1<<21) /* HTTPS-proxy support built-in */ -#define CURL_VERSION_MULTI_SSL (1<<22) /* Multiple SSL backends available */ -#define CURL_VERSION_BROTLI (1<<23) /* Brotli features are present. */ -#define CURL_VERSION_ALTSVC (1<<24) /* Alt-Svc handling built-in */ -#define CURL_VERSION_HTTP3 (1<<25) /* HTTP3 support built-in */ -#define CURL_VERSION_ZSTD (1<<26) /* zstd features are present */ -#define CURL_VERSION_UNICODE (1<<27) /* Unicode support on Windows */ -#define CURL_VERSION_HSTS (1<<28) /* HSTS is supported */ -#define CURL_VERSION_GSASL (1<<29) /* libgsasl is supported */ -#define CURL_VERSION_THREADSAFE (1<<30) /* libcurl API is thread-safe */ - - /* - * NAME curl_version_info() - * - * DESCRIPTION - * - * This function returns a pointer to a static copy of the version info - * struct. See above. - */ -CURL_EXTERN curl_version_info_data *curl_version_info(CURLversion); - -/* - * NAME curl_easy_strerror() - * - * DESCRIPTION - * - * The curl_easy_strerror function may be used to turn a CURLcode value - * into the equivalent human readable error string. This is useful - * for printing meaningful error messages. - */ -CURL_EXTERN const char *curl_easy_strerror(CURLcode); - -/* - * NAME curl_share_strerror() - * - * DESCRIPTION - * - * The curl_share_strerror function may be used to turn a CURLSHcode value - * into the equivalent human readable error string. This is useful - * for printing meaningful error messages. - */ -CURL_EXTERN const char *curl_share_strerror(CURLSHcode); - -/* - * NAME curl_easy_pause() - * - * DESCRIPTION - * - * The curl_easy_pause function pauses or unpauses transfers. Select the new - * state by setting the bitmask, use the convenience defines below. - * - */ -CURL_EXTERN CURLcode curl_easy_pause(CURL *handle, int bitmask); - -#define CURLPAUSE_RECV (1<<0) -#define CURLPAUSE_RECV_CONT (0) - -#define CURLPAUSE_SEND (1<<2) -#define CURLPAUSE_SEND_CONT (0) - -#define CURLPAUSE_ALL (CURLPAUSE_RECV|CURLPAUSE_SEND) -#define CURLPAUSE_CONT (CURLPAUSE_RECV_CONT|CURLPAUSE_SEND_CONT) - -#ifdef __cplusplus -} -#endif - -/* unfortunately, the easy.h and multi.h include files need options and info - stuff before they can be included! */ -#include "easy.h" /* nothing in curl is fun without the easy stuff */ -#include "multi.h" -#include "urlapi.h" -#include "options.h" -#include "header.h" - -/* the typechecker doesn't work in C++ (yet) */ -#if defined(__GNUC__) && defined(__GNUC_MINOR__) && \ - ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) && \ - !defined(__cplusplus) && !defined(CURL_DISABLE_TYPECHECK) -#include "typecheck-gcc.h" -#else -#if defined(__STDC__) && (__STDC__ >= 1) -/* This preprocessor magic that replaces a call with the exact same call is - only done to make sure application authors pass exactly three arguments - to these functions. */ -#define curl_easy_setopt(handle,opt,param) curl_easy_setopt(handle,opt,param) -#define curl_easy_getinfo(handle,info,arg) curl_easy_getinfo(handle,info,arg) -#define curl_share_setopt(share,opt,param) curl_share_setopt(share,opt,param) -#define curl_multi_setopt(handle,opt,param) curl_multi_setopt(handle,opt,param) -#endif /* __STDC__ >= 1 */ -#endif /* gcc >= 4.3 && !__cplusplus */ - -#endif /* CURLINC_CURL_H */ diff --git a/ktor-client/ktor-client-curl/desktop/interop/mingwX64/include/curl/curlver.h b/ktor-client/ktor-client-curl/desktop/interop/mingwX64/include/curl/curlver.h deleted file mode 100644 index a21446e3468..00000000000 --- a/ktor-client/ktor-client-curl/desktop/interop/mingwX64/include/curl/curlver.h +++ /dev/null @@ -1,79 +0,0 @@ -#ifndef CURLINC_CURLVER_H -#define CURLINC_CURLVER_H -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 1998 - 2022, Daniel Stenberg, , et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at https://curl.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - * SPDX-License-Identifier: curl - * - ***************************************************************************/ - -/* This header file contains nothing but libcurl version info, generated by - a script at release-time. This was made its own header file in 7.11.2 */ - -/* This is the global package copyright */ -#define LIBCURL_COPYRIGHT "1996 - 2022 Daniel Stenberg, ." - -/* This is the version number of the libcurl package from which this header - file origins: */ -#define LIBCURL_VERSION "7.84.0" - -/* The numeric version number is also available "in parts" by using these - defines: */ -#define LIBCURL_VERSION_MAJOR 7 -#define LIBCURL_VERSION_MINOR 84 -#define LIBCURL_VERSION_PATCH 0 - -/* This is the numeric version of the libcurl version number, meant for easier - parsing and comparisons by programs. The LIBCURL_VERSION_NUM define will - always follow this syntax: - - 0xXXYYZZ - - Where XX, YY and ZZ are the main version, release and patch numbers in - hexadecimal (using 8 bits each). All three numbers are always represented - using two digits. 1.2 would appear as "0x010200" while version 9.11.7 - appears as "0x090b07". - - This 6-digit (24 bits) hexadecimal number does not show pre-release number, - and it is always a greater number in a more recent release. It makes - comparisons with greater than and less than work. - - Note: This define is the full hex number and _does not_ use the - CURL_VERSION_BITS() macro since curl's own configure script greps for it - and needs it to contain the full number. -*/ -#define LIBCURL_VERSION_NUM 0x075400 - -/* - * This is the date and time when the full source package was created. The - * timestamp is not stored in git, as the timestamp is properly set in the - * tarballs by the maketgz script. - * - * The format of the date follows this template: - * - * "2007-11-23" - */ -#define LIBCURL_TIMESTAMP "2022-06-27" - -#define CURL_VERSION_BITS(x,y,z) ((x)<<16|(y)<<8|(z)) -#define CURL_AT_LEAST_VERSION(x,y,z) \ - (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS(x, y, z)) - -#endif /* CURLINC_CURLVER_H */ diff --git a/ktor-client/ktor-client-curl/desktop/interop/mingwX64/include/curl/easy.h b/ktor-client/ktor-client-curl/desktop/interop/mingwX64/include/curl/easy.h deleted file mode 100644 index 9c7e63adad6..00000000000 --- a/ktor-client/ktor-client-curl/desktop/interop/mingwX64/include/curl/easy.h +++ /dev/null @@ -1,125 +0,0 @@ -#ifndef CURLINC_EASY_H -#define CURLINC_EASY_H -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 1998 - 2022, Daniel Stenberg, , et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at https://curl.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - * SPDX-License-Identifier: curl - * - ***************************************************************************/ -#ifdef __cplusplus -extern "C" { -#endif - -/* Flag bits in the curl_blob struct: */ -#define CURL_BLOB_COPY 1 /* tell libcurl to copy the data */ -#define CURL_BLOB_NOCOPY 0 /* tell libcurl to NOT copy the data */ - -struct curl_blob { - void *data; - size_t len; - unsigned int flags; /* bit 0 is defined, the rest are reserved and should be - left zeroes */ -}; - -CURL_EXTERN CURL *curl_easy_init(void); -CURL_EXTERN CURLcode curl_easy_setopt(CURL *curl, CURLoption option, ...); -CURL_EXTERN CURLcode curl_easy_perform(CURL *curl); -CURL_EXTERN void curl_easy_cleanup(CURL *curl); - -/* - * NAME curl_easy_getinfo() - * - * DESCRIPTION - * - * Request internal information from the curl session with this function. The - * third argument MUST be a pointer to a long, a pointer to a char * or a - * pointer to a double (as the documentation describes elsewhere). The data - * pointed to will be filled in accordingly and can be relied upon only if the - * function returns CURLE_OK. This function is intended to get used *AFTER* a - * performed transfer, all results from this function are undefined until the - * transfer is completed. - */ -CURL_EXTERN CURLcode curl_easy_getinfo(CURL *curl, CURLINFO info, ...); - - -/* - * NAME curl_easy_duphandle() - * - * DESCRIPTION - * - * Creates a new curl session handle with the same options set for the handle - * passed in. Duplicating a handle could only be a matter of cloning data and - * options, internal state info and things like persistent connections cannot - * be transferred. It is useful in multithreaded applications when you can run - * curl_easy_duphandle() for each new thread to avoid a series of identical - * curl_easy_setopt() invokes in every thread. - */ -CURL_EXTERN CURL *curl_easy_duphandle(CURL *curl); - -/* - * NAME curl_easy_reset() - * - * DESCRIPTION - * - * Re-initializes a CURL handle to the default values. This puts back the - * handle to the same state as it was in when it was just created. - * - * It does keep: live connections, the Session ID cache, the DNS cache and the - * cookies. - */ -CURL_EXTERN void curl_easy_reset(CURL *curl); - -/* - * NAME curl_easy_recv() - * - * DESCRIPTION - * - * Receives data from the connected socket. Use after successful - * curl_easy_perform() with CURLOPT_CONNECT_ONLY option. - */ -CURL_EXTERN CURLcode curl_easy_recv(CURL *curl, void *buffer, size_t buflen, - size_t *n); - -/* - * NAME curl_easy_send() - * - * DESCRIPTION - * - * Sends data over the connected socket. Use after successful - * curl_easy_perform() with CURLOPT_CONNECT_ONLY option. - */ -CURL_EXTERN CURLcode curl_easy_send(CURL *curl, const void *buffer, - size_t buflen, size_t *n); - - -/* - * NAME curl_easy_upkeep() - * - * DESCRIPTION - * - * Performs connection upkeep for the given session handle. - */ -CURL_EXTERN CURLcode curl_easy_upkeep(CURL *curl); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/ktor-client/ktor-client-curl/desktop/interop/mingwX64/include/curl/header.h b/ktor-client/ktor-client-curl/desktop/interop/mingwX64/include/curl/header.h deleted file mode 100644 index 6af29c0c0a4..00000000000 --- a/ktor-client/ktor-client-curl/desktop/interop/mingwX64/include/curl/header.h +++ /dev/null @@ -1,66 +0,0 @@ -#ifndef CURLINC_HEADER_H -#define CURLINC_HEADER_H -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 2018 - 2022, Daniel Stenberg, , et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at https://curl.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - * SPDX-License-Identifier: curl - * - ***************************************************************************/ - -struct curl_header { - char *name; /* this might not use the same case */ - char *value; - size_t amount; /* number of headers using this name */ - size_t index; /* ... of this instance, 0 or higher */ - unsigned int origin; /* see bits below */ - void *anchor; /* handle privately used by libcurl */ -}; - -/* 'origin' bits */ -#define CURLH_HEADER (1<<0) /* plain server header */ -#define CURLH_TRAILER (1<<1) /* trailers */ -#define CURLH_CONNECT (1<<2) /* CONNECT headers */ -#define CURLH_1XX (1<<3) /* 1xx headers */ -#define CURLH_PSEUDO (1<<4) /* pseudo headers */ - -typedef enum { - CURLHE_OK, - CURLHE_BADINDEX, /* header exists but not with this index */ - CURLHE_MISSING, /* no such header exists */ - CURLHE_NOHEADERS, /* no headers at all exist (yet) */ - CURLHE_NOREQUEST, /* no request with this number was used */ - CURLHE_OUT_OF_MEMORY, /* out of memory while processing */ - CURLHE_BAD_ARGUMENT, /* a function argument was not okay */ - CURLHE_NOT_BUILT_IN /* if API was disabled in the build */ -} CURLHcode; - -CURL_EXTERN CURLHcode curl_easy_header(CURL *easy, - const char *name, - size_t index, - unsigned int origin, - int request, - struct curl_header **hout); - -CURL_EXTERN struct curl_header *curl_easy_nextheader(CURL *easy, - unsigned int origin, - int request, - struct curl_header *prev); - -#endif /* CURLINC_HEADER_H */ diff --git a/ktor-client/ktor-client-curl/desktop/interop/mingwX64/include/curl/mprintf.h b/ktor-client/ktor-client-curl/desktop/interop/mingwX64/include/curl/mprintf.h deleted file mode 100644 index cb948dcd97b..00000000000 --- a/ktor-client/ktor-client-curl/desktop/interop/mingwX64/include/curl/mprintf.h +++ /dev/null @@ -1,52 +0,0 @@ -#ifndef CURLINC_MPRINTF_H -#define CURLINC_MPRINTF_H -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 1998 - 2022, Daniel Stenberg, , et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at https://curl.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - * SPDX-License-Identifier: curl - * - ***************************************************************************/ - -#include -#include /* needed for FILE */ -#include "curl.h" /* for CURL_EXTERN */ - -#ifdef __cplusplus -extern "C" { -#endif - -CURL_EXTERN int curl_mprintf(const char *format, ...); -CURL_EXTERN int curl_mfprintf(FILE *fd, const char *format, ...); -CURL_EXTERN int curl_msprintf(char *buffer, const char *format, ...); -CURL_EXTERN int curl_msnprintf(char *buffer, size_t maxlength, - const char *format, ...); -CURL_EXTERN int curl_mvprintf(const char *format, va_list args); -CURL_EXTERN int curl_mvfprintf(FILE *fd, const char *format, va_list args); -CURL_EXTERN int curl_mvsprintf(char *buffer, const char *format, va_list args); -CURL_EXTERN int curl_mvsnprintf(char *buffer, size_t maxlength, - const char *format, va_list args); -CURL_EXTERN char *curl_maprintf(const char *format, ...); -CURL_EXTERN char *curl_mvaprintf(const char *format, va_list args); - -#ifdef __cplusplus -} -#endif - -#endif /* CURLINC_MPRINTF_H */ diff --git a/ktor-client/ktor-client-curl/desktop/interop/mingwX64/include/curl/multi.h b/ktor-client/ktor-client-curl/desktop/interop/mingwX64/include/curl/multi.h deleted file mode 100644 index 30104925b7e..00000000000 --- a/ktor-client/ktor-client-curl/desktop/interop/mingwX64/include/curl/multi.h +++ /dev/null @@ -1,460 +0,0 @@ -#ifndef CURLINC_MULTI_H -#define CURLINC_MULTI_H -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 1998 - 2022, Daniel Stenberg, , et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at https://curl.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - * SPDX-License-Identifier: curl - * - ***************************************************************************/ -/* - This is an "external" header file. Don't give away any internals here! - - GOALS - - o Enable a "pull" interface. The application that uses libcurl decides where - and when to ask libcurl to get/send data. - - o Enable multiple simultaneous transfers in the same thread without making it - complicated for the application. - - o Enable the application to select() on its own file descriptors and curl's - file descriptors simultaneous easily. - -*/ - -/* - * This header file should not really need to include "curl.h" since curl.h - * itself includes this file and we expect user applications to do #include - * without the need for especially including multi.h. - * - * For some reason we added this include here at one point, and rather than to - * break existing (wrongly written) libcurl applications, we leave it as-is - * but with this warning attached. - */ -#include "curl.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#if defined(BUILDING_LIBCURL) || defined(CURL_STRICTER) -typedef struct Curl_multi CURLM; -#else -typedef void CURLM; -#endif - -typedef enum { - CURLM_CALL_MULTI_PERFORM = -1, /* please call curl_multi_perform() or - curl_multi_socket*() soon */ - CURLM_OK, - CURLM_BAD_HANDLE, /* the passed-in handle is not a valid CURLM handle */ - CURLM_BAD_EASY_HANDLE, /* an easy handle was not good/valid */ - CURLM_OUT_OF_MEMORY, /* if you ever get this, you're in deep sh*t */ - CURLM_INTERNAL_ERROR, /* this is a libcurl bug */ - CURLM_BAD_SOCKET, /* the passed in socket argument did not match */ - CURLM_UNKNOWN_OPTION, /* curl_multi_setopt() with unsupported option */ - CURLM_ADDED_ALREADY, /* an easy handle already added to a multi handle was - attempted to get added - again */ - CURLM_RECURSIVE_API_CALL, /* an api function was called from inside a - callback */ - CURLM_WAKEUP_FAILURE, /* wakeup is unavailable or failed */ - CURLM_BAD_FUNCTION_ARGUMENT, /* function called with a bad parameter */ - CURLM_ABORTED_BY_CALLBACK, - CURLM_UNRECOVERABLE_POLL, - CURLM_LAST -} CURLMcode; - -/* just to make code nicer when using curl_multi_socket() you can now check - for CURLM_CALL_MULTI_SOCKET too in the same style it works for - curl_multi_perform() and CURLM_CALL_MULTI_PERFORM */ -#define CURLM_CALL_MULTI_SOCKET CURLM_CALL_MULTI_PERFORM - -/* bitmask bits for CURLMOPT_PIPELINING */ -#define CURLPIPE_NOTHING 0L -#define CURLPIPE_HTTP1 1L -#define CURLPIPE_MULTIPLEX 2L - -typedef enum { - CURLMSG_NONE, /* first, not used */ - CURLMSG_DONE, /* This easy handle has completed. 'result' contains - the CURLcode of the transfer */ - CURLMSG_LAST /* last, not used */ -} CURLMSG; - -struct CURLMsg { - CURLMSG msg; /* what this message means */ - CURL *easy_handle; /* the handle it concerns */ - union { - void *whatever; /* message-specific data */ - CURLcode result; /* return code for transfer */ - } data; -}; -typedef struct CURLMsg CURLMsg; - -/* Based on poll(2) structure and values. - * We don't use pollfd and POLL* constants explicitly - * to cover platforms without poll(). */ -#define CURL_WAIT_POLLIN 0x0001 -#define CURL_WAIT_POLLPRI 0x0002 -#define CURL_WAIT_POLLOUT 0x0004 - -struct curl_waitfd { - curl_socket_t fd; - short events; - short revents; /* not supported yet */ -}; - -/* - * Name: curl_multi_init() - * - * Desc: inititalize multi-style curl usage - * - * Returns: a new CURLM handle to use in all 'curl_multi' functions. - */ -CURL_EXTERN CURLM *curl_multi_init(void); - -/* - * Name: curl_multi_add_handle() - * - * Desc: add a standard curl handle to the multi stack - * - * Returns: CURLMcode type, general multi error code. - */ -CURL_EXTERN CURLMcode curl_multi_add_handle(CURLM *multi_handle, - CURL *curl_handle); - - /* - * Name: curl_multi_remove_handle() - * - * Desc: removes a curl handle from the multi stack again - * - * Returns: CURLMcode type, general multi error code. - */ -CURL_EXTERN CURLMcode curl_multi_remove_handle(CURLM *multi_handle, - CURL *curl_handle); - - /* - * Name: curl_multi_fdset() - * - * Desc: Ask curl for its fd_set sets. The app can use these to select() or - * poll() on. We want curl_multi_perform() called as soon as one of - * them are ready. - * - * Returns: CURLMcode type, general multi error code. - */ -CURL_EXTERN CURLMcode curl_multi_fdset(CURLM *multi_handle, - fd_set *read_fd_set, - fd_set *write_fd_set, - fd_set *exc_fd_set, - int *max_fd); - -/* - * Name: curl_multi_wait() - * - * Desc: Poll on all fds within a CURLM set as well as any - * additional fds passed to the function. - * - * Returns: CURLMcode type, general multi error code. - */ -CURL_EXTERN CURLMcode curl_multi_wait(CURLM *multi_handle, - struct curl_waitfd extra_fds[], - unsigned int extra_nfds, - int timeout_ms, - int *ret); - -/* - * Name: curl_multi_poll() - * - * Desc: Poll on all fds within a CURLM set as well as any - * additional fds passed to the function. - * - * Returns: CURLMcode type, general multi error code. - */ -CURL_EXTERN CURLMcode curl_multi_poll(CURLM *multi_handle, - struct curl_waitfd extra_fds[], - unsigned int extra_nfds, - int timeout_ms, - int *ret); - -/* - * Name: curl_multi_wakeup() - * - * Desc: wakes up a sleeping curl_multi_poll call. - * - * Returns: CURLMcode type, general multi error code. - */ -CURL_EXTERN CURLMcode curl_multi_wakeup(CURLM *multi_handle); - - /* - * Name: curl_multi_perform() - * - * Desc: When the app thinks there's data available for curl it calls this - * function to read/write whatever there is right now. This returns - * as soon as the reads and writes are done. This function does not - * require that there actually is data available for reading or that - * data can be written, it can be called just in case. It returns - * the number of handles that still transfer data in the second - * argument's integer-pointer. - * - * Returns: CURLMcode type, general multi error code. *NOTE* that this only - * returns errors etc regarding the whole multi stack. There might - * still have occurred problems on individual transfers even when - * this returns OK. - */ -CURL_EXTERN CURLMcode curl_multi_perform(CURLM *multi_handle, - int *running_handles); - - /* - * Name: curl_multi_cleanup() - * - * Desc: Cleans up and removes a whole multi stack. It does not free or - * touch any individual easy handles in any way. We need to define - * in what state those handles will be if this function is called - * in the middle of a transfer. - * - * Returns: CURLMcode type, general multi error code. - */ -CURL_EXTERN CURLMcode curl_multi_cleanup(CURLM *multi_handle); - -/* - * Name: curl_multi_info_read() - * - * Desc: Ask the multi handle if there's any messages/informationals from - * the individual transfers. Messages include informationals such as - * error code from the transfer or just the fact that a transfer is - * completed. More details on these should be written down as well. - * - * Repeated calls to this function will return a new struct each - * time, until a special "end of msgs" struct is returned as a signal - * that there is no more to get at this point. - * - * The data the returned pointer points to will not survive calling - * curl_multi_cleanup(). - * - * The 'CURLMsg' struct is meant to be very simple and only contain - * very basic information. If more involved information is wanted, - * we will provide the particular "transfer handle" in that struct - * and that should/could/would be used in subsequent - * curl_easy_getinfo() calls (or similar). The point being that we - * must never expose complex structs to applications, as then we'll - * undoubtably get backwards compatibility problems in the future. - * - * Returns: A pointer to a filled-in struct, or NULL if it failed or ran out - * of structs. It also writes the number of messages left in the - * queue (after this read) in the integer the second argument points - * to. - */ -CURL_EXTERN CURLMsg *curl_multi_info_read(CURLM *multi_handle, - int *msgs_in_queue); - -/* - * Name: curl_multi_strerror() - * - * Desc: The curl_multi_strerror function may be used to turn a CURLMcode - * value into the equivalent human readable error string. This is - * useful for printing meaningful error messages. - * - * Returns: A pointer to a null-terminated error message. - */ -CURL_EXTERN const char *curl_multi_strerror(CURLMcode); - -/* - * Name: curl_multi_socket() and - * curl_multi_socket_all() - * - * Desc: An alternative version of curl_multi_perform() that allows the - * application to pass in one of the file descriptors that have been - * detected to have "action" on them and let libcurl perform. - * See man page for details. - */ -#define CURL_POLL_NONE 0 -#define CURL_POLL_IN 1 -#define CURL_POLL_OUT 2 -#define CURL_POLL_INOUT 3 -#define CURL_POLL_REMOVE 4 - -#define CURL_SOCKET_TIMEOUT CURL_SOCKET_BAD - -#define CURL_CSELECT_IN 0x01 -#define CURL_CSELECT_OUT 0x02 -#define CURL_CSELECT_ERR 0x04 - -typedef int (*curl_socket_callback)(CURL *easy, /* easy handle */ - curl_socket_t s, /* socket */ - int what, /* see above */ - void *userp, /* private callback - pointer */ - void *socketp); /* private socket - pointer */ -/* - * Name: curl_multi_timer_callback - * - * Desc: Called by libcurl whenever the library detects a change in the - * maximum number of milliseconds the app is allowed to wait before - * curl_multi_socket() or curl_multi_perform() must be called - * (to allow libcurl's timed events to take place). - * - * Returns: The callback should return zero. - */ -typedef int (*curl_multi_timer_callback)(CURLM *multi, /* multi handle */ - long timeout_ms, /* see above */ - void *userp); /* private callback - pointer */ - -CURL_EXTERN CURLMcode curl_multi_socket(CURLM *multi_handle, curl_socket_t s, - int *running_handles); - -CURL_EXTERN CURLMcode curl_multi_socket_action(CURLM *multi_handle, - curl_socket_t s, - int ev_bitmask, - int *running_handles); - -CURL_EXTERN CURLMcode curl_multi_socket_all(CURLM *multi_handle, - int *running_handles); - -#ifndef CURL_ALLOW_OLD_MULTI_SOCKET -/* This macro below was added in 7.16.3 to push users who recompile to use - the new curl_multi_socket_action() instead of the old curl_multi_socket() -*/ -#define curl_multi_socket(x,y,z) curl_multi_socket_action(x,y,0,z) -#endif - -/* - * Name: curl_multi_timeout() - * - * Desc: Returns the maximum number of milliseconds the app is allowed to - * wait before curl_multi_socket() or curl_multi_perform() must be - * called (to allow libcurl's timed events to take place). - * - * Returns: CURLM error code. - */ -CURL_EXTERN CURLMcode curl_multi_timeout(CURLM *multi_handle, - long *milliseconds); - -typedef enum { - /* This is the socket callback function pointer */ - CURLOPT(CURLMOPT_SOCKETFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 1), - - /* This is the argument passed to the socket callback */ - CURLOPT(CURLMOPT_SOCKETDATA, CURLOPTTYPE_OBJECTPOINT, 2), - - /* set to 1 to enable pipelining for this multi handle */ - CURLOPT(CURLMOPT_PIPELINING, CURLOPTTYPE_LONG, 3), - - /* This is the timer callback function pointer */ - CURLOPT(CURLMOPT_TIMERFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 4), - - /* This is the argument passed to the timer callback */ - CURLOPT(CURLMOPT_TIMERDATA, CURLOPTTYPE_OBJECTPOINT, 5), - - /* maximum number of entries in the connection cache */ - CURLOPT(CURLMOPT_MAXCONNECTS, CURLOPTTYPE_LONG, 6), - - /* maximum number of (pipelining) connections to one host */ - CURLOPT(CURLMOPT_MAX_HOST_CONNECTIONS, CURLOPTTYPE_LONG, 7), - - /* maximum number of requests in a pipeline */ - CURLOPT(CURLMOPT_MAX_PIPELINE_LENGTH, CURLOPTTYPE_LONG, 8), - - /* a connection with a content-length longer than this - will not be considered for pipelining */ - CURLOPT(CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE, CURLOPTTYPE_OFF_T, 9), - - /* a connection with a chunk length longer than this - will not be considered for pipelining */ - CURLOPT(CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE, CURLOPTTYPE_OFF_T, 10), - - /* a list of site names(+port) that are blocked from pipelining */ - CURLOPT(CURLMOPT_PIPELINING_SITE_BL, CURLOPTTYPE_OBJECTPOINT, 11), - - /* a list of server types that are blocked from pipelining */ - CURLOPT(CURLMOPT_PIPELINING_SERVER_BL, CURLOPTTYPE_OBJECTPOINT, 12), - - /* maximum number of open connections in total */ - CURLOPT(CURLMOPT_MAX_TOTAL_CONNECTIONS, CURLOPTTYPE_LONG, 13), - - /* This is the server push callback function pointer */ - CURLOPT(CURLMOPT_PUSHFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 14), - - /* This is the argument passed to the server push callback */ - CURLOPT(CURLMOPT_PUSHDATA, CURLOPTTYPE_OBJECTPOINT, 15), - - /* maximum number of concurrent streams to support on a connection */ - CURLOPT(CURLMOPT_MAX_CONCURRENT_STREAMS, CURLOPTTYPE_LONG, 16), - - CURLMOPT_LASTENTRY /* the last unused */ -} CURLMoption; - - -/* - * Name: curl_multi_setopt() - * - * Desc: Sets options for the multi handle. - * - * Returns: CURLM error code. - */ -CURL_EXTERN CURLMcode curl_multi_setopt(CURLM *multi_handle, - CURLMoption option, ...); - - -/* - * Name: curl_multi_assign() - * - * Desc: This function sets an association in the multi handle between the - * given socket and a private pointer of the application. This is - * (only) useful for curl_multi_socket uses. - * - * Returns: CURLM error code. - */ -CURL_EXTERN CURLMcode curl_multi_assign(CURLM *multi_handle, - curl_socket_t sockfd, void *sockp); - - -/* - * Name: curl_push_callback - * - * Desc: This callback gets called when a new stream is being pushed by the - * server. It approves or denies the new stream. It can also decide - * to completely fail the connection. - * - * Returns: CURL_PUSH_OK, CURL_PUSH_DENY or CURL_PUSH_ERROROUT - */ -#define CURL_PUSH_OK 0 -#define CURL_PUSH_DENY 1 -#define CURL_PUSH_ERROROUT 2 /* added in 7.72.0 */ - -struct curl_pushheaders; /* forward declaration only */ - -CURL_EXTERN char *curl_pushheader_bynum(struct curl_pushheaders *h, - size_t num); -CURL_EXTERN char *curl_pushheader_byname(struct curl_pushheaders *h, - const char *name); - -typedef int (*curl_push_callback)(CURL *parent, - CURL *easy, - size_t num_headers, - struct curl_pushheaders *headers, - void *userp); - -#ifdef __cplusplus -} /* end of extern "C" */ -#endif - -#endif diff --git a/ktor-client/ktor-client-curl/desktop/interop/mingwX64/include/curl/options.h b/ktor-client/ktor-client-curl/desktop/interop/mingwX64/include/curl/options.h deleted file mode 100644 index c8ac827c077..00000000000 --- a/ktor-client/ktor-client-curl/desktop/interop/mingwX64/include/curl/options.h +++ /dev/null @@ -1,70 +0,0 @@ -#ifndef CURLINC_OPTIONS_H -#define CURLINC_OPTIONS_H -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 2018 - 2022, Daniel Stenberg, , et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at https://curl.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - * SPDX-License-Identifier: curl - * - ***************************************************************************/ - -#ifdef __cplusplus -extern "C" { -#endif - -typedef enum { - CURLOT_LONG, /* long (a range of values) */ - CURLOT_VALUES, /* (a defined set or bitmask) */ - CURLOT_OFF_T, /* curl_off_t (a range of values) */ - CURLOT_OBJECT, /* pointer (void *) */ - CURLOT_STRING, /* (char * to zero terminated buffer) */ - CURLOT_SLIST, /* (struct curl_slist *) */ - CURLOT_CBPTR, /* (void * passed as-is to a callback) */ - CURLOT_BLOB, /* blob (struct curl_blob *) */ - CURLOT_FUNCTION /* function pointer */ -} curl_easytype; - -/* Flag bits */ - -/* "alias" means it is provided for old programs to remain functional, - we prefer another name */ -#define CURLOT_FLAG_ALIAS (1<<0) - -/* The CURLOPTTYPE_* id ranges can still be used to figure out what type/size - to use for curl_easy_setopt() for the given id */ -struct curl_easyoption { - const char *name; - CURLoption id; - curl_easytype type; - unsigned int flags; -}; - -CURL_EXTERN const struct curl_easyoption * -curl_easy_option_by_name(const char *name); - -CURL_EXTERN const struct curl_easyoption * -curl_easy_option_by_id(CURLoption id); - -CURL_EXTERN const struct curl_easyoption * -curl_easy_option_next(const struct curl_easyoption *prev); - -#ifdef __cplusplus -} /* end of extern "C" */ -#endif -#endif /* CURLINC_OPTIONS_H */ diff --git a/ktor-client/ktor-client-curl/desktop/interop/mingwX64/include/curl/stdcheaders.h b/ktor-client/ktor-client-curl/desktop/interop/mingwX64/include/curl/stdcheaders.h deleted file mode 100644 index 82e1b5fef6d..00000000000 --- a/ktor-client/ktor-client-curl/desktop/interop/mingwX64/include/curl/stdcheaders.h +++ /dev/null @@ -1,35 +0,0 @@ -#ifndef CURLINC_STDCHEADERS_H -#define CURLINC_STDCHEADERS_H -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 1998 - 2022, Daniel Stenberg, , et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at https://curl.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - * SPDX-License-Identifier: curl - * - ***************************************************************************/ - -#include - -size_t fread(void *, size_t, size_t, FILE *); -size_t fwrite(const void *, size_t, size_t, FILE *); - -int strcasecmp(const char *, const char *); -int strncasecmp(const char *, const char *, size_t); - -#endif /* CURLINC_STDCHEADERS_H */ diff --git a/ktor-client/ktor-client-curl/desktop/interop/mingwX64/include/curl/system.h b/ktor-client/ktor-client-curl/desktop/interop/mingwX64/include/curl/system.h deleted file mode 100644 index 8d56b8a4a1b..00000000000 --- a/ktor-client/ktor-client-curl/desktop/interop/mingwX64/include/curl/system.h +++ /dev/null @@ -1,490 +0,0 @@ -#ifndef CURLINC_SYSTEM_H -#define CURLINC_SYSTEM_H -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 1998 - 2022, Daniel Stenberg, , et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at https://curl.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - * SPDX-License-Identifier: curl - * - ***************************************************************************/ - -/* - * Try to keep one section per platform, compiler and architecture, otherwise, - * if an existing section is reused for a different one and later on the - * original is adjusted, probably the piggybacking one can be adversely - * changed. - * - * In order to differentiate between platforms/compilers/architectures use - * only compiler built in predefined preprocessor symbols. - * - * curl_off_t - * ---------- - * - * For any given platform/compiler curl_off_t must be typedef'ed to a 64-bit - * wide signed integral data type. The width of this data type must remain - * constant and independent of any possible large file support settings. - * - * As an exception to the above, curl_off_t shall be typedef'ed to a 32-bit - * wide signed integral data type if there is no 64-bit type. - * - * As a general rule, curl_off_t shall not be mapped to off_t. This rule shall - * only be violated if off_t is the only 64-bit data type available and the - * size of off_t is independent of large file support settings. Keep your - * build on the safe side avoiding an off_t gating. If you have a 64-bit - * off_t then take for sure that another 64-bit data type exists, dig deeper - * and you will find it. - * - */ - -#if defined(__DJGPP__) || defined(__GO32__) -# if defined(__DJGPP__) && (__DJGPP__ > 1) -# define CURL_TYPEOF_CURL_OFF_T long long -# define CURL_FORMAT_CURL_OFF_T "lld" -# define CURL_FORMAT_CURL_OFF_TU "llu" -# define CURL_SUFFIX_CURL_OFF_T LL -# define CURL_SUFFIX_CURL_OFF_TU ULL -# else -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# endif -# define CURL_TYPEOF_CURL_SOCKLEN_T int - -#elif defined(__SALFORDC__) -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# define CURL_TYPEOF_CURL_SOCKLEN_T int - -#elif defined(__BORLANDC__) -# if (__BORLANDC__ < 0x520) -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# else -# define CURL_TYPEOF_CURL_OFF_T __int64 -# define CURL_FORMAT_CURL_OFF_T "I64d" -# define CURL_FORMAT_CURL_OFF_TU "I64u" -# define CURL_SUFFIX_CURL_OFF_T i64 -# define CURL_SUFFIX_CURL_OFF_TU ui64 -# endif -# define CURL_TYPEOF_CURL_SOCKLEN_T int - -#elif defined(__TURBOC__) -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# define CURL_TYPEOF_CURL_SOCKLEN_T int - -#elif defined(__POCC__) -# if (__POCC__ < 280) -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# elif defined(_MSC_VER) -# define CURL_TYPEOF_CURL_OFF_T __int64 -# define CURL_FORMAT_CURL_OFF_T "I64d" -# define CURL_FORMAT_CURL_OFF_TU "I64u" -# define CURL_SUFFIX_CURL_OFF_T i64 -# define CURL_SUFFIX_CURL_OFF_TU ui64 -# else -# define CURL_TYPEOF_CURL_OFF_T long long -# define CURL_FORMAT_CURL_OFF_T "lld" -# define CURL_FORMAT_CURL_OFF_TU "llu" -# define CURL_SUFFIX_CURL_OFF_T LL -# define CURL_SUFFIX_CURL_OFF_TU ULL -# endif -# define CURL_TYPEOF_CURL_SOCKLEN_T int - -#elif defined(__LCC__) -# if defined(__MCST__) /* MCST eLbrus Compiler Collection */ -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t -# define CURL_PULL_SYS_TYPES_H 1 -# define CURL_PULL_SYS_SOCKET_H 1 -# else /* Local (or Little) C Compiler */ -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# define CURL_TYPEOF_CURL_SOCKLEN_T int -# endif - -#elif defined(__SYMBIAN32__) -# if defined(__EABI__) /* Treat all ARM compilers equally */ -# define CURL_TYPEOF_CURL_OFF_T long long -# define CURL_FORMAT_CURL_OFF_T "lld" -# define CURL_FORMAT_CURL_OFF_TU "llu" -# define CURL_SUFFIX_CURL_OFF_T LL -# define CURL_SUFFIX_CURL_OFF_TU ULL -# elif defined(__CW32__) -# pragma longlong on -# define CURL_TYPEOF_CURL_OFF_T long long -# define CURL_FORMAT_CURL_OFF_T "lld" -# define CURL_FORMAT_CURL_OFF_TU "llu" -# define CURL_SUFFIX_CURL_OFF_T LL -# define CURL_SUFFIX_CURL_OFF_TU ULL -# elif defined(__VC32__) -# define CURL_TYPEOF_CURL_OFF_T __int64 -# define CURL_FORMAT_CURL_OFF_T "lld" -# define CURL_FORMAT_CURL_OFF_TU "llu" -# define CURL_SUFFIX_CURL_OFF_T LL -# define CURL_SUFFIX_CURL_OFF_TU ULL -# endif -# define CURL_TYPEOF_CURL_SOCKLEN_T unsigned int - -#elif defined(__MWERKS__) -# define CURL_TYPEOF_CURL_OFF_T long long -# define CURL_FORMAT_CURL_OFF_T "lld" -# define CURL_FORMAT_CURL_OFF_TU "llu" -# define CURL_SUFFIX_CURL_OFF_T LL -# define CURL_SUFFIX_CURL_OFF_TU ULL -# define CURL_TYPEOF_CURL_SOCKLEN_T int - -#elif defined(_WIN32_WCE) -# define CURL_TYPEOF_CURL_OFF_T __int64 -# define CURL_FORMAT_CURL_OFF_T "I64d" -# define CURL_FORMAT_CURL_OFF_TU "I64u" -# define CURL_SUFFIX_CURL_OFF_T i64 -# define CURL_SUFFIX_CURL_OFF_TU ui64 -# define CURL_TYPEOF_CURL_SOCKLEN_T int - -#elif defined(__MINGW32__) -# define CURL_TYPEOF_CURL_OFF_T long long -# define CURL_FORMAT_CURL_OFF_T "I64d" -# define CURL_FORMAT_CURL_OFF_TU "I64u" -# define CURL_SUFFIX_CURL_OFF_T LL -# define CURL_SUFFIX_CURL_OFF_TU ULL -# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t -# define CURL_PULL_SYS_TYPES_H 1 -# define CURL_PULL_WS2TCPIP_H 1 - -#elif defined(__VMS) -# if defined(__VAX) -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# else -# define CURL_TYPEOF_CURL_OFF_T long long -# define CURL_FORMAT_CURL_OFF_T "lld" -# define CURL_FORMAT_CURL_OFF_TU "llu" -# define CURL_SUFFIX_CURL_OFF_T LL -# define CURL_SUFFIX_CURL_OFF_TU ULL -# endif -# define CURL_TYPEOF_CURL_SOCKLEN_T unsigned int - -#elif defined(__OS400__) -# if defined(__ILEC400__) -# define CURL_TYPEOF_CURL_OFF_T long long -# define CURL_FORMAT_CURL_OFF_T "lld" -# define CURL_FORMAT_CURL_OFF_TU "llu" -# define CURL_SUFFIX_CURL_OFF_T LL -# define CURL_SUFFIX_CURL_OFF_TU ULL -# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t -# define CURL_PULL_SYS_TYPES_H 1 -# define CURL_PULL_SYS_SOCKET_H 1 -# endif - -#elif defined(__MVS__) -# if defined(__IBMC__) || defined(__IBMCPP__) -# if defined(_ILP32) -# elif defined(_LP64) -# endif -# if defined(_LONG_LONG) -# define CURL_TYPEOF_CURL_OFF_T long long -# define CURL_FORMAT_CURL_OFF_T "lld" -# define CURL_FORMAT_CURL_OFF_TU "llu" -# define CURL_SUFFIX_CURL_OFF_T LL -# define CURL_SUFFIX_CURL_OFF_TU ULL -# elif defined(_LP64) -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# else -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# endif -# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t -# define CURL_PULL_SYS_TYPES_H 1 -# define CURL_PULL_SYS_SOCKET_H 1 -# endif - -#elif defined(__370__) -# if defined(__IBMC__) || defined(__IBMCPP__) -# if defined(_ILP32) -# elif defined(_LP64) -# endif -# if defined(_LONG_LONG) -# define CURL_TYPEOF_CURL_OFF_T long long -# define CURL_FORMAT_CURL_OFF_T "lld" -# define CURL_FORMAT_CURL_OFF_TU "llu" -# define CURL_SUFFIX_CURL_OFF_T LL -# define CURL_SUFFIX_CURL_OFF_TU ULL -# elif defined(_LP64) -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# else -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# endif -# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t -# define CURL_PULL_SYS_TYPES_H 1 -# define CURL_PULL_SYS_SOCKET_H 1 -# endif - -#elif defined(TPF) -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# define CURL_TYPEOF_CURL_SOCKLEN_T int - -#elif defined(__TINYC__) /* also known as tcc */ -# define CURL_TYPEOF_CURL_OFF_T long long -# define CURL_FORMAT_CURL_OFF_T "lld" -# define CURL_FORMAT_CURL_OFF_TU "llu" -# define CURL_SUFFIX_CURL_OFF_T LL -# define CURL_SUFFIX_CURL_OFF_TU ULL -# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t -# define CURL_PULL_SYS_TYPES_H 1 -# define CURL_PULL_SYS_SOCKET_H 1 - -#elif defined(__SUNPRO_C) || defined(__SUNPRO_CC) /* Oracle Solaris Studio */ -# if !defined(__LP64) && (defined(__ILP32) || \ - defined(__i386) || \ - defined(__sparcv8) || \ - defined(__sparcv8plus)) -# define CURL_TYPEOF_CURL_OFF_T long long -# define CURL_FORMAT_CURL_OFF_T "lld" -# define CURL_FORMAT_CURL_OFF_TU "llu" -# define CURL_SUFFIX_CURL_OFF_T LL -# define CURL_SUFFIX_CURL_OFF_TU ULL -# elif defined(__LP64) || \ - defined(__amd64) || defined(__sparcv9) -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# endif -# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t -# define CURL_PULL_SYS_TYPES_H 1 -# define CURL_PULL_SYS_SOCKET_H 1 - -#elif defined(__xlc__) /* IBM xlc compiler */ -# if !defined(_LP64) -# define CURL_TYPEOF_CURL_OFF_T long long -# define CURL_FORMAT_CURL_OFF_T "lld" -# define CURL_FORMAT_CURL_OFF_TU "llu" -# define CURL_SUFFIX_CURL_OFF_T LL -# define CURL_SUFFIX_CURL_OFF_TU ULL -# else -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# endif -# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t -# define CURL_PULL_SYS_TYPES_H 1 -# define CURL_PULL_SYS_SOCKET_H 1 - -/* ===================================== */ -/* KEEP MSVC THE PENULTIMATE ENTRY */ -/* ===================================== */ - -#elif defined(_MSC_VER) -# if (_MSC_VER >= 900) && (_INTEGRAL_MAX_BITS >= 64) -# define CURL_TYPEOF_CURL_OFF_T __int64 -# define CURL_FORMAT_CURL_OFF_T "I64d" -# define CURL_FORMAT_CURL_OFF_TU "I64u" -# define CURL_SUFFIX_CURL_OFF_T i64 -# define CURL_SUFFIX_CURL_OFF_TU ui64 -# else -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# endif -# define CURL_TYPEOF_CURL_SOCKLEN_T int - -/* ===================================== */ -/* KEEP GENERIC GCC THE LAST ENTRY */ -/* ===================================== */ - -#elif defined(__GNUC__) && !defined(_SCO_DS) -# if !defined(__LP64__) && \ - (defined(__ILP32__) || defined(__i386__) || defined(__hppa__) || \ - defined(__ppc__) || defined(__powerpc__) || defined(__arm__) || \ - defined(__sparc__) || defined(__mips__) || defined(__sh__) || \ - defined(__XTENSA__) || \ - (defined(__SIZEOF_LONG__) && __SIZEOF_LONG__ == 4) || \ - (defined(__LONG_MAX__) && __LONG_MAX__ == 2147483647L)) -# define CURL_TYPEOF_CURL_OFF_T long long -# define CURL_FORMAT_CURL_OFF_T "lld" -# define CURL_FORMAT_CURL_OFF_TU "llu" -# define CURL_SUFFIX_CURL_OFF_T LL -# define CURL_SUFFIX_CURL_OFF_TU ULL -# elif defined(__LP64__) || \ - defined(__x86_64__) || defined(__ppc64__) || defined(__sparc64__) || \ - defined(__e2k__) || \ - (defined(__SIZEOF_LONG__) && __SIZEOF_LONG__ == 8) || \ - (defined(__LONG_MAX__) && __LONG_MAX__ == 9223372036854775807L) -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# endif -# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t -# define CURL_PULL_SYS_TYPES_H 1 -# define CURL_PULL_SYS_SOCKET_H 1 - -#else -/* generic "safe guess" on old 32 bit style */ -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# define CURL_TYPEOF_CURL_SOCKLEN_T int -#endif - -#ifdef _AIX -/* AIX needs */ -#define CURL_PULL_SYS_POLL_H -#endif - - -/* CURL_PULL_WS2TCPIP_H is defined above when inclusion of header file */ -/* ws2tcpip.h is required here to properly make type definitions below. */ -#ifdef CURL_PULL_WS2TCPIP_H -# include -# include -# include -#endif - -/* CURL_PULL_SYS_TYPES_H is defined above when inclusion of header file */ -/* sys/types.h is required here to properly make type definitions below. */ -#ifdef CURL_PULL_SYS_TYPES_H -# include -#endif - -/* CURL_PULL_SYS_SOCKET_H is defined above when inclusion of header file */ -/* sys/socket.h is required here to properly make type definitions below. */ -#ifdef CURL_PULL_SYS_SOCKET_H -# include -#endif - -/* CURL_PULL_SYS_POLL_H is defined above when inclusion of header file */ -/* sys/poll.h is required here to properly make type definitions below. */ -#ifdef CURL_PULL_SYS_POLL_H -# include -#endif - -/* Data type definition of curl_socklen_t. */ -#ifdef CURL_TYPEOF_CURL_SOCKLEN_T - typedef CURL_TYPEOF_CURL_SOCKLEN_T curl_socklen_t; -#endif - -/* Data type definition of curl_off_t. */ - -#ifdef CURL_TYPEOF_CURL_OFF_T - typedef CURL_TYPEOF_CURL_OFF_T curl_off_t; -#endif - -/* - * CURL_ISOCPP and CURL_OFF_T_C definitions are done here in order to allow - * these to be visible and exported by the external libcurl interface API, - * while also making them visible to the library internals, simply including - * curl_setup.h, without actually needing to include curl.h internally. - * If some day this section would grow big enough, all this should be moved - * to its own header file. - */ - -/* - * Figure out if we can use the ## preprocessor operator, which is supported - * by ISO/ANSI C and C++. Some compilers support it without setting __STDC__ - * or __cplusplus so we need to carefully check for them too. - */ - -#if defined(__STDC__) || defined(_MSC_VER) || defined(__cplusplus) || \ - defined(__HP_aCC) || defined(__BORLANDC__) || defined(__LCC__) || \ - defined(__POCC__) || defined(__SALFORDC__) || defined(__HIGHC__) || \ - defined(__ILEC400__) - /* This compiler is believed to have an ISO compatible preprocessor */ -#define CURL_ISOCPP -#else - /* This compiler is believed NOT to have an ISO compatible preprocessor */ -#undef CURL_ISOCPP -#endif - -/* - * Macros for minimum-width signed and unsigned curl_off_t integer constants. - */ - -#if defined(__BORLANDC__) && (__BORLANDC__ == 0x0551) -# define CURLINC_OFF_T_C_HLPR2(x) x -# define CURLINC_OFF_T_C_HLPR1(x) CURLINC_OFF_T_C_HLPR2(x) -# define CURL_OFF_T_C(Val) CURLINC_OFF_T_C_HLPR1(Val) ## \ - CURLINC_OFF_T_C_HLPR1(CURL_SUFFIX_CURL_OFF_T) -# define CURL_OFF_TU_C(Val) CURLINC_OFF_T_C_HLPR1(Val) ## \ - CURLINC_OFF_T_C_HLPR1(CURL_SUFFIX_CURL_OFF_TU) -#else -# ifdef CURL_ISOCPP -# define CURLINC_OFF_T_C_HLPR2(Val,Suffix) Val ## Suffix -# else -# define CURLINC_OFF_T_C_HLPR2(Val,Suffix) Val/**/Suffix -# endif -# define CURLINC_OFF_T_C_HLPR1(Val,Suffix) CURLINC_OFF_T_C_HLPR2(Val,Suffix) -# define CURL_OFF_T_C(Val) CURLINC_OFF_T_C_HLPR1(Val,CURL_SUFFIX_CURL_OFF_T) -# define CURL_OFF_TU_C(Val) CURLINC_OFF_T_C_HLPR1(Val,CURL_SUFFIX_CURL_OFF_TU) -#endif - -#endif /* CURLINC_SYSTEM_H */ diff --git a/ktor-client/ktor-client-curl/desktop/interop/mingwX64/include/curl/typecheck-gcc.h b/ktor-client/ktor-client-curl/desktop/interop/mingwX64/include/curl/typecheck-gcc.h deleted file mode 100644 index d7c7a9a309f..00000000000 --- a/ktor-client/ktor-client-curl/desktop/interop/mingwX64/include/curl/typecheck-gcc.h +++ /dev/null @@ -1,710 +0,0 @@ -#ifndef CURLINC_TYPECHECK_GCC_H -#define CURLINC_TYPECHECK_GCC_H -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 1998 - 2022, Daniel Stenberg, , et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at https://curl.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - * SPDX-License-Identifier: curl - * - ***************************************************************************/ - -/* wraps curl_easy_setopt() with typechecking */ - -/* To add a new kind of warning, add an - * if(curlcheck_sometype_option(_curl_opt)) - * if(!curlcheck_sometype(value)) - * _curl_easy_setopt_err_sometype(); - * block and define curlcheck_sometype_option, curlcheck_sometype and - * _curl_easy_setopt_err_sometype below - * - * NOTE: We use two nested 'if' statements here instead of the && operator, in - * order to work around gcc bug #32061. It affects only gcc 4.3.x/4.4.x - * when compiling with -Wlogical-op. - * - * To add an option that uses the same type as an existing option, you'll just - * need to extend the appropriate _curl_*_option macro - */ -#define curl_easy_setopt(handle, option, value) \ - __extension__({ \ - __typeof__(option) _curl_opt = option; \ - if(__builtin_constant_p(_curl_opt)) { \ - if(curlcheck_long_option(_curl_opt)) \ - if(!curlcheck_long(value)) \ - _curl_easy_setopt_err_long(); \ - if(curlcheck_off_t_option(_curl_opt)) \ - if(!curlcheck_off_t(value)) \ - _curl_easy_setopt_err_curl_off_t(); \ - if(curlcheck_string_option(_curl_opt)) \ - if(!curlcheck_string(value)) \ - _curl_easy_setopt_err_string(); \ - if(curlcheck_write_cb_option(_curl_opt)) \ - if(!curlcheck_write_cb(value)) \ - _curl_easy_setopt_err_write_callback(); \ - if((_curl_opt) == CURLOPT_RESOLVER_START_FUNCTION) \ - if(!curlcheck_resolver_start_callback(value)) \ - _curl_easy_setopt_err_resolver_start_callback(); \ - if((_curl_opt) == CURLOPT_READFUNCTION) \ - if(!curlcheck_read_cb(value)) \ - _curl_easy_setopt_err_read_cb(); \ - if((_curl_opt) == CURLOPT_IOCTLFUNCTION) \ - if(!curlcheck_ioctl_cb(value)) \ - _curl_easy_setopt_err_ioctl_cb(); \ - if((_curl_opt) == CURLOPT_SOCKOPTFUNCTION) \ - if(!curlcheck_sockopt_cb(value)) \ - _curl_easy_setopt_err_sockopt_cb(); \ - if((_curl_opt) == CURLOPT_OPENSOCKETFUNCTION) \ - if(!curlcheck_opensocket_cb(value)) \ - _curl_easy_setopt_err_opensocket_cb(); \ - if((_curl_opt) == CURLOPT_PROGRESSFUNCTION) \ - if(!curlcheck_progress_cb(value)) \ - _curl_easy_setopt_err_progress_cb(); \ - if((_curl_opt) == CURLOPT_DEBUGFUNCTION) \ - if(!curlcheck_debug_cb(value)) \ - _curl_easy_setopt_err_debug_cb(); \ - if((_curl_opt) == CURLOPT_SSL_CTX_FUNCTION) \ - if(!curlcheck_ssl_ctx_cb(value)) \ - _curl_easy_setopt_err_ssl_ctx_cb(); \ - if(curlcheck_conv_cb_option(_curl_opt)) \ - if(!curlcheck_conv_cb(value)) \ - _curl_easy_setopt_err_conv_cb(); \ - if((_curl_opt) == CURLOPT_SEEKFUNCTION) \ - if(!curlcheck_seek_cb(value)) \ - _curl_easy_setopt_err_seek_cb(); \ - if(curlcheck_cb_data_option(_curl_opt)) \ - if(!curlcheck_cb_data(value)) \ - _curl_easy_setopt_err_cb_data(); \ - if((_curl_opt) == CURLOPT_ERRORBUFFER) \ - if(!curlcheck_error_buffer(value)) \ - _curl_easy_setopt_err_error_buffer(); \ - if((_curl_opt) == CURLOPT_STDERR) \ - if(!curlcheck_FILE(value)) \ - _curl_easy_setopt_err_FILE(); \ - if(curlcheck_postfields_option(_curl_opt)) \ - if(!curlcheck_postfields(value)) \ - _curl_easy_setopt_err_postfields(); \ - if((_curl_opt) == CURLOPT_HTTPPOST) \ - if(!curlcheck_arr((value), struct curl_httppost)) \ - _curl_easy_setopt_err_curl_httpost(); \ - if((_curl_opt) == CURLOPT_MIMEPOST) \ - if(!curlcheck_ptr((value), curl_mime)) \ - _curl_easy_setopt_err_curl_mimepost(); \ - if(curlcheck_slist_option(_curl_opt)) \ - if(!curlcheck_arr((value), struct curl_slist)) \ - _curl_easy_setopt_err_curl_slist(); \ - if((_curl_opt) == CURLOPT_SHARE) \ - if(!curlcheck_ptr((value), CURLSH)) \ - _curl_easy_setopt_err_CURLSH(); \ - } \ - curl_easy_setopt(handle, _curl_opt, value); \ - }) - -/* wraps curl_easy_getinfo() with typechecking */ -#define curl_easy_getinfo(handle, info, arg) \ - __extension__({ \ - __typeof__(info) _curl_info = info; \ - if(__builtin_constant_p(_curl_info)) { \ - if(curlcheck_string_info(_curl_info)) \ - if(!curlcheck_arr((arg), char *)) \ - _curl_easy_getinfo_err_string(); \ - if(curlcheck_long_info(_curl_info)) \ - if(!curlcheck_arr((arg), long)) \ - _curl_easy_getinfo_err_long(); \ - if(curlcheck_double_info(_curl_info)) \ - if(!curlcheck_arr((arg), double)) \ - _curl_easy_getinfo_err_double(); \ - if(curlcheck_slist_info(_curl_info)) \ - if(!curlcheck_arr((arg), struct curl_slist *)) \ - _curl_easy_getinfo_err_curl_slist(); \ - if(curlcheck_tlssessioninfo_info(_curl_info)) \ - if(!curlcheck_arr((arg), struct curl_tlssessioninfo *)) \ - _curl_easy_getinfo_err_curl_tlssesssioninfo(); \ - if(curlcheck_certinfo_info(_curl_info)) \ - if(!curlcheck_arr((arg), struct curl_certinfo *)) \ - _curl_easy_getinfo_err_curl_certinfo(); \ - if(curlcheck_socket_info(_curl_info)) \ - if(!curlcheck_arr((arg), curl_socket_t)) \ - _curl_easy_getinfo_err_curl_socket(); \ - if(curlcheck_off_t_info(_curl_info)) \ - if(!curlcheck_arr((arg), curl_off_t)) \ - _curl_easy_getinfo_err_curl_off_t(); \ - } \ - curl_easy_getinfo(handle, _curl_info, arg); \ - }) - -/* - * For now, just make sure that the functions are called with three arguments - */ -#define curl_share_setopt(share,opt,param) curl_share_setopt(share,opt,param) -#define curl_multi_setopt(handle,opt,param) curl_multi_setopt(handle,opt,param) - - -/* the actual warnings, triggered by calling the _curl_easy_setopt_err* - * functions */ - -/* To define a new warning, use _CURL_WARNING(identifier, "message") */ -#define CURLWARNING(id, message) \ - static void __attribute__((__warning__(message))) \ - __attribute__((__unused__)) __attribute__((__noinline__)) \ - id(void) { __asm__(""); } - -CURLWARNING(_curl_easy_setopt_err_long, - "curl_easy_setopt expects a long argument for this option") -CURLWARNING(_curl_easy_setopt_err_curl_off_t, - "curl_easy_setopt expects a curl_off_t argument for this option") -CURLWARNING(_curl_easy_setopt_err_string, - "curl_easy_setopt expects a " - "string ('char *' or char[]) argument for this option" - ) -CURLWARNING(_curl_easy_setopt_err_write_callback, - "curl_easy_setopt expects a curl_write_callback argument for this option") -CURLWARNING(_curl_easy_setopt_err_resolver_start_callback, - "curl_easy_setopt expects a " - "curl_resolver_start_callback argument for this option" - ) -CURLWARNING(_curl_easy_setopt_err_read_cb, - "curl_easy_setopt expects a curl_read_callback argument for this option") -CURLWARNING(_curl_easy_setopt_err_ioctl_cb, - "curl_easy_setopt expects a curl_ioctl_callback argument for this option") -CURLWARNING(_curl_easy_setopt_err_sockopt_cb, - "curl_easy_setopt expects a curl_sockopt_callback argument for this option") -CURLWARNING(_curl_easy_setopt_err_opensocket_cb, - "curl_easy_setopt expects a " - "curl_opensocket_callback argument for this option" - ) -CURLWARNING(_curl_easy_setopt_err_progress_cb, - "curl_easy_setopt expects a curl_progress_callback argument for this option") -CURLWARNING(_curl_easy_setopt_err_debug_cb, - "curl_easy_setopt expects a curl_debug_callback argument for this option") -CURLWARNING(_curl_easy_setopt_err_ssl_ctx_cb, - "curl_easy_setopt expects a curl_ssl_ctx_callback argument for this option") -CURLWARNING(_curl_easy_setopt_err_conv_cb, - "curl_easy_setopt expects a curl_conv_callback argument for this option") -CURLWARNING(_curl_easy_setopt_err_seek_cb, - "curl_easy_setopt expects a curl_seek_callback argument for this option") -CURLWARNING(_curl_easy_setopt_err_cb_data, - "curl_easy_setopt expects a " - "private data pointer as argument for this option") -CURLWARNING(_curl_easy_setopt_err_error_buffer, - "curl_easy_setopt expects a " - "char buffer of CURL_ERROR_SIZE as argument for this option") -CURLWARNING(_curl_easy_setopt_err_FILE, - "curl_easy_setopt expects a 'FILE *' argument for this option") -CURLWARNING(_curl_easy_setopt_err_postfields, - "curl_easy_setopt expects a 'void *' or 'char *' argument for this option") -CURLWARNING(_curl_easy_setopt_err_curl_httpost, - "curl_easy_setopt expects a 'struct curl_httppost *' " - "argument for this option") -CURLWARNING(_curl_easy_setopt_err_curl_mimepost, - "curl_easy_setopt expects a 'curl_mime *' " - "argument for this option") -CURLWARNING(_curl_easy_setopt_err_curl_slist, - "curl_easy_setopt expects a 'struct curl_slist *' argument for this option") -CURLWARNING(_curl_easy_setopt_err_CURLSH, - "curl_easy_setopt expects a CURLSH* argument for this option") - -CURLWARNING(_curl_easy_getinfo_err_string, - "curl_easy_getinfo expects a pointer to 'char *' for this info") -CURLWARNING(_curl_easy_getinfo_err_long, - "curl_easy_getinfo expects a pointer to long for this info") -CURLWARNING(_curl_easy_getinfo_err_double, - "curl_easy_getinfo expects a pointer to double for this info") -CURLWARNING(_curl_easy_getinfo_err_curl_slist, - "curl_easy_getinfo expects a pointer to 'struct curl_slist *' for this info") -CURLWARNING(_curl_easy_getinfo_err_curl_tlssesssioninfo, - "curl_easy_getinfo expects a pointer to " - "'struct curl_tlssessioninfo *' for this info") -CURLWARNING(_curl_easy_getinfo_err_curl_certinfo, - "curl_easy_getinfo expects a pointer to " - "'struct curl_certinfo *' for this info") -CURLWARNING(_curl_easy_getinfo_err_curl_socket, - "curl_easy_getinfo expects a pointer to curl_socket_t for this info") -CURLWARNING(_curl_easy_getinfo_err_curl_off_t, - "curl_easy_getinfo expects a pointer to curl_off_t for this info") - -/* groups of curl_easy_setops options that take the same type of argument */ - -/* To add a new option to one of the groups, just add - * (option) == CURLOPT_SOMETHING - * to the or-expression. If the option takes a long or curl_off_t, you don't - * have to do anything - */ - -/* evaluates to true if option takes a long argument */ -#define curlcheck_long_option(option) \ - (0 < (option) && (option) < CURLOPTTYPE_OBJECTPOINT) - -#define curlcheck_off_t_option(option) \ - (((option) > CURLOPTTYPE_OFF_T) && ((option) < CURLOPTTYPE_BLOB)) - -/* evaluates to true if option takes a char* argument */ -#define curlcheck_string_option(option) \ - ((option) == CURLOPT_ABSTRACT_UNIX_SOCKET || \ - (option) == CURLOPT_ACCEPT_ENCODING || \ - (option) == CURLOPT_ALTSVC || \ - (option) == CURLOPT_CAINFO || \ - (option) == CURLOPT_CAPATH || \ - (option) == CURLOPT_COOKIE || \ - (option) == CURLOPT_COOKIEFILE || \ - (option) == CURLOPT_COOKIEJAR || \ - (option) == CURLOPT_COOKIELIST || \ - (option) == CURLOPT_CRLFILE || \ - (option) == CURLOPT_CUSTOMREQUEST || \ - (option) == CURLOPT_DEFAULT_PROTOCOL || \ - (option) == CURLOPT_DNS_INTERFACE || \ - (option) == CURLOPT_DNS_LOCAL_IP4 || \ - (option) == CURLOPT_DNS_LOCAL_IP6 || \ - (option) == CURLOPT_DNS_SERVERS || \ - (option) == CURLOPT_DOH_URL || \ - (option) == CURLOPT_EGDSOCKET || \ - (option) == CURLOPT_FTPPORT || \ - (option) == CURLOPT_FTP_ACCOUNT || \ - (option) == CURLOPT_FTP_ALTERNATIVE_TO_USER || \ - (option) == CURLOPT_HSTS || \ - (option) == CURLOPT_INTERFACE || \ - (option) == CURLOPT_ISSUERCERT || \ - (option) == CURLOPT_KEYPASSWD || \ - (option) == CURLOPT_KRBLEVEL || \ - (option) == CURLOPT_LOGIN_OPTIONS || \ - (option) == CURLOPT_MAIL_AUTH || \ - (option) == CURLOPT_MAIL_FROM || \ - (option) == CURLOPT_NETRC_FILE || \ - (option) == CURLOPT_NOPROXY || \ - (option) == CURLOPT_PASSWORD || \ - (option) == CURLOPT_PINNEDPUBLICKEY || \ - (option) == CURLOPT_PRE_PROXY || \ - (option) == CURLOPT_PROXY || \ - (option) == CURLOPT_PROXYPASSWORD || \ - (option) == CURLOPT_PROXYUSERNAME || \ - (option) == CURLOPT_PROXYUSERPWD || \ - (option) == CURLOPT_PROXY_CAINFO || \ - (option) == CURLOPT_PROXY_CAPATH || \ - (option) == CURLOPT_PROXY_CRLFILE || \ - (option) == CURLOPT_PROXY_ISSUERCERT || \ - (option) == CURLOPT_PROXY_KEYPASSWD || \ - (option) == CURLOPT_PROXY_PINNEDPUBLICKEY || \ - (option) == CURLOPT_PROXY_SERVICE_NAME || \ - (option) == CURLOPT_PROXY_SSLCERT || \ - (option) == CURLOPT_PROXY_SSLCERTTYPE || \ - (option) == CURLOPT_PROXY_SSLKEY || \ - (option) == CURLOPT_PROXY_SSLKEYTYPE || \ - (option) == CURLOPT_PROXY_SSL_CIPHER_LIST || \ - (option) == CURLOPT_PROXY_TLS13_CIPHERS || \ - (option) == CURLOPT_PROXY_TLSAUTH_PASSWORD || \ - (option) == CURLOPT_PROXY_TLSAUTH_TYPE || \ - (option) == CURLOPT_PROXY_TLSAUTH_USERNAME || \ - (option) == CURLOPT_RANDOM_FILE || \ - (option) == CURLOPT_RANGE || \ - (option) == CURLOPT_REFERER || \ - (option) == CURLOPT_REQUEST_TARGET || \ - (option) == CURLOPT_RTSP_SESSION_ID || \ - (option) == CURLOPT_RTSP_STREAM_URI || \ - (option) == CURLOPT_RTSP_TRANSPORT || \ - (option) == CURLOPT_SASL_AUTHZID || \ - (option) == CURLOPT_SERVICE_NAME || \ - (option) == CURLOPT_SOCKS5_GSSAPI_SERVICE || \ - (option) == CURLOPT_SSH_HOST_PUBLIC_KEY_MD5 || \ - (option) == CURLOPT_SSH_HOST_PUBLIC_KEY_SHA256 || \ - (option) == CURLOPT_SSH_KNOWNHOSTS || \ - (option) == CURLOPT_SSH_PRIVATE_KEYFILE || \ - (option) == CURLOPT_SSH_PUBLIC_KEYFILE || \ - (option) == CURLOPT_SSLCERT || \ - (option) == CURLOPT_SSLCERTTYPE || \ - (option) == CURLOPT_SSLENGINE || \ - (option) == CURLOPT_SSLKEY || \ - (option) == CURLOPT_SSLKEYTYPE || \ - (option) == CURLOPT_SSL_CIPHER_LIST || \ - (option) == CURLOPT_TLS13_CIPHERS || \ - (option) == CURLOPT_TLSAUTH_PASSWORD || \ - (option) == CURLOPT_TLSAUTH_TYPE || \ - (option) == CURLOPT_TLSAUTH_USERNAME || \ - (option) == CURLOPT_UNIX_SOCKET_PATH || \ - (option) == CURLOPT_URL || \ - (option) == CURLOPT_USERAGENT || \ - (option) == CURLOPT_USERNAME || \ - (option) == CURLOPT_AWS_SIGV4 || \ - (option) == CURLOPT_USERPWD || \ - (option) == CURLOPT_XOAUTH2_BEARER || \ - (option) == CURLOPT_SSL_EC_CURVES || \ - 0) - -/* evaluates to true if option takes a curl_write_callback argument */ -#define curlcheck_write_cb_option(option) \ - ((option) == CURLOPT_HEADERFUNCTION || \ - (option) == CURLOPT_WRITEFUNCTION) - -/* evaluates to true if option takes a curl_conv_callback argument */ -#define curlcheck_conv_cb_option(option) \ - ((option) == CURLOPT_CONV_TO_NETWORK_FUNCTION || \ - (option) == CURLOPT_CONV_FROM_NETWORK_FUNCTION || \ - (option) == CURLOPT_CONV_FROM_UTF8_FUNCTION) - -/* evaluates to true if option takes a data argument to pass to a callback */ -#define curlcheck_cb_data_option(option) \ - ((option) == CURLOPT_CHUNK_DATA || \ - (option) == CURLOPT_CLOSESOCKETDATA || \ - (option) == CURLOPT_DEBUGDATA || \ - (option) == CURLOPT_FNMATCH_DATA || \ - (option) == CURLOPT_HEADERDATA || \ - (option) == CURLOPT_HSTSREADDATA || \ - (option) == CURLOPT_HSTSWRITEDATA || \ - (option) == CURLOPT_INTERLEAVEDATA || \ - (option) == CURLOPT_IOCTLDATA || \ - (option) == CURLOPT_OPENSOCKETDATA || \ - (option) == CURLOPT_PREREQDATA || \ - (option) == CURLOPT_PROGRESSDATA || \ - (option) == CURLOPT_READDATA || \ - (option) == CURLOPT_SEEKDATA || \ - (option) == CURLOPT_SOCKOPTDATA || \ - (option) == CURLOPT_SSH_KEYDATA || \ - (option) == CURLOPT_SSL_CTX_DATA || \ - (option) == CURLOPT_WRITEDATA || \ - (option) == CURLOPT_RESOLVER_START_DATA || \ - (option) == CURLOPT_TRAILERDATA || \ - (option) == CURLOPT_SSH_HOSTKEYDATA || \ - 0) - -/* evaluates to true if option takes a POST data argument (void* or char*) */ -#define curlcheck_postfields_option(option) \ - ((option) == CURLOPT_POSTFIELDS || \ - (option) == CURLOPT_COPYPOSTFIELDS || \ - 0) - -/* evaluates to true if option takes a struct curl_slist * argument */ -#define curlcheck_slist_option(option) \ - ((option) == CURLOPT_HTTP200ALIASES || \ - (option) == CURLOPT_HTTPHEADER || \ - (option) == CURLOPT_MAIL_RCPT || \ - (option) == CURLOPT_POSTQUOTE || \ - (option) == CURLOPT_PREQUOTE || \ - (option) == CURLOPT_PROXYHEADER || \ - (option) == CURLOPT_QUOTE || \ - (option) == CURLOPT_RESOLVE || \ - (option) == CURLOPT_TELNETOPTIONS || \ - (option) == CURLOPT_CONNECT_TO || \ - 0) - -/* groups of curl_easy_getinfo infos that take the same type of argument */ - -/* evaluates to true if info expects a pointer to char * argument */ -#define curlcheck_string_info(info) \ - (CURLINFO_STRING < (info) && (info) < CURLINFO_LONG && \ - (info) != CURLINFO_PRIVATE) - -/* evaluates to true if info expects a pointer to long argument */ -#define curlcheck_long_info(info) \ - (CURLINFO_LONG < (info) && (info) < CURLINFO_DOUBLE) - -/* evaluates to true if info expects a pointer to double argument */ -#define curlcheck_double_info(info) \ - (CURLINFO_DOUBLE < (info) && (info) < CURLINFO_SLIST) - -/* true if info expects a pointer to struct curl_slist * argument */ -#define curlcheck_slist_info(info) \ - (((info) == CURLINFO_SSL_ENGINES) || ((info) == CURLINFO_COOKIELIST)) - -/* true if info expects a pointer to struct curl_tlssessioninfo * argument */ -#define curlcheck_tlssessioninfo_info(info) \ - (((info) == CURLINFO_TLS_SSL_PTR) || ((info) == CURLINFO_TLS_SESSION)) - -/* true if info expects a pointer to struct curl_certinfo * argument */ -#define curlcheck_certinfo_info(info) ((info) == CURLINFO_CERTINFO) - -/* true if info expects a pointer to struct curl_socket_t argument */ -#define curlcheck_socket_info(info) \ - (CURLINFO_SOCKET < (info) && (info) < CURLINFO_OFF_T) - -/* true if info expects a pointer to curl_off_t argument */ -#define curlcheck_off_t_info(info) \ - (CURLINFO_OFF_T < (info)) - - -/* typecheck helpers -- check whether given expression has requested type*/ - -/* For pointers, you can use the curlcheck_ptr/curlcheck_arr macros, - * otherwise define a new macro. Search for __builtin_types_compatible_p - * in the GCC manual. - * NOTE: these macros MUST NOT EVALUATE their arguments! The argument is - * the actual expression passed to the curl_easy_setopt macro. This - * means that you can only apply the sizeof and __typeof__ operators, no - * == or whatsoever. - */ - -/* XXX: should evaluate to true if expr is a pointer */ -#define curlcheck_any_ptr(expr) \ - (sizeof(expr) == sizeof(void *)) - -/* evaluates to true if expr is NULL */ -/* XXX: must not evaluate expr, so this check is not accurate */ -#define curlcheck_NULL(expr) \ - (__builtin_types_compatible_p(__typeof__(expr), __typeof__(NULL))) - -/* evaluates to true if expr is type*, const type* or NULL */ -#define curlcheck_ptr(expr, type) \ - (curlcheck_NULL(expr) || \ - __builtin_types_compatible_p(__typeof__(expr), type *) || \ - __builtin_types_compatible_p(__typeof__(expr), const type *)) - -/* evaluates to true if expr is one of type[], type*, NULL or const type* */ -#define curlcheck_arr(expr, type) \ - (curlcheck_ptr((expr), type) || \ - __builtin_types_compatible_p(__typeof__(expr), type [])) - -/* evaluates to true if expr is a string */ -#define curlcheck_string(expr) \ - (curlcheck_arr((expr), char) || \ - curlcheck_arr((expr), signed char) || \ - curlcheck_arr((expr), unsigned char)) - -/* evaluates to true if expr is a long (no matter the signedness) - * XXX: for now, int is also accepted (and therefore short and char, which - * are promoted to int when passed to a variadic function) */ -#define curlcheck_long(expr) \ - (__builtin_types_compatible_p(__typeof__(expr), long) || \ - __builtin_types_compatible_p(__typeof__(expr), signed long) || \ - __builtin_types_compatible_p(__typeof__(expr), unsigned long) || \ - __builtin_types_compatible_p(__typeof__(expr), int) || \ - __builtin_types_compatible_p(__typeof__(expr), signed int) || \ - __builtin_types_compatible_p(__typeof__(expr), unsigned int) || \ - __builtin_types_compatible_p(__typeof__(expr), short) || \ - __builtin_types_compatible_p(__typeof__(expr), signed short) || \ - __builtin_types_compatible_p(__typeof__(expr), unsigned short) || \ - __builtin_types_compatible_p(__typeof__(expr), char) || \ - __builtin_types_compatible_p(__typeof__(expr), signed char) || \ - __builtin_types_compatible_p(__typeof__(expr), unsigned char)) - -/* evaluates to true if expr is of type curl_off_t */ -#define curlcheck_off_t(expr) \ - (__builtin_types_compatible_p(__typeof__(expr), curl_off_t)) - -/* evaluates to true if expr is abuffer suitable for CURLOPT_ERRORBUFFER */ -/* XXX: also check size of an char[] array? */ -#define curlcheck_error_buffer(expr) \ - (curlcheck_NULL(expr) || \ - __builtin_types_compatible_p(__typeof__(expr), char *) || \ - __builtin_types_compatible_p(__typeof__(expr), char[])) - -/* evaluates to true if expr is of type (const) void* or (const) FILE* */ -#if 0 -#define curlcheck_cb_data(expr) \ - (curlcheck_ptr((expr), void) || \ - curlcheck_ptr((expr), FILE)) -#else /* be less strict */ -#define curlcheck_cb_data(expr) \ - curlcheck_any_ptr(expr) -#endif - -/* evaluates to true if expr is of type FILE* */ -#define curlcheck_FILE(expr) \ - (curlcheck_NULL(expr) || \ - (__builtin_types_compatible_p(__typeof__(expr), FILE *))) - -/* evaluates to true if expr can be passed as POST data (void* or char*) */ -#define curlcheck_postfields(expr) \ - (curlcheck_ptr((expr), void) || \ - curlcheck_arr((expr), char) || \ - curlcheck_arr((expr), unsigned char)) - -/* helper: __builtin_types_compatible_p distinguishes between functions and - * function pointers, hide it */ -#define curlcheck_cb_compatible(func, type) \ - (__builtin_types_compatible_p(__typeof__(func), type) || \ - __builtin_types_compatible_p(__typeof__(func) *, type)) - -/* evaluates to true if expr is of type curl_resolver_start_callback */ -#define curlcheck_resolver_start_callback(expr) \ - (curlcheck_NULL(expr) || \ - curlcheck_cb_compatible((expr), curl_resolver_start_callback)) - -/* evaluates to true if expr is of type curl_read_callback or "similar" */ -#define curlcheck_read_cb(expr) \ - (curlcheck_NULL(expr) || \ - curlcheck_cb_compatible((expr), __typeof__(fread) *) || \ - curlcheck_cb_compatible((expr), curl_read_callback) || \ - curlcheck_cb_compatible((expr), _curl_read_callback1) || \ - curlcheck_cb_compatible((expr), _curl_read_callback2) || \ - curlcheck_cb_compatible((expr), _curl_read_callback3) || \ - curlcheck_cb_compatible((expr), _curl_read_callback4) || \ - curlcheck_cb_compatible((expr), _curl_read_callback5) || \ - curlcheck_cb_compatible((expr), _curl_read_callback6)) -typedef size_t (*_curl_read_callback1)(char *, size_t, size_t, void *); -typedef size_t (*_curl_read_callback2)(char *, size_t, size_t, const void *); -typedef size_t (*_curl_read_callback3)(char *, size_t, size_t, FILE *); -typedef size_t (*_curl_read_callback4)(void *, size_t, size_t, void *); -typedef size_t (*_curl_read_callback5)(void *, size_t, size_t, const void *); -typedef size_t (*_curl_read_callback6)(void *, size_t, size_t, FILE *); - -/* evaluates to true if expr is of type curl_write_callback or "similar" */ -#define curlcheck_write_cb(expr) \ - (curlcheck_read_cb(expr) || \ - curlcheck_cb_compatible((expr), __typeof__(fwrite) *) || \ - curlcheck_cb_compatible((expr), curl_write_callback) || \ - curlcheck_cb_compatible((expr), _curl_write_callback1) || \ - curlcheck_cb_compatible((expr), _curl_write_callback2) || \ - curlcheck_cb_compatible((expr), _curl_write_callback3) || \ - curlcheck_cb_compatible((expr), _curl_write_callback4) || \ - curlcheck_cb_compatible((expr), _curl_write_callback5) || \ - curlcheck_cb_compatible((expr), _curl_write_callback6)) -typedef size_t (*_curl_write_callback1)(const char *, size_t, size_t, void *); -typedef size_t (*_curl_write_callback2)(const char *, size_t, size_t, - const void *); -typedef size_t (*_curl_write_callback3)(const char *, size_t, size_t, FILE *); -typedef size_t (*_curl_write_callback4)(const void *, size_t, size_t, void *); -typedef size_t (*_curl_write_callback5)(const void *, size_t, size_t, - const void *); -typedef size_t (*_curl_write_callback6)(const void *, size_t, size_t, FILE *); - -/* evaluates to true if expr is of type curl_ioctl_callback or "similar" */ -#define curlcheck_ioctl_cb(expr) \ - (curlcheck_NULL(expr) || \ - curlcheck_cb_compatible((expr), curl_ioctl_callback) || \ - curlcheck_cb_compatible((expr), _curl_ioctl_callback1) || \ - curlcheck_cb_compatible((expr), _curl_ioctl_callback2) || \ - curlcheck_cb_compatible((expr), _curl_ioctl_callback3) || \ - curlcheck_cb_compatible((expr), _curl_ioctl_callback4)) -typedef curlioerr (*_curl_ioctl_callback1)(CURL *, int, void *); -typedef curlioerr (*_curl_ioctl_callback2)(CURL *, int, const void *); -typedef curlioerr (*_curl_ioctl_callback3)(CURL *, curliocmd, void *); -typedef curlioerr (*_curl_ioctl_callback4)(CURL *, curliocmd, const void *); - -/* evaluates to true if expr is of type curl_sockopt_callback or "similar" */ -#define curlcheck_sockopt_cb(expr) \ - (curlcheck_NULL(expr) || \ - curlcheck_cb_compatible((expr), curl_sockopt_callback) || \ - curlcheck_cb_compatible((expr), _curl_sockopt_callback1) || \ - curlcheck_cb_compatible((expr), _curl_sockopt_callback2)) -typedef int (*_curl_sockopt_callback1)(void *, curl_socket_t, curlsocktype); -typedef int (*_curl_sockopt_callback2)(const void *, curl_socket_t, - curlsocktype); - -/* evaluates to true if expr is of type curl_opensocket_callback or - "similar" */ -#define curlcheck_opensocket_cb(expr) \ - (curlcheck_NULL(expr) || \ - curlcheck_cb_compatible((expr), curl_opensocket_callback) || \ - curlcheck_cb_compatible((expr), _curl_opensocket_callback1) || \ - curlcheck_cb_compatible((expr), _curl_opensocket_callback2) || \ - curlcheck_cb_compatible((expr), _curl_opensocket_callback3) || \ - curlcheck_cb_compatible((expr), _curl_opensocket_callback4)) -typedef curl_socket_t (*_curl_opensocket_callback1) - (void *, curlsocktype, struct curl_sockaddr *); -typedef curl_socket_t (*_curl_opensocket_callback2) - (void *, curlsocktype, const struct curl_sockaddr *); -typedef curl_socket_t (*_curl_opensocket_callback3) - (const void *, curlsocktype, struct curl_sockaddr *); -typedef curl_socket_t (*_curl_opensocket_callback4) - (const void *, curlsocktype, const struct curl_sockaddr *); - -/* evaluates to true if expr is of type curl_progress_callback or "similar" */ -#define curlcheck_progress_cb(expr) \ - (curlcheck_NULL(expr) || \ - curlcheck_cb_compatible((expr), curl_progress_callback) || \ - curlcheck_cb_compatible((expr), _curl_progress_callback1) || \ - curlcheck_cb_compatible((expr), _curl_progress_callback2)) -typedef int (*_curl_progress_callback1)(void *, - double, double, double, double); -typedef int (*_curl_progress_callback2)(const void *, - double, double, double, double); - -/* evaluates to true if expr is of type curl_debug_callback or "similar" */ -#define curlcheck_debug_cb(expr) \ - (curlcheck_NULL(expr) || \ - curlcheck_cb_compatible((expr), curl_debug_callback) || \ - curlcheck_cb_compatible((expr), _curl_debug_callback1) || \ - curlcheck_cb_compatible((expr), _curl_debug_callback2) || \ - curlcheck_cb_compatible((expr), _curl_debug_callback3) || \ - curlcheck_cb_compatible((expr), _curl_debug_callback4) || \ - curlcheck_cb_compatible((expr), _curl_debug_callback5) || \ - curlcheck_cb_compatible((expr), _curl_debug_callback6) || \ - curlcheck_cb_compatible((expr), _curl_debug_callback7) || \ - curlcheck_cb_compatible((expr), _curl_debug_callback8)) -typedef int (*_curl_debug_callback1) (CURL *, - curl_infotype, char *, size_t, void *); -typedef int (*_curl_debug_callback2) (CURL *, - curl_infotype, char *, size_t, const void *); -typedef int (*_curl_debug_callback3) (CURL *, - curl_infotype, const char *, size_t, void *); -typedef int (*_curl_debug_callback4) (CURL *, - curl_infotype, const char *, size_t, const void *); -typedef int (*_curl_debug_callback5) (CURL *, - curl_infotype, unsigned char *, size_t, void *); -typedef int (*_curl_debug_callback6) (CURL *, - curl_infotype, unsigned char *, size_t, const void *); -typedef int (*_curl_debug_callback7) (CURL *, - curl_infotype, const unsigned char *, size_t, void *); -typedef int (*_curl_debug_callback8) (CURL *, - curl_infotype, const unsigned char *, size_t, const void *); - -/* evaluates to true if expr is of type curl_ssl_ctx_callback or "similar" */ -/* this is getting even messier... */ -#define curlcheck_ssl_ctx_cb(expr) \ - (curlcheck_NULL(expr) || \ - curlcheck_cb_compatible((expr), curl_ssl_ctx_callback) || \ - curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback1) || \ - curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback2) || \ - curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback3) || \ - curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback4) || \ - curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback5) || \ - curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback6) || \ - curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback7) || \ - curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback8)) -typedef CURLcode (*_curl_ssl_ctx_callback1)(CURL *, void *, void *); -typedef CURLcode (*_curl_ssl_ctx_callback2)(CURL *, void *, const void *); -typedef CURLcode (*_curl_ssl_ctx_callback3)(CURL *, const void *, void *); -typedef CURLcode (*_curl_ssl_ctx_callback4)(CURL *, const void *, - const void *); -#ifdef HEADER_SSL_H -/* hack: if we included OpenSSL's ssl.h, we know about SSL_CTX - * this will of course break if we're included before OpenSSL headers... - */ -typedef CURLcode (*_curl_ssl_ctx_callback5)(CURL *, SSL_CTX *, void *); -typedef CURLcode (*_curl_ssl_ctx_callback6)(CURL *, SSL_CTX *, const void *); -typedef CURLcode (*_curl_ssl_ctx_callback7)(CURL *, const SSL_CTX *, void *); -typedef CURLcode (*_curl_ssl_ctx_callback8)(CURL *, const SSL_CTX *, - const void *); -#else -typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback5; -typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback6; -typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback7; -typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback8; -#endif - -/* evaluates to true if expr is of type curl_conv_callback or "similar" */ -#define curlcheck_conv_cb(expr) \ - (curlcheck_NULL(expr) || \ - curlcheck_cb_compatible((expr), curl_conv_callback) || \ - curlcheck_cb_compatible((expr), _curl_conv_callback1) || \ - curlcheck_cb_compatible((expr), _curl_conv_callback2) || \ - curlcheck_cb_compatible((expr), _curl_conv_callback3) || \ - curlcheck_cb_compatible((expr), _curl_conv_callback4)) -typedef CURLcode (*_curl_conv_callback1)(char *, size_t length); -typedef CURLcode (*_curl_conv_callback2)(const char *, size_t length); -typedef CURLcode (*_curl_conv_callback3)(void *, size_t length); -typedef CURLcode (*_curl_conv_callback4)(const void *, size_t length); - -/* evaluates to true if expr is of type curl_seek_callback or "similar" */ -#define curlcheck_seek_cb(expr) \ - (curlcheck_NULL(expr) || \ - curlcheck_cb_compatible((expr), curl_seek_callback) || \ - curlcheck_cb_compatible((expr), _curl_seek_callback1) || \ - curlcheck_cb_compatible((expr), _curl_seek_callback2)) -typedef CURLcode (*_curl_seek_callback1)(void *, curl_off_t, int); -typedef CURLcode (*_curl_seek_callback2)(const void *, curl_off_t, int); - - -#endif /* CURLINC_TYPECHECK_GCC_H */ diff --git a/ktor-client/ktor-client-curl/desktop/interop/mingwX64/include/curl/urlapi.h b/ktor-client/ktor-client-curl/desktop/interop/mingwX64/include/curl/urlapi.h deleted file mode 100644 index e15c213ccdf..00000000000 --- a/ktor-client/ktor-client-curl/desktop/interop/mingwX64/include/curl/urlapi.h +++ /dev/null @@ -1,147 +0,0 @@ -#ifndef CURLINC_URLAPI_H -#define CURLINC_URLAPI_H -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 2018 - 2022, Daniel Stenberg, , et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at https://curl.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - * SPDX-License-Identifier: curl - * - ***************************************************************************/ - -#include "curl.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/* the error codes for the URL API */ -typedef enum { - CURLUE_OK, - CURLUE_BAD_HANDLE, /* 1 */ - CURLUE_BAD_PARTPOINTER, /* 2 */ - CURLUE_MALFORMED_INPUT, /* 3 */ - CURLUE_BAD_PORT_NUMBER, /* 4 */ - CURLUE_UNSUPPORTED_SCHEME, /* 5 */ - CURLUE_URLDECODE, /* 6 */ - CURLUE_OUT_OF_MEMORY, /* 7 */ - CURLUE_USER_NOT_ALLOWED, /* 8 */ - CURLUE_UNKNOWN_PART, /* 9 */ - CURLUE_NO_SCHEME, /* 10 */ - CURLUE_NO_USER, /* 11 */ - CURLUE_NO_PASSWORD, /* 12 */ - CURLUE_NO_OPTIONS, /* 13 */ - CURLUE_NO_HOST, /* 14 */ - CURLUE_NO_PORT, /* 15 */ - CURLUE_NO_QUERY, /* 16 */ - CURLUE_NO_FRAGMENT, /* 17 */ - CURLUE_NO_ZONEID, /* 18 */ - CURLUE_BAD_FILE_URL, /* 19 */ - CURLUE_BAD_FRAGMENT, /* 20 */ - CURLUE_BAD_HOSTNAME, /* 21 */ - CURLUE_BAD_IPV6, /* 22 */ - CURLUE_BAD_LOGIN, /* 23 */ - CURLUE_BAD_PASSWORD, /* 24 */ - CURLUE_BAD_PATH, /* 25 */ - CURLUE_BAD_QUERY, /* 26 */ - CURLUE_BAD_SCHEME, /* 27 */ - CURLUE_BAD_SLASHES, /* 28 */ - CURLUE_BAD_USER, /* 29 */ - CURLUE_LAST -} CURLUcode; - -typedef enum { - CURLUPART_URL, - CURLUPART_SCHEME, - CURLUPART_USER, - CURLUPART_PASSWORD, - CURLUPART_OPTIONS, - CURLUPART_HOST, - CURLUPART_PORT, - CURLUPART_PATH, - CURLUPART_QUERY, - CURLUPART_FRAGMENT, - CURLUPART_ZONEID /* added in 7.65.0 */ -} CURLUPart; - -#define CURLU_DEFAULT_PORT (1<<0) /* return default port number */ -#define CURLU_NO_DEFAULT_PORT (1<<1) /* act as if no port number was set, - if the port number matches the - default for the scheme */ -#define CURLU_DEFAULT_SCHEME (1<<2) /* return default scheme if - missing */ -#define CURLU_NON_SUPPORT_SCHEME (1<<3) /* allow non-supported scheme */ -#define CURLU_PATH_AS_IS (1<<4) /* leave dot sequences */ -#define CURLU_DISALLOW_USER (1<<5) /* no user+password allowed */ -#define CURLU_URLDECODE (1<<6) /* URL decode on get */ -#define CURLU_URLENCODE (1<<7) /* URL encode on set */ -#define CURLU_APPENDQUERY (1<<8) /* append a form style part */ -#define CURLU_GUESS_SCHEME (1<<9) /* legacy curl-style guessing */ -#define CURLU_NO_AUTHORITY (1<<10) /* Allow empty authority when the - scheme is unknown. */ -#define CURLU_ALLOW_SPACE (1<<11) /* Allow spaces in the URL */ - -typedef struct Curl_URL CURLU; - -/* - * curl_url() creates a new CURLU handle and returns a pointer to it. - * Must be freed with curl_url_cleanup(). - */ -CURL_EXTERN CURLU *curl_url(void); - -/* - * curl_url_cleanup() frees the CURLU handle and related resources used for - * the URL parsing. It will not free strings previously returned with the URL - * API. - */ -CURL_EXTERN void curl_url_cleanup(CURLU *handle); - -/* - * curl_url_dup() duplicates a CURLU handle and returns a new copy. The new - * handle must also be freed with curl_url_cleanup(). - */ -CURL_EXTERN CURLU *curl_url_dup(CURLU *in); - -/* - * curl_url_get() extracts a specific part of the URL from a CURLU - * handle. Returns error code. The returned pointer MUST be freed with - * curl_free() afterwards. - */ -CURL_EXTERN CURLUcode curl_url_get(CURLU *handle, CURLUPart what, - char **part, unsigned int flags); - -/* - * curl_url_set() sets a specific part of the URL in a CURLU handle. Returns - * error code. The passed in string will be copied. Passing a NULL instead of - * a part string, clears that part. - */ -CURL_EXTERN CURLUcode curl_url_set(CURLU *handle, CURLUPart what, - const char *part, unsigned int flags); - -/* - * curl_url_strerror() turns a CURLUcode value into the equivalent human - * readable error string. This is useful for printing meaningful error - * messages. - */ -CURL_EXTERN const char *curl_url_strerror(CURLUcode); - -#ifdef __cplusplus -} /* end of extern "C" */ -#endif - -#endif /* CURLINC_URLAPI_H */ diff --git a/ktor-client/ktor-client-curl/desktop/interop/mingwX64/lib/libbrotlicommon.a b/ktor-client/ktor-client-curl/desktop/interop/mingwX64/lib/libbrotlicommon.a deleted file mode 100644 index a505be994c3..00000000000 Binary files a/ktor-client/ktor-client-curl/desktop/interop/mingwX64/lib/libbrotlicommon.a and /dev/null differ diff --git a/ktor-client/ktor-client-curl/desktop/interop/mingwX64/lib/libbrotlidec.a b/ktor-client/ktor-client-curl/desktop/interop/mingwX64/lib/libbrotlidec.a deleted file mode 100644 index 46680dfee11..00000000000 Binary files a/ktor-client/ktor-client-curl/desktop/interop/mingwX64/lib/libbrotlidec.a and /dev/null differ diff --git a/ktor-client/ktor-client-curl/desktop/interop/mingwX64/lib/libcurl.a b/ktor-client/ktor-client-curl/desktop/interop/mingwX64/lib/libcurl.a deleted file mode 100644 index 347b7854204..00000000000 Binary files a/ktor-client/ktor-client-curl/desktop/interop/mingwX64/lib/libcurl.a and /dev/null differ diff --git a/ktor-client/ktor-client-curl/desktop/interop/mingwX64/lib/libidn2.a b/ktor-client/ktor-client-curl/desktop/interop/mingwX64/lib/libidn2.a deleted file mode 100644 index 7f714eb21b5..00000000000 Binary files a/ktor-client/ktor-client-curl/desktop/interop/mingwX64/lib/libidn2.a and /dev/null differ diff --git a/ktor-client/ktor-client-curl/desktop/interop/mingwX64/lib/libpsl.a b/ktor-client/ktor-client-curl/desktop/interop/mingwX64/lib/libpsl.a deleted file mode 100644 index 4975afede62..00000000000 Binary files a/ktor-client/ktor-client-curl/desktop/interop/mingwX64/lib/libpsl.a and /dev/null differ diff --git a/ktor-client/ktor-client-curl/desktop/interop/mingwX64/lib/libssh2.a b/ktor-client/ktor-client-curl/desktop/interop/mingwX64/lib/libssh2.a deleted file mode 100644 index 54b8fa22aa0..00000000000 Binary files a/ktor-client/ktor-client-curl/desktop/interop/mingwX64/lib/libssh2.a and /dev/null differ diff --git a/ktor-client/ktor-client-curl/desktop/interop/mingwX64/lib/libunistring.a b/ktor-client/ktor-client-curl/desktop/interop/mingwX64/lib/libunistring.a deleted file mode 100644 index a73bfc5c242..00000000000 Binary files a/ktor-client/ktor-client-curl/desktop/interop/mingwX64/lib/libunistring.a and /dev/null differ diff --git a/ktor-client/ktor-client-curl/desktop/interop/mingwX64/lib/libzstd.a b/ktor-client/ktor-client-curl/desktop/interop/mingwX64/lib/libzstd.a deleted file mode 100644 index ddda1b1d537..00000000000 Binary files a/ktor-client/ktor-client-curl/desktop/interop/mingwX64/lib/libzstd.a and /dev/null differ diff --git a/ktor-client/ktor-client-curl/desktop/test/io/ktor/client/engine/curl/test/CurlNativeTests.kt b/ktor-client/ktor-client-curl/desktop/test/io/ktor/client/engine/curl/test/CurlNativeTests.kt index 6204db99a37..366ca4da5a7 100644 --- a/ktor-client/ktor-client-curl/desktop/test/io/ktor/client/engine/curl/test/CurlNativeTests.kt +++ b/ktor-client/ktor-client-curl/desktop/test/io/ktor/client/engine/curl/test/CurlNativeTests.kt @@ -1,6 +1,6 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.client.engine.curl.test @@ -9,9 +9,7 @@ import io.ktor.client.call.* import io.ktor.client.engine.curl.* import io.ktor.client.request.* import io.ktor.client.statement.* -import io.ktor.utils.io.core.* import kotlinx.coroutines.* -import kotlin.native.concurrent.* import kotlin.test.* class CurlNativeTests { diff --git a/ktor-client/ktor-client-curl/desktop/test/io/ktor/client/engine/curl/test/CurlProxyTest.kt b/ktor-client/ktor-client-curl/desktop/test/io/ktor/client/engine/curl/test/CurlProxyTest.kt index 73b64693d69..e0d8e2b350e 100644 --- a/ktor-client/ktor-client-curl/desktop/test/io/ktor/client/engine/curl/test/CurlProxyTest.kt +++ b/ktor-client/ktor-client-curl/desktop/test/io/ktor/client/engine/curl/test/CurlProxyTest.kt @@ -1,6 +1,6 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.client.engine.curl.test @@ -11,7 +11,6 @@ import io.ktor.client.engine.curl.* import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* -import io.ktor.utils.io.core.* import kotlinx.coroutines.* import kotlin.test.* diff --git a/ktor-client/ktor-client-curl/gradle.properties b/ktor-client/ktor-client-curl/gradle.properties new file mode 100644 index 00000000000..05d11d79551 --- /dev/null +++ b/ktor-client/ktor-client-curl/gradle.properties @@ -0,0 +1,5 @@ +# +# Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. +# + +kotlin.native.cacheKind.linuxX64=none diff --git a/ktor-client/ktor-client-java/api/ktor-client-java.api b/ktor-client/ktor-client-java/api/ktor-client-java.api index 609867b39c0..e8ee2f28578 100644 --- a/ktor-client/ktor-client-java/api/ktor-client-java.api +++ b/ktor-client/ktor-client-java/api/ktor-client-java.api @@ -1,6 +1,9 @@ public final class io/ktor/client/engine/java/Java : io/ktor/client/engine/HttpClientEngineFactory { public static final field INSTANCE Lio/ktor/client/engine/java/Java; public fun create (Lkotlin/jvm/functions/Function1;)Lio/ktor/client/engine/HttpClientEngine; + public fun equals (Ljava/lang/Object;)Z + public fun hashCode ()I + public fun toString ()Ljava/lang/String; } public final class io/ktor/client/engine/java/JavaHttpConfig : io/ktor/client/engine/HttpClientEngineConfig { diff --git a/ktor-client/ktor-client-java/jvm/src/io/ktor/client/engine/java/Java.kt b/ktor-client/ktor-client-java/jvm/src/io/ktor/client/engine/java/Java.kt index 1d9fc377611..753a6362e54 100644 --- a/ktor-client/ktor-client-java/jvm/src/io/ktor/client/engine/java/Java.kt +++ b/ktor-client/ktor-client-java/jvm/src/io/ktor/client/engine/java/Java.kt @@ -25,7 +25,7 @@ import io.ktor.client.engine.* * * You can learn more about client engines from [Engines](https://ktor.io/docs/http-client-engines.html). */ -public object Java : HttpClientEngineFactory { +public data object Java : HttpClientEngineFactory { override fun create(block: JavaHttpConfig.() -> Unit): HttpClientEngine = JavaHttpEngine(JavaHttpConfig().apply(block)) } diff --git a/ktor-client/ktor-client-jetty-jakarta/api/ktor-client-jetty-jakarta.api b/ktor-client/ktor-client-jetty-jakarta/api/ktor-client-jetty-jakarta.api index faef63dd755..d7c00794a7c 100644 --- a/ktor-client/ktor-client-jetty-jakarta/api/ktor-client-jetty-jakarta.api +++ b/ktor-client/ktor-client-jetty-jakarta/api/ktor-client-jetty-jakarta.api @@ -1,6 +1,9 @@ public final class io/ktor/client/engine/jetty/jakarta/Jetty : io/ktor/client/engine/HttpClientEngineFactory { public static final field INSTANCE Lio/ktor/client/engine/jetty/jakarta/Jetty; public fun create (Lkotlin/jvm/functions/Function1;)Lio/ktor/client/engine/HttpClientEngine; + public fun equals (Ljava/lang/Object;)Z + public fun hashCode ()I + public fun toString ()Ljava/lang/String; } public final class io/ktor/client/engine/jetty/jakarta/JettyEngineConfig : io/ktor/client/engine/HttpClientEngineConfig { diff --git a/ktor-client/ktor-client-jetty-jakarta/jvm/src/io/ktor/client/engine/jetty/jakarta/Jetty.kt b/ktor-client/ktor-client-jetty-jakarta/jvm/src/io/ktor/client/engine/jetty/jakarta/Jetty.kt index 07df70ca0f2..2b5d62be189 100644 --- a/ktor-client/ktor-client-jetty-jakarta/jvm/src/io/ktor/client/engine/jetty/jakarta/Jetty.kt +++ b/ktor-client/ktor-client-jetty-jakarta/jvm/src/io/ktor/client/engine/jetty/jakarta/Jetty.kt @@ -26,7 +26,7 @@ import io.ktor.utils.io.* * * You can learn more about client engines from [Engines](https://ktor.io/docs/http-client-engines.html). */ -public object Jetty : HttpClientEngineFactory { +public data object Jetty : HttpClientEngineFactory { override fun create(block: JettyEngineConfig.() -> Unit): HttpClientEngine = JettyHttp2Engine(JettyEngineConfig().apply(block)) } diff --git a/ktor-client/ktor-client-jetty/api/ktor-client-jetty.api b/ktor-client/ktor-client-jetty/api/ktor-client-jetty.api index 3e86808ca47..9cdc9d6be2f 100644 --- a/ktor-client/ktor-client-jetty/api/ktor-client-jetty.api +++ b/ktor-client/ktor-client-jetty/api/ktor-client-jetty.api @@ -1,6 +1,9 @@ public final class io/ktor/client/engine/jetty/Jetty : io/ktor/client/engine/HttpClientEngineFactory { public static final field INSTANCE Lio/ktor/client/engine/jetty/Jetty; public fun create (Lkotlin/jvm/functions/Function1;)Lio/ktor/client/engine/HttpClientEngine; + public fun equals (Ljava/lang/Object;)Z + public fun hashCode ()I + public fun toString ()Ljava/lang/String; } public final class io/ktor/client/engine/jetty/JettyEngineConfig : io/ktor/client/engine/HttpClientEngineConfig { diff --git a/ktor-client/ktor-client-jetty/jvm/src/io/ktor/client/engine/jetty/Jetty.kt b/ktor-client/ktor-client-jetty/jvm/src/io/ktor/client/engine/jetty/Jetty.kt index 133d96eab51..d61b64a6576 100644 --- a/ktor-client/ktor-client-jetty/jvm/src/io/ktor/client/engine/jetty/Jetty.kt +++ b/ktor-client/ktor-client-jetty/jvm/src/io/ktor/client/engine/jetty/Jetty.kt @@ -26,7 +26,7 @@ import io.ktor.utils.io.* * * You can learn more about client engines from [Engines](https://ktor.io/docs/http-client-engines.html). */ -public object Jetty : HttpClientEngineFactory { +public data object Jetty : HttpClientEngineFactory { override fun create(block: JettyEngineConfig.() -> Unit): HttpClientEngine = JettyHttp2Engine(JettyEngineConfig().apply(block)) } diff --git a/ktor-client/ktor-client-okhttp/api/ktor-client-okhttp.api b/ktor-client/ktor-client-okhttp/api/ktor-client-okhttp.api index 931abbd1131..454b838c8e8 100644 --- a/ktor-client/ktor-client-okhttp/api/ktor-client-okhttp.api +++ b/ktor-client/ktor-client-okhttp/api/ktor-client-okhttp.api @@ -1,6 +1,9 @@ public final class io/ktor/client/engine/okhttp/OkHttp : io/ktor/client/engine/HttpClientEngineFactory { public static final field INSTANCE Lio/ktor/client/engine/okhttp/OkHttp; public fun create (Lkotlin/jvm/functions/Function1;)Lio/ktor/client/engine/HttpClientEngine; + public fun equals (Ljava/lang/Object;)Z + public fun hashCode ()I + public fun toString ()Ljava/lang/String; } public final class io/ktor/client/engine/okhttp/OkHttpConfig : io/ktor/client/engine/HttpClientEngineConfig { diff --git a/ktor-client/ktor-client-okhttp/jvm/src/io/ktor/client/engine/okhttp/OkHttp.kt b/ktor-client/ktor-client-okhttp/jvm/src/io/ktor/client/engine/okhttp/OkHttp.kt index b8e462f3703..d36221c4020 100644 --- a/ktor-client/ktor-client-okhttp/jvm/src/io/ktor/client/engine/okhttp/OkHttp.kt +++ b/ktor-client/ktor-client-okhttp/jvm/src/io/ktor/client/engine/okhttp/OkHttp.kt @@ -26,7 +26,7 @@ import io.ktor.client.engine.* * * You can learn more about client engines from [Engines](https://ktor.io/docs/http-client-engines.html). */ -public object OkHttp : HttpClientEngineFactory { +public data object OkHttp : HttpClientEngineFactory { override fun create(block: OkHttpConfig.() -> Unit): HttpClientEngine = OkHttpEngine(OkHttpConfig().apply(block)) } diff --git a/ktor-client/ktor-client-plugins/ktor-client-auth/api/ktor-client-auth.api b/ktor-client/ktor-client-plugins/ktor-client-auth/api/ktor-client-auth.api index 9198fe3d958..e2c695df713 100644 --- a/ktor-client/ktor-client-plugins/ktor-client-auth/api/ktor-client-auth.api +++ b/ktor-client/ktor-client-plugins/ktor-client-auth/api/ktor-client-auth.api @@ -1,6 +1,8 @@ public final class io/ktor/client/plugins/auth/AuthConfig { public fun ()V public final fun getProviders ()Ljava/util/List; + public final fun isUnauthorizedResponse ()Lkotlin/jvm/functions/Function2; + public final fun reAuthorizeOnResponse (Lkotlin/jvm/functions/Function2;)V } public final class io/ktor/client/plugins/auth/AuthKt { diff --git a/ktor-client/ktor-client-plugins/ktor-client-auth/api/ktor-client-auth.klib.api b/ktor-client/ktor-client-plugins/ktor-client-auth/api/ktor-client-auth.klib.api index afe2c92a770..a5f0797997e 100644 --- a/ktor-client/ktor-client-plugins/ktor-client-auth/api/ktor-client-auth.klib.api +++ b/ktor-client/ktor-client-plugins/ktor-client-auth/api/ktor-client-auth.klib.api @@ -155,6 +155,11 @@ final class io.ktor.client.plugins.auth/AuthConfig { // io.ktor.client.plugins.a final val providers // io.ktor.client.plugins.auth/AuthConfig.providers|{}providers[0] final fun (): kotlin.collections/MutableList // io.ktor.client.plugins.auth/AuthConfig.providers.|(){}[0] + + final var isUnauthorizedResponse // io.ktor.client.plugins.auth/AuthConfig.isUnauthorizedResponse|{}isUnauthorizedResponse[0] + final fun (): kotlin.coroutines/SuspendFunction1 // io.ktor.client.plugins.auth/AuthConfig.isUnauthorizedResponse.|(){}[0] + + final fun reAuthorizeOnResponse(kotlin.coroutines/SuspendFunction1) // io.ktor.client.plugins.auth/AuthConfig.reAuthorizeOnResponse|reAuthorizeOnResponse(kotlin.coroutines.SuspendFunction1){}[0] } final val io.ktor.client.plugins.auth/Auth // io.ktor.client.plugins.auth/Auth|{}Auth[0] diff --git a/ktor-client/ktor-client-plugins/ktor-client-auth/common/src/io/ktor/client/plugins/auth/Auth.kt b/ktor-client/ktor-client-plugins/ktor-client-auth/common/src/io/ktor/client/plugins/auth/Auth.kt index 1fd57fa6d25..3cbdef92196 100644 --- a/ktor-client/ktor-client-plugins/ktor-client-auth/common/src/io/ktor/client/plugins/auth/Auth.kt +++ b/ktor-client/ktor-client-plugins/ktor-client-auth/common/src/io/ktor/client/plugins/auth/Auth.kt @@ -1,14 +1,14 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.plugins.auth import io.ktor.client.* import io.ktor.client.call.* -import io.ktor.client.plugins.* import io.ktor.client.plugins.api.* import io.ktor.client.request.* +import io.ktor.client.statement.* import io.ktor.http.* import io.ktor.http.auth.* import io.ktor.util.* @@ -23,9 +23,36 @@ private class AtomicCounter { val atomic = atomic(0) } +/** + * Configuration used by [Auth] plugin. + */ @KtorDsl public class AuthConfig { + /** + * [AuthProvider] list to use. + */ public val providers: MutableList = mutableListOf() + + /** + * The currently set function to control whether a response is unauthorized and should trigger a refresh / re-auth. + * + * By default checks against HTTP status 401. + * + * You can set this value via [reAuthorizeOnResponse]. + */ + @InternalAPI + public var isUnauthorizedResponse: suspend (HttpResponse) -> Boolean = { it.status == HttpStatusCode.Unauthorized } + private set + + /** + * Sets a custom function to control whether a response is unauthorized and should trigger a refresh / re-auth. + * + * Use this to change the value of [isUnauthorizedResponse]. + */ + public fun reAuthorizeOnResponse(block: suspend (HttpResponse) -> Boolean) { + @OptIn(InternalAPI::class) + isUnauthorizedResponse = block + } } /** @@ -39,8 +66,9 @@ public val AuthCircuitBreaker: AttributeKey = AttributeKey("auth-request") * * You can learn more from [Authentication and authorization](https://ktor.io/docs/auth.html). * - * [providers] - list of auth providers to use. + * @see [AuthConfig] for configuration options. */ +@OptIn(InternalAPI::class) public val Auth: ClientPlugin = createClientPlugin("Auth", ::AuthConfig) { val providers = pluginConfig.providers.toList() @@ -50,7 +78,6 @@ public val Auth: ClientPlugin = createClientPlugin("Auth", ::AuthCon val tokenVersionsAttributeKey = AttributeKey>("ProviderVersionAttributeKey") - @OptIn(InternalAPI::class) fun findProvider( call: HttpClientCall, candidateProviders: Set @@ -64,10 +91,10 @@ public val Auth: ClientPlugin = createClientPlugin("Auth", ::AuthCon } authHeaders.isEmpty() -> { - LOGGER.trace( - "401 response ${call.request.url} has no or empty \"WWW-Authenticate\" header. " + + LOGGER.trace { + "Unauthorized response ${call.request.url} has no or empty \"WWW-Authenticate\" header. " + "Can not add or refresh token" - ) + } null } @@ -88,9 +115,9 @@ public val Auth: ClientPlugin = createClientPlugin("Auth", ::AuthCon val requestTokenVersion = requestTokenVersions[provider] if (requestTokenVersion != null && requestTokenVersion >= tokenVersion.atomic.value) { - LOGGER.trace("Refreshing token for ${call.request.url}") + LOGGER.trace { "Refreshing token for ${call.request.url}" } if (!provider.refreshToken(call.response)) { - LOGGER.trace("Refreshing token failed for ${call.request.url}") + LOGGER.trace { "Refreshing token failed for ${call.request.url}" } return false } else { requestTokenVersions[provider] = tokenVersion.atomic.incrementAndGet() @@ -99,7 +126,6 @@ public val Auth: ClientPlugin = createClientPlugin("Auth", ::AuthCon return true } - @OptIn(InternalAPI::class) suspend fun Send.Sender.executeWithNewToken( call: HttpClientCall, provider: AuthProvider, @@ -111,13 +137,13 @@ public val Auth: ClientPlugin = createClientPlugin("Auth", ::AuthCon provider.addRequestHeaders(request, authHeader) request.attributes.put(AuthCircuitBreaker, Unit) - LOGGER.trace("Sending new request to ${call.request.url}") + LOGGER.trace { "Sending new request to ${call.request.url}" } return proceed(request) } onRequest { request, _ -> providers.filter { it.sendWithoutRequest(request) }.forEach { provider -> - LOGGER.trace("Adding auth headers for ${request.url} from provider $provider") + LOGGER.trace { "Adding auth headers for ${request.url} from provider $provider" } val tokenVersion = tokenVersions.computeIfAbsent(provider) { AtomicCounter() } val requestTokenVersions = request.attributes .computeIfAbsent(tokenVersionsAttributeKey) { mutableMapOf() } @@ -128,22 +154,22 @@ public val Auth: ClientPlugin = createClientPlugin("Auth", ::AuthCon on(Send) { originalRequest -> val origin = proceed(originalRequest) - if (origin.response.status != HttpStatusCode.Unauthorized) return@on origin + if (!pluginConfig.isUnauthorizedResponse(origin.response)) return@on origin if (origin.request.attributes.contains(AuthCircuitBreaker)) return@on origin var call = origin val candidateProviders = HashSet(providers) - while (call.response.status == HttpStatusCode.Unauthorized) { - LOGGER.trace("Received 401 for ${call.request.url}") + while (pluginConfig.isUnauthorizedResponse(call.response)) { + LOGGER.trace { "Unauthorized response for ${call.request.url}" } val (provider, authHeader) = findProvider(call, candidateProviders) ?: run { - LOGGER.trace("Can not find auth provider for ${call.request.url}") + LOGGER.trace { "Can not find auth provider for ${call.request.url}" } return@on call } - LOGGER.trace("Using provider $provider for ${call.request.url}") + LOGGER.trace { "Using provider $provider for ${call.request.url}" } candidateProviders.remove(provider) if (!refreshTokenIfNeeded(call, provider, originalRequest)) return@on call diff --git a/ktor-client/ktor-client-plugins/ktor-client-auth/common/test/io/ktor/client/plugins/auth/AuthTest.kt b/ktor-client/ktor-client-plugins/ktor-client-auth/common/test/io/ktor/client/plugins/auth/AuthTest.kt index 8809eb5f08a..20107f77f51 100644 --- a/ktor-client/ktor-client-plugins/ktor-client-auth/common/test/io/ktor/client/plugins/auth/AuthTest.kt +++ b/ktor-client/ktor-client-plugins/ktor-client-auth/common/test/io/ktor/client/plugins/auth/AuthTest.kt @@ -23,7 +23,7 @@ import kotlin.test.assertFailsWith class AuthTest : ClientLoader() { @Test - fun testDigestAuthLegacy() = clientTests(listOf("Js", "native")) { + fun testDigestAuthLegacy() = clientTests(listOf("Js", "native:*")) { config { install(Auth) { digest { @@ -43,7 +43,7 @@ class AuthTest : ClientLoader() { } @Test - fun testDigestAuth() = clientTests(listOf("Js", "native")) { + fun testDigestAuth() = clientTests(listOf("Js", "native:*")) { config { install(Auth) { digest { @@ -60,7 +60,7 @@ class AuthTest : ClientLoader() { } @Test - fun testDigestAuthPerRealm() = clientTests(listOf("Js", "native")) { + fun testDigestAuthPerRealm() = clientTests(listOf("Js", "native:*")) { config { install(Auth) { digest { @@ -84,7 +84,7 @@ class AuthTest : ClientLoader() { } @Test - fun testDigestAuthSHA256() = clientTests(listOf("Js", "native")) { + fun testDigestAuthSHA256() = clientTests(listOf("Js", "native:*")) { config { install(Auth) { digest { @@ -403,6 +403,27 @@ class AuthTest : ClientLoader() { } } + @Test + fun testForbiddenBearerAuthWithInvalidAccessAndValidRefreshTokens() = clientTests { + config { + install(Auth) { + reAuthorizeOnResponse { it.status == HttpStatusCode.Forbidden } + bearer { + refreshTokens { BearerTokens("valid", "refresh") } + loadTokens { BearerTokens("invalid", "refresh") } + } + } + + expectSuccess = false + } + + test { client -> + client.prepareGet("$TEST_SERVER/auth/bearer/test-refresh?status=403").execute { + assertEquals(HttpStatusCode.OK, it.status) + } + } + } + // The return of refreshTokenFun is null, cause it should not be called at all, if loadTokensFun returns valid tokens @Test fun testUnauthorizedBearerAuthWithValidAccessTokenAndInvalidRefreshToken() = clientTests { diff --git a/ktor-client/ktor-client-plugins/ktor-client-content-negotiation/api/ktor-client-content-negotiation.api b/ktor-client/ktor-client-plugins/ktor-client-content-negotiation/api/ktor-client-content-negotiation.api index ad13c0a333b..912d384413f 100644 --- a/ktor-client/ktor-client-plugins/ktor-client-content-negotiation/api/ktor-client-content-negotiation.api +++ b/ktor-client/ktor-client-plugins/ktor-client-content-negotiation/api/ktor-client-content-negotiation.api @@ -5,13 +5,16 @@ public final class io/ktor/client/plugins/contentnegotiation/ContentConverterExc public final class io/ktor/client/plugins/contentnegotiation/ContentNegotiationConfig : io/ktor/serialization/Configuration { public fun ()V public final fun clearIgnoredTypes ()V + public final fun getDefaultAcceptHeaderQValue ()Ljava/lang/Double; public final fun ignoreType (Lkotlin/reflect/KClass;)V public final fun register (Lio/ktor/http/ContentType;Lio/ktor/serialization/ContentConverter;Lio/ktor/http/ContentTypeMatcher;Lkotlin/jvm/functions/Function1;)V public fun register (Lio/ktor/http/ContentType;Lio/ktor/serialization/ContentConverter;Lkotlin/jvm/functions/Function1;)V public final fun removeIgnoredType (Lkotlin/reflect/KClass;)V + public final fun setDefaultAcceptHeaderQValue (Ljava/lang/Double;)V } public final class io/ktor/client/plugins/contentnegotiation/ContentNegotiationKt { + public static final fun exclude (Lio/ktor/client/request/HttpRequestBuilder;[Lio/ktor/http/ContentType;)V public static final fun getContentNegotiation ()Lio/ktor/client/plugins/api/ClientPlugin; } diff --git a/ktor-client/ktor-client-plugins/ktor-client-content-negotiation/api/ktor-client-content-negotiation.klib.api b/ktor-client/ktor-client-plugins/ktor-client-content-negotiation/api/ktor-client-content-negotiation.klib.api index 06315ef5525..2638ca4ba91 100644 --- a/ktor-client/ktor-client-plugins/ktor-client-content-negotiation/api/ktor-client-content-negotiation.klib.api +++ b/ktor-client/ktor-client-plugins/ktor-client-content-negotiation/api/ktor-client-content-negotiation.klib.api @@ -13,6 +13,10 @@ final class io.ktor.client.plugins.contentnegotiation/ContentConverterException final class io.ktor.client.plugins.contentnegotiation/ContentNegotiationConfig : io.ktor.serialization/Configuration { // io.ktor.client.plugins.contentnegotiation/ContentNegotiationConfig|null[0] constructor () // io.ktor.client.plugins.contentnegotiation/ContentNegotiationConfig.|(){}[0] + final var defaultAcceptHeaderQValue // io.ktor.client.plugins.contentnegotiation/ContentNegotiationConfig.defaultAcceptHeaderQValue|{}defaultAcceptHeaderQValue[0] + final fun (): kotlin/Double? // io.ktor.client.plugins.contentnegotiation/ContentNegotiationConfig.defaultAcceptHeaderQValue.|(){}[0] + final fun (kotlin/Double?) // io.ktor.client.plugins.contentnegotiation/ContentNegotiationConfig.defaultAcceptHeaderQValue.|(kotlin.Double?){}[0] + final fun <#A1: io.ktor.serialization/ContentConverter> register(io.ktor.http/ContentType, #A1, io.ktor.http/ContentTypeMatcher, kotlin/Function1<#A1, kotlin/Unit>) // io.ktor.client.plugins.contentnegotiation/ContentNegotiationConfig.register|register(io.ktor.http.ContentType;0:0;io.ktor.http.ContentTypeMatcher;kotlin.Function1<0:0,kotlin.Unit>){0§}[0] final fun <#A1: io.ktor.serialization/ContentConverter> register(io.ktor.http/ContentType, #A1, kotlin/Function1<#A1, kotlin/Unit>) // io.ktor.client.plugins.contentnegotiation/ContentNegotiationConfig.register|register(io.ktor.http.ContentType;0:0;kotlin.Function1<0:0,kotlin.Unit>){0§}[0] final fun clearIgnoredTypes() // io.ktor.client.plugins.contentnegotiation/ContentNegotiationConfig.clearIgnoredTypes|clearIgnoredTypes(){}[0] @@ -28,3 +32,5 @@ final object io.ktor.client.plugins.contentnegotiation/JsonContentTypeMatcher : final val io.ktor.client.plugins.contentnegotiation/ContentNegotiation // io.ktor.client.plugins.contentnegotiation/ContentNegotiation|{}ContentNegotiation[0] final fun (): io.ktor.client.plugins.api/ClientPlugin // io.ktor.client.plugins.contentnegotiation/ContentNegotiation.|(){}[0] + +final fun (io.ktor.client.request/HttpRequestBuilder).io.ktor.client.plugins.contentnegotiation/exclude(kotlin/Array...) // io.ktor.client.plugins.contentnegotiation/exclude|exclude@io.ktor.client.request.HttpRequestBuilder(kotlin.Array...){}[0] diff --git a/ktor-client/ktor-client-plugins/ktor-client-content-negotiation/common/src/io/ktor/client/plugins/contentnegotiation/ContentNegotiation.kt b/ktor-client/ktor-client-plugins/ktor-client-content-negotiation/common/src/io/ktor/client/plugins/contentnegotiation/ContentNegotiation.kt index de812bd1ea9..21edbe71305 100644 --- a/ktor-client/ktor-client-plugins/ktor-client-content-negotiation/common/src/io/ktor/client/plugins/contentnegotiation/ContentNegotiation.kt +++ b/ktor-client/ktor-client-plugins/ktor-client-content-negotiation/common/src/io/ktor/client/plugins/contentnegotiation/ContentNegotiation.kt @@ -11,6 +11,7 @@ import io.ktor.client.utils.* import io.ktor.http.* import io.ktor.http.content.* import io.ktor.serialization.* +import io.ktor.util.AttributeKey import io.ktor.util.logging.* import io.ktor.util.reflect.* import io.ktor.utils.io.* @@ -29,6 +30,12 @@ internal val DefaultCommonIgnoredTypes: Set> = setOf( internal expect val DefaultIgnoredTypes: Set> +/** + * The content types that are excluded from the `Accept` header for this specific request. Use the + * [exclude] `HttpRequestBuilder` extension to set this attribute on a request. + */ +internal val ExcludedContentTypes: AttributeKey> = AttributeKey("ExcludedContentTypesAttr") + /** * A [ContentNegotiation] configuration that is used during installation. */ @@ -46,6 +53,12 @@ public class ContentNegotiationConfig : Configuration { internal val registrations = mutableListOf() + /** + * By default, `Accept` headers for registered content types will have no q value (implicit 1.0). Set this to + * change that behavior. This is useful to override the preferred `Accept` content types on a per-request basis. + */ + public var defaultAcceptHeaderQValue: Double? = null + /** * Registers a [contentType] to a specified [converter] with an optional [configuration] script for a converter. */ @@ -54,8 +67,8 @@ public class ContentNegotiationConfig : Configuration { converter: T, configuration: T.() -> Unit ) { - val matcher = when (contentType) { - ContentType.Application.Json -> JsonContentTypeMatcher + val matcher = when { + contentType.match(ContentType.Application.Json) -> JsonContentTypeMatcher else -> defaultMatcher(contentType) } register(contentType, converter, matcher, configuration) @@ -140,11 +153,25 @@ public val ContentNegotiation: ClientPlugin = createCl val ignoredTypes: Set> = pluginConfig.ignoredTypes suspend fun convertRequest(request: HttpRequestBuilder, body: Any): OutgoingContent? { - registrations.forEach { - LOGGER.trace("Adding Accept=${it.contentTypeToSend.contentType} header for ${request.url}") + val requestRegistrations = if (request.attributes.contains(ExcludedContentTypes)) { + val excluded = request.attributes[ExcludedContentTypes] + registrations.filter { registration -> excluded.none { registration.contentTypeToSend.match(it) } } + } else { + registrations + } - if (request.headers.contains(HttpHeaders.Accept, it.contentTypeToSend.toString())) return@forEach - request.accept(it.contentTypeToSend) + val acceptHeaders = request.headers.getAll(HttpHeaders.Accept).orEmpty() + requestRegistrations.forEach { + if (acceptHeaders.none { h -> ContentType.parse(h).match(it.contentTypeToSend) }) { + // automatically added headers get a lower content type priority, so user-specified accept headers + // with higher q or implicit q=1 will take precedence + val contentTypeToSend = when (val qValue = pluginConfig.defaultAcceptHeaderQValue) { + null -> it.contentTypeToSend + else -> it.contentTypeToSend.withParameter("q", qValue.toString()) + } + LOGGER.trace("Adding Accept=$contentTypeToSend header for ${request.url}") + request.accept(contentTypeToSend) + } } if (body is OutgoingContent || ignoredTypes.any { it.isInstance(body) }) { @@ -251,3 +278,14 @@ public val ContentNegotiation: ClientPlugin = createCl } public class ContentConverterException(message: String) : Exception(message) + +/** + * Excludes the given [ContentType] from the list of types that will be sent in the `Accept` header by + * the [ContentNegotiation] plugin. Can be used to not accept specific types for particular requests. + * This can be called multiple times to exclude multiple content types, or multiple content types can + * be passed in a single call. + */ +public fun HttpRequestBuilder.exclude(vararg contentType: ContentType) { + val excludedContentTypes = attributes.getOrNull(ExcludedContentTypes).orEmpty() + attributes.put(ExcludedContentTypes, excludedContentTypes + contentType) +} diff --git a/ktor-client/ktor-client-plugins/ktor-client-content-negotiation/common/test/io/ktor/client/plugins/ContentNegotiationTests.kt b/ktor-client/ktor-client-plugins/ktor-client-content-negotiation/common/test/io/ktor/client/plugins/ContentNegotiationTests.kt index 8812f098753..38783d52009 100644 --- a/ktor-client/ktor-client-plugins/ktor-client-content-negotiation/common/test/io/ktor/client/plugins/ContentNegotiationTests.kt +++ b/ktor-client/ktor-client-plugins/ktor-client-content-negotiation/common/test/io/ktor/client/plugins/ContentNegotiationTests.kt @@ -71,6 +71,166 @@ class ContentNegotiationTests { } } + @Test + fun addAcceptHeadersWithSingleExclusion() { + testWithEngine(MockEngine) { + val registeredTypesToSend = listOf( + ContentType("testing", "a"), + ContentType("testing", "b"), + ContentType("testing", "c") + ) + + setupWithContentNegotiation { + for (typeToSend in registeredTypesToSend) { + register(typeToSend, TestContentConverter()) + } + } + + test { client -> + client.get("https://test.com/") { + exclude(ContentType("testing", "b")) + }.apply { + val sentTypes = assertNotNull(call.request.headers.getAll(HttpHeaders.Accept)) + .map { ContentType.parse(it) } + + // Order NOT tested + for (typeToSend in registeredTypesToSend.filter { it.contentSubtype != "b" }) { + assertContains(sentTypes, typeToSend) + } + assertNull(sentTypes.firstOrNull { it.contentSubtype == "b" }) + } + } + } + } + + @Test + fun addAcceptHeadersWithExclusionMatchingParameterizedType() { + testWithEngine(MockEngine) { + val registeredTypesToSend = listOf( + ContentType("testing", "a").withParameter("foo", "bar"), + ContentType("testing", "b").withParameter("foo", "bar"), + ContentType("testing", "c").withParameter("foo", "bar") + ) + + setupWithContentNegotiation { + for (typeToSend in registeredTypesToSend) { + register(typeToSend, TestContentConverter()) + } + } + + test { client -> + client.get("https://test.com/") { + exclude(ContentType("testing", "b")) + }.apply { + val sentTypes = assertNotNull(call.request.headers.getAll(HttpHeaders.Accept)) + .map { ContentType.parse(it) } + + // Order NOT tested + for (typeToSend in registeredTypesToSend.filter { it.contentSubtype != "b" }) { + assertContains(sentTypes, typeToSend) + } + assertNull(sentTypes.firstOrNull { it.contentSubtype == "b" }) + } + } + } + } + + @Test + fun addAcceptHeadersWithMultipleExclusions() { + testWithEngine(MockEngine) { + val registeredTypesToSend = listOf( + ContentType("testing", "a"), + ContentType("testing", "b"), + ContentType("testing", "c") + ) + + setupWithContentNegotiation { + for (typeToSend in registeredTypesToSend) { + register(typeToSend, TestContentConverter()) + } + } + + test { client -> + client.get("https://test.com/") { + exclude(ContentType("testing", "b")) + exclude(ContentType("testing", "c")) + }.apply { + val sentTypes = assertNotNull(call.request.headers.getAll(HttpHeaders.Accept)) + .map { ContentType.parse(it) } + + // Order NOT tested + assertTrue(sentTypes.size == 1) + assertContains(sentTypes, ContentType("testing", "a")) + } + } + + test { client -> + client.get("https://test.com/") { + exclude(ContentType("testing", "b"), ContentType("testing", "c")) + }.apply { + val sentTypes = assertNotNull(call.request.headers.getAll(HttpHeaders.Accept)) + .map { ContentType.parse(it) } + + // Order NOT tested + assertTrue(sentTypes.size == 1) + assertContains(sentTypes, ContentType("testing", "a")) + } + } + } + } + + @Test + fun addAcceptHeadersWithDefaultQValue() { + testWithEngine(MockEngine) { + val registeredTypesToSend = listOf( + ContentType("testing", "a"), + ContentType("testing", "b"), + ContentType("testing", "c") + ) + + setupWithContentNegotiation { + for (typeToSend in registeredTypesToSend) { + register(typeToSend, TestContentConverter()) + defaultAcceptHeaderQValue = 0.8 + } + } + + test { client -> + client.get("https://test.com/").apply { + val sentTypes = assertNotNull(call.request.headers.getAll(HttpHeaders.Accept)) + .map { ContentType.parse(it) } + + // Order NOT tested + for (typeToSend in registeredTypesToSend) { + assertContains(sentTypes, typeToSend.withParameter("q", "0.8")) + } + } + } + } + } + + @Test + fun skipAddAcceptHeadersWithMatchingContentType() { + testWithEngine(MockEngine) { + setupWithContentNegotiation { + register(ContentType("testing", "a"), TestContentConverter()) + } + + test { client -> + client.get("https://test.com/") { + // our explicitly specified lower q-value should take precedence + accept(ContentType("testing", "a", listOf(HeaderValueParam("q", "0.5")))) + }.apply { + val sentTypes = assertNotNull(call.request.headers.getAll(HttpHeaders.Accept)) + .map { ContentType.parse(it) } + + assertContains(sentTypes, ContentType("testing", "a", listOf(HeaderValueParam("q", "0.5")))) + assertEquals(1, sentTypes.size) + } + } + } + } + @Test fun testKeepsContentType() { testWithEngine(MockEngine) { diff --git a/ktor-client/ktor-client-tests/build.gradle.kts b/ktor-client/ktor-client-tests/build.gradle.kts index 2de670961aa..b28e935b9c1 100644 --- a/ktor-client/ktor-client-tests/build.gradle.kts +++ b/ktor-client/ktor-client-tests/build.gradle.kts @@ -2,7 +2,7 @@ * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ -import test.server.* +import test.server.TestServerPlugin description = "Common tests for client" @@ -68,9 +68,9 @@ kotlin.sourceSets { } } - jvmAndPosixTest { + commonTest { dependencies { - runtimeOnly(project(":ktor-client:ktor-client-cio")) + api(project(":ktor-client:ktor-client-cio")) } } diff --git a/ktor-client/ktor-client-tests/common/src/io/ktor/client/tests/utils/ClientLoader.kt b/ktor-client/ktor-client-tests/common/src/io/ktor/client/tests/utils/ClientLoader.kt index ecd84cc776c..da7acf100b8 100644 --- a/ktor-client/ktor-client-tests/common/src/io/ktor/client/tests/utils/ClientLoader.kt +++ b/ktor-client/ktor-client-tests/common/src/io/ktor/client/tests/utils/ClientLoader.kt @@ -6,11 +6,18 @@ package io.ktor.client.tests.utils import io.ktor.client.engine.* import kotlinx.coroutines.test.* +import kotlin.time.* +import kotlin.time.Duration.Companion.minutes + +internal expect val enginesToTest: Iterable> +internal expect val platformName: String +internal expect fun platformDumpCoroutines() +internal expect fun platformWaitForAllCoroutines() /** * Helper interface to test client. */ -expect abstract class ClientLoader(timeoutSeconds: Int = 60) { +abstract class ClientLoader(private val timeout: Duration = 1.minutes) { /** * Perform test against all clients from dependencies. */ @@ -19,10 +26,108 @@ expect abstract class ClientLoader(timeoutSeconds: Int = 60) { onlyWithEngine: String? = null, retries: Int = 1, block: suspend TestClientBuilder.() -> Unit - ): TestResult + ): TestResult = runTest(timeout = timeout) { + val skipPatterns = skipEngines.map { SkipEnginePattern.parse(it.lowercase()) } + + val failures: List = enginesToTest.mapNotNull { engineFactory -> + val engineName = engineFactory.toString().lowercase() + + if (shouldRun(engineName, skipPatterns, onlyWithEngine?.lowercase())) { + try { + println("Run test with engine $engineName") + // run test here + performTestWithEngine(engineFactory, this@ClientLoader, retries, block) + null // engine test passed + } catch (cause: Throwable) { + // engine test failed, save failure to report after run for every engine. + TestFailure(engineName, cause) + } + } else { + println("Skipping test with engine $engineName") + null // engine skipped + } + } + + if (failures.isNotEmpty()) { + val message = buildString { + appendLine("Test failed for engines: ${failures.map { it.engineName }}") + failures.forEach { + appendLine("Test failed for engine '$platformName:${it.engineName}' with:") + appendLine(it.cause.stackTraceToString().prependIndent(" ")) + } + } + throw AssertionError(message) + } + } + + private fun shouldRun( + engineName: String, + skipEnginePatterns: List, + onlyWithEngine: String? + ): Boolean { + if (onlyWithEngine != null && onlyWithEngine != engineName) return false + + skipEnginePatterns.forEach { + if (it.matches(engineName)) return false + } + + return true + } /** * Print coroutines in debug mode. */ - fun dumpCoroutines() + fun dumpCoroutines(): Unit = platformDumpCoroutines() + + /** + * Issues to fix before unlock: + * 1. Pinger & Ponger in ws + * 2. Nonce generator + */ + // @After + fun waitForAllCoroutines(): Unit = platformWaitForAllCoroutines() +} + +private data class SkipEnginePattern( + val skippedPlatform: String?, // null means * or empty + val skippedEngine: String?, // null means * or empty +) { + fun matches(engineName: String): Boolean { + var result = true + if (skippedEngine != null) { + result = result && engineName == skippedEngine + } + if (result && skippedPlatform != null) { + result = result && platformName.startsWith(skippedPlatform) + } + return result + } + + companion object { + fun parse(pattern: String): SkipEnginePattern { + val parts = pattern.split(":").map { it.takeIf { it != "*" } } + val platform: String? + val engine: String? + when (parts.size) { + 1 -> { + platform = null + engine = parts[0] + } + + 2 -> { + platform = parts[0] + engine = parts[1] + } + + else -> error("Skip engine pattern should consist of two parts: PLATFORM:ENGINE or ENGINE") + } + + if (platform == null && engine == null) { + error("Skip engine pattern should consist of two parts: PLATFORM:ENGINE or ENGINE") + } + return SkipEnginePattern(platform, engine) + } + } } + +private class TestFailure(val engineName: String, val cause: Throwable) diff --git a/ktor-client/ktor-client-tests/common/src/io/ktor/client/tests/utils/CommonClientTestUtils.kt b/ktor-client/ktor-client-tests/common/src/io/ktor/client/tests/utils/CommonClientTestUtils.kt index 59ac996b784..1036094a601 100644 --- a/ktor-client/ktor-client-tests/common/src/io/ktor/client/tests/utils/CommonClientTestUtils.kt +++ b/ktor-client/ktor-client-tests/common/src/io/ktor/client/tests/utils/CommonClientTestUtils.kt @@ -1,16 +1,13 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ -@file:Suppress("NO_EXPLICIT_RETURN_TYPE_IN_API_MODE_WARNING", "KDocMissingDocumentation") - package io.ktor.client.tests.utils import io.ktor.client.* import io.ktor.client.engine.* -import io.ktor.utils.io.core.* import kotlinx.coroutines.* -import kotlinx.coroutines.test.* +import kotlinx.coroutines.test.runTest import kotlin.time.Duration.Companion.milliseconds /** @@ -65,7 +62,6 @@ private fun testWithClient( /** * Perform test with selected client engine [factory]. */ -@OptIn(DelicateCoroutinesApi::class) fun testWithEngine( factory: HttpClientEngineFactory, loader: ClientLoader? = null, @@ -73,6 +69,16 @@ fun testWithEngine( retries: Int = 1, block: suspend TestClientBuilder.() -> Unit ) = runTest(timeout = timeoutMillis.milliseconds) { + performTestWithEngine(factory, loader, retries, block) +} + +@OptIn(DelicateCoroutinesApi::class) +suspend fun performTestWithEngine( + factory: HttpClientEngineFactory, + loader: ClientLoader? = null, + retries: Int = 1, + block: suspend TestClientBuilder.() -> Unit +) { val builder = TestClientBuilder().apply { block() } if (builder.dumpAfterDelay > 0 && loader != null) { diff --git a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/BodyProgressTest.kt b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/BodyProgressTest.kt index 41c47af0e37..34d286b0b88 100644 --- a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/BodyProgressTest.kt +++ b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/BodyProgressTest.kt @@ -28,7 +28,7 @@ private val TEST_ARRAY = ByteArray(8 * 1025) { 1 } private val TEST_NAME = "123".repeat(5000) @OptIn(DelicateCoroutinesApi::class) -class BodyProgressTest : ClientLoader(timeoutSeconds = 60) { +class BodyProgressTest : ClientLoader() { @Serializable data class User(val login: String, val id: Long) diff --git a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/ContentTest.kt b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/ContentTest.kt index 5269fb0f89a..feba14fad05 100644 --- a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/ContentTest.kt +++ b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/ContentTest.kt @@ -42,7 +42,7 @@ val testArrays = testSize.map { makeArray(it) } -class ContentTest : ClientLoader(5 * 60) { +class ContentTest : ClientLoader(5.minutes) { @Test fun testGetFormData() = clientTests { diff --git a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/EventsTest.kt b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/EventsTest.kt index 55195d6d085..fbf9b12ff05 100644 --- a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/EventsTest.kt +++ b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/EventsTest.kt @@ -74,7 +74,7 @@ class EventsTest : ClientLoader() { } @Test - fun testRedirectEvent() = clientTests(listOf("js")) { + fun testRedirectEvent() = clientTests(listOf("Js")) { test { client -> counter.value = 0 client.monitor.subscribe(HttpResponseRedirectEvent) { diff --git a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/HttpStatementTest.kt b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/HttpStatementTest.kt index 0371b934c74..00b8f69fd35 100644 --- a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/HttpStatementTest.kt +++ b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/HttpStatementTest.kt @@ -38,7 +38,7 @@ class HttpStatementTest : ClientLoader() { } @Test - fun testGZipFromSavedResponse() = clientTests(listOf("native:CIO")) { + fun testGZipFromSavedResponse() = clientTests(listOf("native:CIO", "web:CIO")) { config { ContentEncoding { gzip() diff --git a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/HttpTimeoutTest.kt b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/HttpTimeoutTest.kt index ff26ae629d1..2a0233790f1 100644 --- a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/HttpTimeoutTest.kt +++ b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/HttpTimeoutTest.kt @@ -325,7 +325,7 @@ class HttpTimeoutTest : ClientLoader() { // Js can't configure test timeout in browser @Test - fun testRedirect() = clientTests(listOf("js"), retries = 5) { + fun testRedirect() = clientTests(listOf("Js"), retries = 5) { config { install(HttpTimeout) { requestTimeoutMillis = 10000 } } @@ -342,7 +342,7 @@ class HttpTimeoutTest : ClientLoader() { // Js can't configure test timeout in browser @Test - fun testRedirectPerRequestAttributes() = clientTests(listOf("js")) { + fun testRedirectPerRequestAttributes() = clientTests(listOf("Js")) { config { install(HttpTimeout) } @@ -427,7 +427,7 @@ class HttpTimeoutTest : ClientLoader() { } @Test - fun testConnectionRefusedException() = clientTests(listOf("Js", "native:*", "win:*")) { + fun testConnectionRefusedException() = clientTests(listOf("Js", "native:*", "jvm/win:*")) { config { install(HttpTimeout) { connectTimeoutMillis = 1000 } } @@ -443,7 +443,7 @@ class HttpTimeoutTest : ClientLoader() { } @Test - fun testSocketTimeoutRead() = clientTests(listOf("Js", "native:CIO", "Java")) { + fun testSocketTimeoutRead() = clientTests(listOf("Js", "native:CIO", "Curl", "Java")) { config { install(HttpTimeout) { socketTimeoutMillis = 1000 } } @@ -458,7 +458,9 @@ class HttpTimeoutTest : ClientLoader() { } @Test - fun testSocketTimeoutReadPerRequestAttributes() = clientTests(listOf("Js", "native:CIO", "Java", "Apache5")) { + fun testSocketTimeoutReadPerRequestAttributes() = clientTests( + listOf("Js", "native:CIO", "Curl", "Java", "Apache5") + ) { config { install(HttpTimeout) } @@ -475,7 +477,9 @@ class HttpTimeoutTest : ClientLoader() { } @Test - fun testSocketTimeoutWriteFailOnWrite() = clientTests(listOf("Js", "Android", "native:CIO", "Java")) { + fun testSocketTimeoutWriteFailOnWrite() = clientTests( + listOf("Js", "Android", "Curl", "native:CIO", "web:CIO", "Java") + ) { config { install(HttpTimeout) { socketTimeoutMillis = 500 } } @@ -489,7 +493,7 @@ class HttpTimeoutTest : ClientLoader() { @Test fun testSocketTimeoutWriteFailOnWritePerRequestAttributes() = clientTests( - listOf("Js", "Android", "Apache5", "native:CIO", "Java") + listOf("Js", "Android", "Apache5", "Curl", "native:CIO", "web:CIO", "Java") ) { config { install(HttpTimeout) diff --git a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/JsonTest.kt b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/JsonTest.kt index 58b59a3ed90..1cd73017f76 100644 --- a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/JsonTest.kt +++ b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/JsonTest.kt @@ -22,7 +22,7 @@ class JsonTest : ClientLoader() { @OptIn(ExperimentalStdlibApi::class) @Test - fun testUserGenerics() = clientTests(listOf("js")) { + fun testUserGenerics() = clientTests(listOf("Js")) { config { install(ContentNegotiation) { json() } } diff --git a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/LoggingTest.kt b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/LoggingTest.kt index d9a319b375e..d9a09503802 100644 --- a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/LoggingTest.kt +++ b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/LoggingTest.kt @@ -351,7 +351,7 @@ class LoggingTest : ClientLoader() { } @Test - fun testLoggingWithCompression() = clientTests(listOf("native:CIO")) { + fun testLoggingWithCompression() = clientTests(listOf("Darwin", "native:CIO", "DarwinLegacy", "web:CIO")) { val testLogger = TestLogger( "REQUEST: http://127.0.0.1:8080/compression/deflate", "METHOD: HttpMethod(value=GET)", diff --git a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/MultiPartFormDataTest.kt b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/MultiPartFormDataTest.kt index 74cc70ebca7..7d947df4211 100644 --- a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/MultiPartFormDataTest.kt +++ b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/MultiPartFormDataTest.kt @@ -4,13 +4,15 @@ package io.ktor.client.tests +import io.ktor.client.call.* import io.ktor.client.request.* import io.ktor.client.request.forms.* import io.ktor.client.tests.utils.* import io.ktor.http.* +import io.ktor.http.content.* +import io.ktor.utils.io.* import kotlinx.io.* import kotlin.test.* -import kotlin.time.* /** * Tests client request with multi-part form data. @@ -25,7 +27,7 @@ class MultiPartFormDataTest : ClientLoader() { } @Test - fun testMultiPartFormData() = clientTests(listOf("native")) { + fun testMultiPartFormData() = clientTests(listOf("native:*")) { test { client -> val result = client.preparePost("$TEST_SERVER/multipart") { setBody( @@ -48,4 +50,41 @@ class MultiPartFormDataTest : ClientLoader() { assertTrue(response.status.isSuccess()) } } + + @Test + fun testReceiveMultiPartFormData() = clientTests { + test { client -> + val response = client.post("$TEST_SERVER/multipart/receive") + + val multipart = response.body() + var textFound = false + var fileFound = false + + multipart.forEachPart { part -> + when (part) { + is PartData.FormItem -> { + assertEquals("text", part.name) + assertEquals("Hello, World!", part.value) + textFound = true + } + is PartData.FileItem -> { + assertEquals("file", part.name) + assertEquals("test.bin", part.originalFileName) + + val bytes = part.provider().readRemaining().readByteArray() + assertEquals(1024, bytes.size) + for (i in bytes.indices) { + assertEquals(i.toByte(), bytes[i]) + } + fileFound = true + } + else -> fail("Unexpected part type: ${part::class.simpleName}") + } + part.dispose() + } + + assertTrue(textFound, "Text part not found") + assertTrue(fileFound, "File part not found") + } + } } diff --git a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/ProxyTest.kt b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/ProxyTest.kt index 970099950b8..32f28ce918d 100644 --- a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/ProxyTest.kt +++ b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/ProxyTest.kt @@ -19,7 +19,7 @@ data class ProxyResponse(val status: String) class ProxyTest : ClientLoader() { @Test - fun testHttpProxy() = clientTests(listOf("Js")) { + fun testHttpProxy() = clientTests(listOf("Js", "web:CIO")) { config { engine { proxy = ProxyBuilder.http(TCP_SERVER) @@ -33,7 +33,7 @@ class ProxyTest : ClientLoader() { } @Test - fun testProxyWithSerialization() = clientTests(listOf("Js")) { + fun testProxyWithSerialization() = clientTests(listOf("Js", "web:CIO")) { config { engine { proxy = ProxyBuilder.http(TCP_SERVER) diff --git a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/WebSocketTest.kt b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/WebSocketTest.kt index 21fe8656afa..144970bddb2 100644 --- a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/WebSocketTest.kt +++ b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/WebSocketTest.kt @@ -329,7 +329,7 @@ class WebSocketTest : ClientLoader() { @Ignore // TODO KTOR-7088 @Test fun testImmediateReceiveAfterConnect() = clientTests( - ENGINES_WITHOUT_WS + "Darwin" + "js" // TODO KTOR-7088 + ENGINES_WITHOUT_WS + "Darwin" + "Js" // TODO KTOR-7088 ) { config { install(WebSockets) diff --git a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/plugins/CacheLegacyStorageTest.kt b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/plugins/CacheLegacyStorageTest.kt index 536c3b38e2b..5e3f7f26c45 100644 --- a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/plugins/CacheLegacyStorageTest.kt +++ b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/plugins/CacheLegacyStorageTest.kt @@ -569,7 +569,7 @@ class CacheLegacyStorageTest : ClientLoader() { } @Test - fun testPublicAndPrivateCache() = clientTests(listOf("native")) { + fun testPublicAndPrivateCache() = clientTests(listOf("native:*")) { val publicStorage = HttpCacheStorage.Unlimited() val privateStorage = HttpCacheStorage.Unlimited() config { diff --git a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/plugins/CookiesIntegrationTests.kt b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/plugins/CookiesIntegrationTests.kt index 6d8b63216a5..d331b23f1f1 100644 --- a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/plugins/CookiesIntegrationTests.kt +++ b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/plugins/CookiesIntegrationTests.kt @@ -106,7 +106,7 @@ class CookiesIntegrationTests : ClientLoader() { } @Test - fun testPath() = clientTests(listOf("js")) { + fun testPath() = clientTests(listOf("Js")) { config { install(HttpCookies) } diff --git a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/plugins/SSESessionParserTest.kt b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/plugins/SSESessionParserTest.kt index 1715926351f..68d906b26c8 100644 Binary files a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/plugins/SSESessionParserTest.kt and b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/plugins/SSESessionParserTest.kt differ diff --git a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/plugins/ServerSentEventsTest.kt b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/plugins/ServerSentEventsTest.kt index 5d3fcfc5229..91e0905f9d9 100644 --- a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/plugins/ServerSentEventsTest.kt +++ b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/plugins/ServerSentEventsTest.kt @@ -15,22 +15,25 @@ import io.ktor.client.statement.* import io.ktor.client.tests.utils.* import io.ktor.http.* import io.ktor.http.content.* +import io.ktor.sse.* import io.ktor.test.dispatcher.* import io.ktor.utils.io.* import io.ktor.utils.io.charsets.* import kotlinx.coroutines.* import kotlinx.coroutines.flow.* +import kotlinx.serialization.* +import kotlinx.serialization.json.* import kotlin.coroutines.* import kotlin.test.* -import kotlin.test.assertFailsWith +import kotlin.time.Duration.Companion.minutes -class ServerSentEventsTest : ClientLoader(timeoutSeconds = 120) { +class ServerSentEventsTest : ClientLoader(2.minutes) { @Test fun testExceptionIfSseIsNotInstalled() = testSuspend { val client = HttpClient() assertFailsWith { - client.serverSentEventsSession() + client.serverSentEventsSession {} }.apply { assertContains(message!!, SSE.key.name) } @@ -430,4 +433,112 @@ class ServerSentEventsTest : ClientLoader(timeoutSeconds = 120) { } } } + + class Person(val name: String) + class Data(val value: String) + + @Test + fun testDeserializer() = clientTests { + config { + install(SSE) + } + + test { client -> + val count = 10 + var size = 0 + client.sse( + { + url("$TEST_SERVER/sse/person") + parameter("times", count) + }, + deserialize = { _, it -> Person(it) } + ) { + incoming.collectIndexed { i, event -> + val person = deserialize(event) + assertEquals("Name $i", person?.name) + assertEquals("$i", event.id) + size++ + } + } + assertEquals(count, size) + } + } + + @Test + fun testExceptionIfWrongDeserializerProvided() = clientTests { + config { + install(SSE) + } + + test { client -> + assertFailsWith { + client.sse({ url("$TEST_SERVER/sse/person") }, { _, it -> Data(it) }) { + incoming.single().apply { + val data = deserialize(data) + assertEquals("Name 0", data?.name) + } + } + } + } + } + + class Person1(val name: String) + class Person2(val middleName: String) + + @Test + fun testDifferentDeserializers() = clientTests { + config { + install(SSE) + } + + test { client -> + client.sse({ url("$TEST_SERVER/sse/person") }, deserialize = { _, str -> Person1(str) }) { + incoming.single().apply { + assertEquals("Name 0", deserialize(data)?.name) + } + } + client.sse({ url("$TEST_SERVER/sse/person") }, deserialize = { _, str -> Person2(str) }) { + incoming.single().apply { + assertEquals("Name 0", deserialize(data)?.middleName) + } + } + } + } + + @Serializable + data class Customer(val id: Int, val firstName: String, val lastName: String) + + @Serializable + data class Product(val name: String, val price: Int) + + @Test + fun testJsonDeserializer() = clientTests { + config { + install(SSE) + } + + test { client -> + client.sse({ + url("$TEST_SERVER/sse/json") + }, deserialize = { typeInfo, jsonString -> + val serializer = Json.serializersModule.serializer(typeInfo.kotlinType!!) + Json.decodeFromString(serializer, jsonString) ?: Exception() + }) { + var firstIsCustomer = true + incoming.collect { event: TypedServerSentEvent -> + if (firstIsCustomer) { + val customer = deserialize(event.data) + assertEquals(1, customer?.id) + assertEquals("Jet", customer?.firstName) + assertEquals("Brains", customer?.lastName) + firstIsCustomer = false + } else { + val product = deserialize(event.data) + assertEquals("Milk", product?.name) + assertEquals(100, product?.price) + } + } + } + } + } } diff --git a/ktor-client/ktor-client-tests/js/src/io/ktor/client/tests/utils/ClientLoaderJs.kt b/ktor-client/ktor-client-tests/js/src/io/ktor/client/tests/utils/ClientLoaderJs.kt deleted file mode 100644 index cc158c7b8c6..00000000000 --- a/ktor-client/ktor-client-tests/js/src/io/ktor/client/tests/utils/ClientLoaderJs.kt +++ /dev/null @@ -1,38 +0,0 @@ -// ktlint-disable filename -/* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. - */ - -package io.ktor.client.tests.utils - -import io.ktor.client.engine.* -import io.ktor.client.engine.js.* -import kotlinx.coroutines.* -import kotlinx.coroutines.test.* - -/** - * Helper interface to test client. - */ -actual abstract class ClientLoader actual constructor(private val timeoutSeconds: Int) { - /** - * Perform test against all clients from dependencies. - */ - @OptIn(DelicateCoroutinesApi::class) - actual fun clientTests( - skipEngines: List, - onlyWithEngine: String?, - retries: Int, - block: suspend TestClientBuilder.() -> Unit - ): TestResult { - val skipEnginesLowerCase = skipEngines.map { it.lowercase() } - if ((onlyWithEngine != null && onlyWithEngine != "js") || skipEnginesLowerCase.contains("js")) { - return runTest { } - } - - return testWithEngine(Js, retries = retries, timeoutMillis = timeoutSeconds * 1000L, block = block) - } - - actual fun dumpCoroutines() { - error("Debug probes unsupported[js]") - } -} diff --git a/ktor-client/ktor-client-tests/jsAndWasmShared/src/io/ktor/client/tests/utils/ClientLoader.jsAndWasmShared.kt b/ktor-client/ktor-client-tests/jsAndWasmShared/src/io/ktor/client/tests/utils/ClientLoader.jsAndWasmShared.kt new file mode 100644 index 00000000000..81f38bb16f9 --- /dev/null +++ b/ktor-client/ktor-client-tests/jsAndWasmShared/src/io/ktor/client/tests/utils/ClientLoader.jsAndWasmShared.kt @@ -0,0 +1,13 @@ +// ktlint-disable filename +/* + * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + +package io.ktor.client.tests.utils + +import io.ktor.client.engine.* +import io.ktor.utils.io.* + +@OptIn(InternalAPI::class) +internal actual val enginesToTest: Iterable> get() = engines +internal actual val platformName: String get() = "web" diff --git a/ktor-client/ktor-client-tests/jvm/src/io/ktor/client/tests/utils/ClientLoader.jvm.kt b/ktor-client/ktor-client-tests/jvm/src/io/ktor/client/tests/utils/ClientLoader.jvm.kt new file mode 100644 index 00000000000..b88241c364f --- /dev/null +++ b/ktor-client/ktor-client-tests/jvm/src/io/ktor/client/tests/utils/ClientLoader.jvm.kt @@ -0,0 +1,72 @@ +/* + * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + +package io.ktor.client.tests.utils + +import io.ktor.client.* +import io.ktor.client.engine.* +import io.ktor.util.reflect.* +import io.ktor.utils.io.* +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.debug.CoroutineInfo +import kotlinx.coroutines.debug.DebugProbes +import java.util.* + +@OptIn(InternalAPI::class) +internal actual val enginesToTest: Iterable> by lazy { + loadServices().map { it.factory } +} + +internal actual val platformName: String by lazy { + val os = System.getProperty("os.name", "unknown").lowercase(Locale.getDefault()) + "jvm/" + when { + os.contains("win") -> "win" + os.contains("mac") -> "mac" + os.contains("nux") -> "unix" + else -> "unknown" + } +} + +@OptIn(ExperimentalCoroutinesApi::class) +internal actual fun platformDumpCoroutines() { + DebugProbes.dumpCoroutines() + + println("Thread Dump") + Thread.getAllStackTraces().forEach { (thread, stackTrace) -> + println("Thread: $thread") + stackTrace.forEach { + println("\t$it") + } + } +} + +@OptIn(ExperimentalCoroutinesApi::class) +internal actual fun platformWaitForAllCoroutines() { + check(DebugProbes.isInstalled) { + "Debug probes isn't installed." + } + + val info = DebugProbes.dumpCoroutinesInfo() + + if (info.isEmpty()) { + return + } + + val message = buildString { + appendLine("Test failed. There are running coroutines") + appendLine(info.dump()) + } + + error(message) +} + +@OptIn(ExperimentalCoroutinesApi::class) +private fun List.dump(): String = buildString { + this@dump.forEach { info -> + appendLine("Coroutine: $info") + info.lastObservedStackTrace().forEach { + appendLine("\t$it") + } + } +} diff --git a/ktor-client/ktor-client-tests/jvm/src/io/ktor/client/tests/utils/ClientLoaderJvm.kt b/ktor-client/ktor-client-tests/jvm/src/io/ktor/client/tests/utils/ClientLoaderJvm.kt deleted file mode 100644 index 53f655685b0..00000000000 --- a/ktor-client/ktor-client-tests/jvm/src/io/ktor/client/tests/utils/ClientLoaderJvm.kt +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. - */ - -package io.ktor.client.tests.utils - -import io.ktor.client.* -import io.ktor.client.engine.* -import io.ktor.util.reflect.* -import io.ktor.utils.io.* -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.debug.CoroutineInfo -import kotlinx.coroutines.debug.DebugProbes -import kotlinx.coroutines.runBlocking -import kotlinx.coroutines.withTimeout -import java.util.* -import kotlin.time.Duration.Companion.seconds - -/** - * Helper interface to test client. - */ -actual abstract class ClientLoader actual constructor(val timeoutSeconds: Int) { - - @OptIn(InternalAPI::class) - private val engines: List by lazy { loadServices() } - - /** - * Perform test against all clients from dependencies. - */ - @OptIn(ExperimentalCoroutinesApi::class) - actual fun clientTests( - skipEngines: List, - onlyWithEngine: String?, - retries: Int, - block: suspend TestClientBuilder.() -> Unit - ) { - DebugProbes.install() - for (engine in engines) { - if (shouldSkip(engine, skipEngines, onlyWithEngine)) { - continue - } - runBlocking { - withTimeout(timeoutSeconds.seconds.inWholeMilliseconds) { - testWithEngine(engine.factory, this@ClientLoader, timeoutSeconds * 1000L, retries, block) - } - } - } - } - - private fun shouldSkip( - engine: HttpClientEngineContainer, - skipEngines: List, - onlyWithEngine: String? - ): Boolean { - val engineName = engine.toString() - return onlyWithEngine != null && !onlyWithEngine.equals(engineName, ignoreCase = true) || - skipEngines.any { shouldSkip(engineName, it) } - } - - private fun shouldSkip(engineName: String, skipEngine: String): Boolean { - val locale = Locale.getDefault() - val skipEngineArray = skipEngine.lowercase(locale).split(":") - - val (platform, skipEngineName) = when (skipEngineArray.size) { - 2 -> skipEngineArray[0] to skipEngineArray[1] - 1 -> "*" to skipEngineArray[0] - else -> throw IllegalStateException("Wrong skip engine format, expected 'engine' or 'platform:engine'") - } - - val platformShouldBeSkipped = "*" == platform || OS_NAME == platform - val engineShouldBeSkipped = "*" == skipEngineName || engineName.lowercase(locale) == skipEngineName.lowercase( - locale - ) - - return engineShouldBeSkipped && platformShouldBeSkipped - } - - @OptIn(ExperimentalCoroutinesApi::class) - actual fun dumpCoroutines() { - DebugProbes.dumpCoroutines() - - println("Thread Dump") - Thread.getAllStackTraces().forEach { (thread, stackTrace) -> - println("Thread: $thread") - stackTrace.forEach { - println("\t$it") - } - } - } - - /** - * Issues to fix before unlock: - * 1. Pinger & Ponger in ws - * 2. Nonce generator - */ - // @After - @OptIn(ExperimentalCoroutinesApi::class) - fun waitForAllCoroutines() { - check(DebugProbes.isInstalled) { - "Debug probes isn't installed." - } - - val info = DebugProbes.dumpCoroutinesInfo() - - if (info.isEmpty()) { - return - } - - val message = buildString { - appendLine("Test failed. There are running coroutines") - appendLine(info.dump()) - } - - error(message) - } -} - -private val OS_NAME: String - get() { - val os = System.getProperty("os.name", "unknown").lowercase(Locale.getDefault()) - return when { - os.contains("win") -> "win" - os.contains("mac") -> "mac" - os.contains("nux") -> "unix" - else -> "unknown" - } - } - -@OptIn(ExperimentalCoroutinesApi::class) -private fun List.dump(): String = buildString { - this@dump.forEach { info -> - appendLine("Coroutine: $info") - info.lastObservedStackTrace().forEach { - appendLine("\t$it") - } - } -} diff --git a/ktor-client/ktor-client-tests/jvm/test/io/ktor/client/tests/LoggingTestJvm.kt b/ktor-client/ktor-client-tests/jvm/test/io/ktor/client/tests/LoggingTestJvm.kt index 8862a94c1b9..6845097a066 100644 --- a/ktor-client/ktor-client-tests/jvm/test/io/ktor/client/tests/LoggingTestJvm.kt +++ b/ktor-client/ktor-client-tests/jvm/test/io/ktor/client/tests/LoggingTestJvm.kt @@ -14,6 +14,7 @@ import kotlinx.coroutines.* import kotlinx.coroutines.slf4j.* import org.slf4j.* import kotlin.test.* +import kotlin.time.Duration.Companion.seconds private class LoggerWithMdc : Logger { val logs = mutableListOf>() @@ -27,7 +28,7 @@ private class LoggerWithMdc : Logger { } } -class LoggingTestJvm : ClientLoader(timeoutSeconds = 1000000) { +class LoggingTestJvm : ClientLoader(1000000.seconds) { @OptIn(InternalAPI::class) @Test diff --git a/ktor-client/ktor-client-tests/jvm/test/io/ktor/client/tests/MultithreadedTest.kt b/ktor-client/ktor-client-tests/jvm/test/io/ktor/client/tests/MultithreadedTest.kt index e6caa8229a0..9f6f199676f 100644 --- a/ktor-client/ktor-client-tests/jvm/test/io/ktor/client/tests/MultithreadedTest.kt +++ b/ktor-client/ktor-client-tests/jvm/test/io/ktor/client/tests/MultithreadedTest.kt @@ -10,11 +10,12 @@ import io.ktor.client.tests.utils.* import kotlinx.coroutines.* import java.util.concurrent.* import kotlin.test.* +import kotlin.time.Duration.Companion.minutes private const val TEST_SIZE = 100_000 private const val DEFAULT_THREADS_COUNT = 32 -class MultithreadedTest : ClientLoader(timeoutSeconds = 10 * 60) { +class MultithreadedTest : ClientLoader(10.minutes) { @Test @Ignore fun numberTest() = clientTests { diff --git a/ktor-client/ktor-client-tests/jvm/test/io/ktor/client/tests/WebSocketJvmTest.kt b/ktor-client/ktor-client-tests/jvm/test/io/ktor/client/tests/WebSocketJvmTest.kt index af98b6a2aff..bb7fa124340 100644 --- a/ktor-client/ktor-client-tests/jvm/test/io/ktor/client/tests/WebSocketJvmTest.kt +++ b/ktor-client/ktor-client-tests/jvm/test/io/ktor/client/tests/WebSocketJvmTest.kt @@ -8,10 +8,11 @@ import io.ktor.client.plugins.websocket.* import io.ktor.client.tests.utils.* import io.ktor.websocket.* import kotlin.test.* +import kotlin.time.Duration.Companion.seconds private const val TEST_SIZE: Int = 100 -class WebSocketJvmTest : ClientLoader(100000) { +class WebSocketJvmTest : ClientLoader(100000.seconds) { @Test fun testWebSocketDeflateBinary() = clientTests(listOf("Android", "Apache", "Apache5")) { diff --git a/ktor-client/ktor-client-tests/nonJvm/src/io/ktor/client/tests/utils/ClientLoader.nonJvm.kt b/ktor-client/ktor-client-tests/nonJvm/src/io/ktor/client/tests/utils/ClientLoader.nonJvm.kt new file mode 100644 index 00000000000..4ea4cbf9b6b --- /dev/null +++ b/ktor-client/ktor-client-tests/nonJvm/src/io/ktor/client/tests/utils/ClientLoader.nonJvm.kt @@ -0,0 +1,9 @@ +/* + * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + +package io.ktor.client.tests.utils + +// supported only on JVM +internal actual fun platformDumpCoroutines() {} +internal actual fun platformWaitForAllCoroutines() {} diff --git a/ktor-client/ktor-client-tests/posix/src/io/ktor/client/tests/utils/ClientLoader.posix.kt b/ktor-client/ktor-client-tests/posix/src/io/ktor/client/tests/utils/ClientLoader.posix.kt new file mode 100644 index 00000000000..ff21e2b486f --- /dev/null +++ b/ktor-client/ktor-client-tests/posix/src/io/ktor/client/tests/utils/ClientLoader.posix.kt @@ -0,0 +1,15 @@ +/* + * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + +package io.ktor.client.tests.utils + +import io.ktor.client.engine.* +import io.ktor.util.* +import io.ktor.utils.io.* +import kotlin.experimental.* +import kotlin.native.runtime.* + +@OptIn(InternalAPI::class) +internal actual val enginesToTest: Iterable> get() = engines +internal actual val platformName: String get() = "native" diff --git a/ktor-client/ktor-client-tests/posix/src/io/ktor/client/tests/utils/ClientLoaderNative.kt b/ktor-client/ktor-client-tests/posix/src/io/ktor/client/tests/utils/ClientLoaderNative.kt deleted file mode 100644 index 153ee6cb6f9..00000000000 --- a/ktor-client/ktor-client-tests/posix/src/io/ktor/client/tests/utils/ClientLoaderNative.kt +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. - */ - -package io.ktor.client.tests.utils - -import io.ktor.client.engine.* -import io.ktor.utils.io.* -import kotlin.experimental.* - -private class TestFailure(val name: String, val cause: Throwable) { - @OptIn(ExperimentalNativeApi::class) - override fun toString(): String = buildString { - appendLine("Test failed with engine: $name") - appendLine(cause) - for (stackline in cause.getStackTrace()) { - appendLine("\t$stackline") - } - } -} - -/** - * Helper interface to test client. - */ -actual abstract class ClientLoader actual constructor(private val timeoutSeconds: Int) { - /** - * Perform test against all clients from dependencies. - */ - @OptIn(InternalAPI::class) - actual fun clientTests( - skipEngines: List, - onlyWithEngine: String?, - retries: Int, - block: suspend TestClientBuilder.() -> Unit - ) { - if (skipEngines.any { it.startsWith("native") }) return - - val skipEnginesLowerCase = skipEngines.map { it.lowercase() }.toSet() - val filteredEngines: List> = engines.filter { - val name = it.toString().lowercase() - !skipEnginesLowerCase.contains(name) && !skipEnginesLowerCase.contains("native:$name") - } - - val failures = mutableListOf() - for (engine in filteredEngines) { - if (onlyWithEngine != null && onlyWithEngine != engine.toString()) continue - - val result = runCatching { - testWithEngine(engine, timeoutMillis = timeoutSeconds.toLong() * 1000L) { - block() - } - } - - if (result.isFailure) { - failures += TestFailure(engine.toString(), result.exceptionOrNull()!!) - } - } - - if (failures.isEmpty()) { - return - } - - error(failures.joinToString("\n")) - } - - actual fun dumpCoroutines() { - error("Debug probes unsupported native.") - } -} diff --git a/ktor-client/ktor-client-tests/wasmJs/src/io/ktor/client/tests/utils/ClientLoaderWasm.kt b/ktor-client/ktor-client-tests/wasmJs/src/io/ktor/client/tests/utils/ClientLoaderWasm.kt deleted file mode 100644 index bac76c033d8..00000000000 --- a/ktor-client/ktor-client-tests/wasmJs/src/io/ktor/client/tests/utils/ClientLoaderWasm.kt +++ /dev/null @@ -1,38 +0,0 @@ -// ktlint-disable filename -/* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. - */ - -package io.ktor.client.tests.utils - -import io.ktor.client.engine.* -import io.ktor.client.engine.js.* -import kotlinx.coroutines.* -import kotlinx.coroutines.test.* - -/** - * Helper interface to test client. - */ -actual abstract class ClientLoader actual constructor(private val timeoutSeconds: Int) { - /** - * Perform test against all clients from dependencies. - */ - @OptIn(DelicateCoroutinesApi::class) - actual fun clientTests( - skipEngines: List, - onlyWithEngine: String?, - retries: Int, - block: suspend TestClientBuilder.() -> Unit - ): TestResult { - val skipEnginesLowerCase = skipEngines.map { it.lowercase() } - return if ((onlyWithEngine != null && onlyWithEngine != "js") || skipEnginesLowerCase.contains("js")) { - runTest {} - } else { - testWithEngine(Js, retries = retries, timeoutMillis = timeoutSeconds * 1000L, block = block) - } - } - - actual fun dumpCoroutines() { - error("Debug probes unsupported[wasm]") - } -} diff --git a/ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpResponseData.kt b/ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpResponseData.kt index 0271f8fb464..93df7931549 100644 --- a/ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpResponseData.kt +++ b/ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpResponseData.kt @@ -1,16 +1,14 @@ /* - * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.engine.winhttp.internal -import io.ktor.client.plugins.sse.* import io.ktor.client.request.* import io.ktor.http.* import io.ktor.http.cio.* import io.ktor.util.date.* import io.ktor.utils.io.* -import io.ktor.utils.io.core.* import kotlin.coroutines.* internal class WinHttpResponseData( diff --git a/ktor-client/ktor-client-winhttp/windows/test/io/ktor/client/engine/winhttp/WinHttpProxyTest.kt b/ktor-client/ktor-client-winhttp/windows/test/io/ktor/client/engine/winhttp/WinHttpProxyTest.kt index bd977ceb70c..a14241ae849 100644 --- a/ktor-client/ktor-client-winhttp/windows/test/io/ktor/client/engine/winhttp/WinHttpProxyTest.kt +++ b/ktor-client/ktor-client-winhttp/windows/test/io/ktor/client/engine/winhttp/WinHttpProxyTest.kt @@ -1,6 +1,6 @@ /* -* Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.client.engine.winhttp @@ -8,7 +8,6 @@ import io.ktor.client.* import io.ktor.client.call.* import io.ktor.client.engine.* import io.ktor.client.request.* -import io.ktor.utils.io.core.* import kotlinx.coroutines.* import kotlin.test.* diff --git a/ktor-http/api/ktor-http.api b/ktor-http/api/ktor-http.api index f369eca9d6a..3f490eb1bf2 100644 --- a/ktor-http/api/ktor-http.api +++ b/ktor-http/api/ktor-http.api @@ -262,7 +262,7 @@ public final class io/ktor/http/ContentTypesKt { public static final fun withCharsetIfNeeded (Lio/ktor/http/ContentType;Ljava/nio/charset/Charset;)Lio/ktor/http/ContentType; } -public final class io/ktor/http/Cookie { +public final class io/ktor/http/Cookie : java/io/Serializable { public static final field Companion Lio/ktor/http/Cookie$Companion; public fun (Ljava/lang/String;Ljava/lang/String;Lio/ktor/http/CookieEncoding;Ljava/lang/Integer;Lio/ktor/util/date/GMTDate;Ljava/lang/String;Ljava/lang/String;ZZLjava/util/Map;)V public synthetic fun (Ljava/lang/String;Ljava/lang/String;Lio/ktor/http/CookieEncoding;Ljava/lang/Integer;Lio/ktor/util/date/GMTDate;Ljava/lang/String;Ljava/lang/String;ZZLjava/util/Map;ILkotlin/jvm/internal/DefaultConstructorMarker;)V @@ -966,7 +966,7 @@ public final class io/ktor/http/URLParserKt { public static final fun takeFrom (Lio/ktor/http/URLBuilder;Ljava/lang/String;)Lio/ktor/http/URLBuilder; } -public final class io/ktor/http/URLProtocol { +public final class io/ktor/http/URLProtocol : java/io/Serializable { public static final field Companion Lio/ktor/http/URLProtocol$Companion; public fun (Ljava/lang/String;I)V public final fun component1 ()Ljava/lang/String; @@ -1026,7 +1026,7 @@ public final class io/ktor/http/UnsafeHeaderException : java/lang/IllegalArgumen public fun (Ljava/lang/String;)V } -public final class io/ktor/http/Url { +public final class io/ktor/http/Url : java/io/Serializable { public static final field Companion Lio/ktor/http/Url$Companion; public fun equals (Ljava/lang/Object;)Z public final fun getEncodedFragment ()Ljava/lang/String; @@ -1053,6 +1053,7 @@ public final class io/ktor/http/Url { } public final class io/ktor/http/Url$Companion { + public final fun serializer ()Lkotlinx/serialization/KSerializer; } public final class io/ktor/http/UrlKt { @@ -1060,6 +1061,15 @@ public final class io/ktor/http/UrlKt { public static final fun getProtocolWithAuthority (Lio/ktor/http/Url;)Ljava/lang/String; } +public final class io/ktor/http/UrlSerializer : kotlinx/serialization/KSerializer { + public static final field INSTANCE Lio/ktor/http/UrlSerializer; + public fun deserialize (Lkotlinx/serialization/encoding/Decoder;)Lio/ktor/http/Url; + public synthetic fun deserialize (Lkotlinx/serialization/encoding/Decoder;)Ljava/lang/Object; + public fun getDescriptor ()Lkotlinx/serialization/descriptors/SerialDescriptor; + public fun serialize (Lkotlinx/serialization/encoding/Encoder;Lio/ktor/http/Url;)V + public synthetic fun serialize (Lkotlinx/serialization/encoding/Encoder;Ljava/lang/Object;)V +} + public final class io/ktor/http/auth/AuthScheme { public static final field Basic Ljava/lang/String; public static final field Bearer Ljava/lang/String; diff --git a/ktor-http/api/ktor-http.klib.api b/ktor-http/api/ktor-http.klib.api index 7bd6b70711b..c4372c4f9a4 100644 --- a/ktor-http/api/ktor-http.klib.api +++ b/ktor-http/api/ktor-http.klib.api @@ -573,7 +573,7 @@ final class io.ktor.http/ContentType : io.ktor.http/HeaderValueWithParameters { } } -final class io.ktor.http/Cookie { // io.ktor.http/Cookie|null[0] +final class io.ktor.http/Cookie : io.ktor.utils.io/JvmSerializable { // io.ktor.http/Cookie|null[0] constructor (kotlin/String, kotlin/String, io.ktor.http/CookieEncoding = ..., kotlin/Int? = ..., io.ktor.util.date/GMTDate? = ..., kotlin/String? = ..., kotlin/String? = ..., kotlin/Boolean = ..., kotlin/Boolean = ..., kotlin.collections/Map = ...) // io.ktor.http/Cookie.|(kotlin.String;kotlin.String;io.ktor.http.CookieEncoding;kotlin.Int?;io.ktor.util.date.GMTDate?;kotlin.String?;kotlin.String?;kotlin.Boolean;kotlin.Boolean;kotlin.collections.Map){}[0] final val domain // io.ktor.http/Cookie.domain|{}domain[0] @@ -1048,7 +1048,7 @@ final class io.ktor.http/URLParserException : kotlin/IllegalStateException { // constructor (kotlin/String, kotlin/Throwable) // io.ktor.http/URLParserException.|(kotlin.String;kotlin.Throwable){}[0] } -final class io.ktor.http/URLProtocol { // io.ktor.http/URLProtocol|null[0] +final class io.ktor.http/URLProtocol : io.ktor.utils.io/JvmSerializable { // io.ktor.http/URLProtocol|null[0] constructor (kotlin/String, kotlin/Int) // io.ktor.http/URLProtocol.|(kotlin.String;kotlin.Int){}[0] final val defaultPort // io.ktor.http/URLProtocol.defaultPort|{}defaultPort[0] @@ -1085,7 +1085,7 @@ final class io.ktor.http/UnsafeHeaderException : kotlin/IllegalArgumentException constructor (kotlin/String) // io.ktor.http/UnsafeHeaderException.|(kotlin.String){}[0] } -final class io.ktor.http/Url { // io.ktor.http/Url|null[0] +final class io.ktor.http/Url : io.ktor.utils.io/JvmSerializable { // io.ktor.http/Url|null[0] final val encodedFragment // io.ktor.http/Url.encodedFragment|{}encodedFragment[0] final fun (): kotlin/String // io.ktor.http/Url.encodedFragment.|(){}[0] final val encodedPassword // io.ktor.http/Url.encodedPassword|{}encodedPassword[0] @@ -1129,7 +1129,9 @@ final class io.ktor.http/Url { // io.ktor.http/Url|null[0] final fun hashCode(): kotlin/Int // io.ktor.http/Url.hashCode|hashCode(){}[0] final fun toString(): kotlin/String // io.ktor.http/Url.toString|toString(){}[0] - final object Companion // io.ktor.http/Url.Companion|null[0] + final object Companion { // io.ktor.http/Url.Companion|null[0] + final fun serializer(): kotlinx.serialization/KSerializer // io.ktor.http/Url.Companion.serializer|serializer(){}[0] + } } sealed class io.ktor.http.auth/HttpAuthHeader { // io.ktor.http.auth/HttpAuthHeader|null[0] @@ -1580,6 +1582,14 @@ final object io.ktor.http/HttpHeaders { // io.ktor.http/HttpHeaders|null[0] final fun isUnsafe(kotlin/String): kotlin/Boolean // io.ktor.http/HttpHeaders.isUnsafe|isUnsafe(kotlin.String){}[0] } +final object io.ktor.http/UrlSerializer : kotlinx.serialization/KSerializer { // io.ktor.http/UrlSerializer|null[0] + final val descriptor // io.ktor.http/UrlSerializer.descriptor|{}descriptor[0] + final fun (): kotlinx.serialization.descriptors/SerialDescriptor // io.ktor.http/UrlSerializer.descriptor.|(){}[0] + + final fun deserialize(kotlinx.serialization.encoding/Decoder): io.ktor.http/Url // io.ktor.http/UrlSerializer.deserialize|deserialize(kotlinx.serialization.encoding.Decoder){}[0] + final fun serialize(kotlinx.serialization.encoding/Encoder, io.ktor.http/Url) // io.ktor.http/UrlSerializer.serialize|serialize(kotlinx.serialization.encoding.Encoder;io.ktor.http.Url){}[0] +} + final const val io.ktor.http/DEFAULT_PORT // io.ktor.http/DEFAULT_PORT|{}DEFAULT_PORT[0] final fun (): kotlin/Int // io.ktor.http/DEFAULT_PORT.|(){}[0] diff --git a/ktor-http/build.gradle.kts b/ktor-http/build.gradle.kts index 0ec58b576f7..bb98a0ec6c1 100644 --- a/ktor-http/build.gradle.kts +++ b/ktor-http/build.gradle.kts @@ -14,5 +14,12 @@ kotlin { api(libs.kotlinx.serialization.core) } } + jvmTest { + dependencies { + implementation(project(":ktor-shared:ktor-junit")) + implementation(project(":ktor-shared:ktor-serialization:ktor-serialization-kotlinx")) + implementation(project(":ktor-shared:ktor-serialization:ktor-serialization-kotlinx:ktor-serialization-kotlinx-json")) + } + } } } diff --git a/ktor-http/common/src/io/ktor/http/ContentTypes.kt b/ktor-http/common/src/io/ktor/http/ContentTypes.kt index c2444bc5c74..117c423d90e 100644 --- a/ktor-http/common/src/io/ktor/http/ContentTypes.kt +++ b/ktor-http/common/src/io/ktor/http/ContentTypes.kt @@ -54,6 +54,14 @@ public class ContentType private constructor( /** * Checks if `this` type matches a [pattern] type taking into account placeholder symbols `*` and parameters. + * The `this` type must be a more specific type than the [pattern] type. In other words: + * + * ```kotlin + * ContentType("a", "b").match(ContentType("a", "b").withParameter("foo", "bar")) === false + * ContentType("a", "b").withParameter("foo", "bar").match(ContentType("a", "b")) === true + * ContentType("a", "*").match(ContentType("a", "b")) === false + * ContentType("a", "b").match(ContentType("a", "*")) === true + * ``` */ public fun match(pattern: ContentType): Boolean { if (pattern.contentType != "*" && !pattern.contentType.equals(contentType, ignoreCase = true)) { diff --git a/ktor-http/common/src/io/ktor/http/Cookie.kt b/ktor-http/common/src/io/ktor/http/Cookie.kt index 83b16e6d562..6872c1d466a 100644 --- a/ktor-http/common/src/io/ktor/http/Cookie.kt +++ b/ktor-http/common/src/io/ktor/http/Cookie.kt @@ -2,10 +2,13 @@ * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ +@file:OptIn(InternalAPI::class) + package io.ktor.http import io.ktor.util.* import io.ktor.util.date.* +import io.ktor.utils.io.* import kotlinx.serialization.* import kotlin.jvm.* @@ -37,7 +40,17 @@ public data class Cookie( val secure: Boolean = false, val httpOnly: Boolean = false, val extensions: Map = emptyMap() -) +) : JvmSerializable { + private fun writeReplace(): Any = JvmSerializerReplacement(CookieJvmSerializer, this) +} + +internal object CookieJvmSerializer : JvmSerializer { + override fun jvmSerialize(value: Cookie): ByteArray = + renderSetCookieHeader(value).encodeToByteArray() + + override fun jvmDeserialize(value: ByteArray): Cookie = + parseServerSetCookieHeader(value.decodeToString()) +} /** * Cooke encoding strategy diff --git a/ktor-http/common/src/io/ktor/http/Mimes.kt b/ktor-http/common/src/io/ktor/http/Mimes.kt index c1da7de818e..4e9d52f09b7 100644 --- a/ktor-http/common/src/io/ktor/http/Mimes.kt +++ b/ktor-http/common/src/io/ktor/http/Mimes.kt @@ -1,1238 +1,1014 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.http import io.ktor.util.* +internal const val INITIAL_MIMES_LIST_SIZE: Int = 1212 + private val rawMimes: String get() = """ -.123,application/vnd.lotus-1-2-3 -.3dmf,x-world/x-3dmf -.3dml,text/vnd.in3d.3dml -.3dm,x-world/x-3dmf -.3g2,video/3gpp2 -.3gp,video/3gpp -.7z,application/x-7z-compressed -.aab,application/x-authorware-bin -.aac,audio/aac -.aam,application/x-authorware-map -.a,application/octet-stream -.aas,application/x-authorware-seg -.abc,text/vnd.abc -.abw,application/x-abiword -.ac,application/pkix-attr-cert -.acc,application/vnd.americandynamics.acc -.ace,application/x-ace-compressed -.acgi,text/html -.acu,application/vnd.acucobol -.adp,audio/adpcm -.aep,application/vnd.audiograph -.afl,video/animaflex -.afp,application/vnd.ibm.modcap -.ahead,application/vnd.ahead.space -.ai,application/postscript -.aif,audio/aiff -.aifc,audio/aiff -.aiff,audio/aiff -.aim,application/x-aim -.aip,text/x-audiosoft-intra -.air,application/vnd.adobe.air-application-installer-package+zip -.ait,application/vnd.dvb.ait -.ami,application/vnd.amiga.ami -.ani,application/x-navi-animation -.aos,application/x-nokia-9000-communicator-add-on-software -.apk,application/vnd.android.package-archive -.application,application/x-ms-application -,application/pgp-encrypted -.apr,application/vnd.lotus-approach -.aps,application/mime -.arc,application/octet-stream -.arj,application/arj -.arj,application/octet-stream -.art,image/x-jg -.asf,video/x-ms-asf -.asm,text/x-asm -.aso,application/vnd.accpac.simply.aso -.asp,text/asp -.asx,application/x-mplayer2 -.asx,video/x-ms-asf -.asx,video/x-ms-asf-plugin -.atc,application/vnd.acucorp -.atomcat,application/atomcat+xml -.atomsvc,application/atomsvc+xml -.atom,application/atom+xml -.atx,application/vnd.antix.game-component -.au,audio/basic -.au,audio/x-au -.avi,video/avi -.avi,video/msvideo -.avi,video/x-msvideo -.avif,image/avif -.avifs,image/avif -.avs,video/avs-video -.aw,application/applixware -.azf,application/vnd.airzip.filesecure.azf -.azs,application/vnd.airzip.filesecure.azs -.azw,application/vnd.amazon.ebook -.bcpio,application/x-bcpio -.bdf,application/x-font-bdf -.bdm,application/vnd.syncml.dm+wbxml -.bed,application/vnd.realvnc.bed -.bh2,application/vnd.fujitsu.oasysprs -.bin,application/macbinary -.bin,application/mac-binary -.bin,application/octet-stream -.bin,application/x-binary -.bin,application/x-macbinary -.bmi,application/vnd.bmi -.bm,image/bmp -.bmp,image/bmp -.bmp,image/x-windows-bmp -.boo,application/book -.book,application/book -.box,application/vnd.previewsystems.box -.boz,application/x-bzip2 -.bsh,application/x-bsh -.btif,image/prs.btif -.bz2,application/x-bzip2 -.bz,application/x-bzip -.c11amc,application/vnd.cluetrust.cartomobile-config -.c11amz,application/vnd.cluetrust.cartomobile-config-pkg -.c4g,application/vnd.clonk.c4group -.cab,application/vnd.ms-cab-compressed -.car,application/vnd.curl.car -.cat,application/vnd.ms-pki.seccat -.ccad,application/clariscad -.cco,application/x-cocoa -.cc,text/plain -.cc,text/x-c -.ccxml,application/ccxml+xml, -.cdbcmsg,application/vnd.contact.cmsg -.cdf,application/cdf -.cdf,application/x-cdf -.cdf,application/x-netcdf -.cdkey,application/vnd.mediastation.cdkey -.cdmia,application/cdmi-capability -.cdmic,application/cdmi-container -.cdmid,application/cdmi-domain -.cdmio,application/cdmi-object -.cdmiq,application/cdmi-queue -.cdx,chemical/x-cdx -.cdxml,application/vnd.chemdraw+xml -.cdy,application/vnd.cinderella -.cer,application/pkix-cert -.cgm,image/cgm -.cha,application/x-chat -.chat,application/x-chat -.chm,application/vnd.ms-htmlhelp -.chrt,application/vnd.kde.kchart -.cif,chemical/x-cif -.cii,application/vnd.anser-web-certificate-issue-initiation -.cil,application/vnd.ms-artgalry -.cla,application/vnd.claymore -.class,application/java -.class,application/java-byte-code -.class,application/java-vm -.class,application/x-java-class -.clkk,application/vnd.crick.clicker.keyboard -.clkp,application/vnd.crick.clicker.palette -.clkt,application/vnd.crick.clicker.template -.clkw,application/vnd.crick.clicker.wordbank -.clkx,application/vnd.crick.clicker -.clp,application/x-msclip -.cmc,application/vnd.cosmocaller -.cmdf,chemical/x-cmdf -.cml,chemical/x-cml -.cmp,application/vnd.yellowriver-custom-menu -.cmx,image/x-cmx -.cod,application/vnd.rim.cod -.collection,font/collection -.com,application/octet-stream -.com,text/plain -.conf,text/plain -.cpio,application/x-cpio -.cpp,text/x-c -.cpt,application/mac-compactpro -.cpt,application/x-compactpro -.cpt,application/x-cpt -.crd,application/x-mscardfile -.crl,application/pkcs-crl -.crl,application/pkix-crl -.crt,application/pkix-cert -.crt,application/x-x509-ca-cert -.crt,application/x-x509-user-cert -.cryptonote,application/vnd.rig.cryptonote -.csh,application/x-csh -.csh,text/x-script.csh -.csml,chemical/x-csml -.csp,application/vnd.commonspace -.css,text/css -.csv,text/csv -.c,text/plain -.c++,text/plain -.c,text/x-c -.cu,application/cu-seeme -.curl,text/vnd.curl -.cww,application/prs.cww -.cxx,text/plain -.dat,binary/octet-stream -.dae,model/vnd.collada+xml -.daf,application/vnd.mobius.daf -.davmount,application/davmount+xml -.dcr,application/x-director -.dcurl,text/vnd.curl.dcurl -.dd2,application/vnd.oma.dd2+xml -.ddd,application/vnd.fujixerox.ddd -.deb,application/x-debian-package -.deepv,application/x-deepv -.def,text/plain -.der,application/x-x509-ca-cert -.dfac,application/vnd.dreamfactory -.dif,video/x-dv -.dir,application/x-director -.dis,application/vnd.mobius.dis -.djvu,image/vnd.djvu -.dl,video/dl -.dl,video/x-dl -.dna,application/vnd.dna -.doc,application/msword -.docm,application/vnd.ms-word.document.macroenabled.12 -.docx,application/vnd.openxmlformats-officedocument.wordprocessingml.document -.dot,application/msword -.dotm,application/vnd.ms-word.template.macroenabled.12 -.dotx,application/vnd.openxmlformats-officedocument.wordprocessingml.template -.dp,application/commonground -.dp,application/vnd.osgi.dp -.dpg,application/vnd.dpgraph -.dra,audio/vnd.dra -.drw,application/drafting -.dsc,text/prs.lines.tag -.dssc,application/dssc+der -.dtb,application/x-dtbook+xml -.dtd,application/xml-dtd -.dts,audio/vnd.dts -.dtshd,audio/vnd.dts.hd -.dump,application/octet-stream -.dvi,application/x-dvi -.dv,video/x-dv -.dwf,model/vnd.dwf -.dwg,application/acad -.dwg,image/vnd.dwg -.dwg,image/x-dwg -.dxf,application/dxf -.dxf,image/vnd.dwg -.dxf,image/vnd.dxf -.dxf,image/x-dwg -.dxp,application/vnd.spotfire.dxp -.dxr,application/x-director -.ecelp4800,audio/vnd.nuera.ecelp4800 -.ecelp7470,audio/vnd.nuera.ecelp7470 -.ecelp9600,audio/vnd.nuera.ecelp9600 -.edm,application/vnd.novadigm.edm -.edx,application/vnd.novadigm.edx -.efif,application/vnd.picsel -.ei6,application/vnd.pg.osasli -.elc,application/x-elc -.el,text/x-script.elisp -.eml,message/rfc822 -.emma,application/emma+xml -.env,application/x-envoy -.eol,audio/vnd.digital-winds -.eot,application/vnd.ms-fontobject -.eps,application/postscript -.epub,application/epub+zip -.es3,application/vnd.eszigno3+xml -.es,application/ecmascript -.es,application/x-esrehber -.esf,application/vnd.epson.esf -.etx,text/x-setext -.evy,application/envoy -.evy,application/x-envoy -.exe,application/octet-stream -.exe,application/x-msdownload -.exi,application/exi -.ext,application/vnd.novadigm.ext -.ez2,application/vnd.ezpix-album -.ez3,application/vnd.ezpix-package -.f4v,video/x-f4v -.f77,text/x-fortran -.f90,text/plain -.f90,text/x-fortran -.fbs,image/vnd.fastbidsheet -.fcs,application/vnd.isac.fcs -.fdf,application/vnd.fdf -.fe_launch,application/vnd.denovo.fcselayout-link -.fg5,application/vnd.fujitsu.oasysgp -.fh,image/x-freehand -.fif,application/fractals -.fif,image/fif -.fig,application/x-xfig -.fli,video/fli -.fli,video/x-fli -.flo,application/vnd.micrografx.flo -.flo,image/florian -.flv,video/x-flv -.flw,application/vnd.kde.kivio -.flx,text/vnd.fmi.flexstor -.fly,text/vnd.fly -.fm,application/vnd.framemaker -.fmf,video/x-atomic3d-feature -.fnc,application/vnd.frogans.fnc -.for,text/plain -.for,text/x-fortran -.fpx,image/vnd.fpx -.fpx,image/vnd.net-fpx -.frl,application/freeloader -.fsc,application/vnd.fsc.weblaunch -.fst,image/vnd.fst -.ftc,application/vnd.fluxtime.clip -.f,text/plain -.f,text/x-fortran -.fti,application/vnd.anser-web-funds-transfer-initiation -.funk,audio/make -.fvt,video/vnd.fvt -.fxp,application/vnd.adobe.fxp -.fzs,application/vnd.fuzzysheet -.g2w,application/vnd.geoplan -.g3,image/g3fax -.g3w,application/vnd.geospace -.gac,application/vnd.groove-account -.gdl,model/vnd.gdl -.geo,application/vnd.dynageo -.gex,application/vnd.geometry-explorer -.ggb,application/vnd.geogebra.file -.ggt,application/vnd.geogebra.tool -.ghf,application/vnd.groove-help -.gif,image/gif -.gim,application/vnd.groove-identity-message -.gl,video/gl -.gl,video/x-gl -.gmx,application/vnd.gmx -.gnumeric,application/x-gnumeric -.gph,application/vnd.flographit -.gqf,application/vnd.grafeq -.gram,application/srgs -.grv,application/vnd.groove-injector -.grxml,application/srgs+xml -.gsd,audio/x-gsm -.gsf,application/x-font-ghostscript -.gsm,audio/x-gsm -.gsp,application/x-gsp -.gss,application/x-gss -.gtar,application/x-gtar -.g,text/plain -.gtm,application/vnd.groove-tool-message -.gtw,model/vnd.gtw -.gv,text/vnd.graphviz -.gxt,application/vnd.geonext -.gz,application/gzip -.gz,application/x-compressed -.gz,application/x-gzip -.gzip,application/gzip -.gzip,application/x-gzip -.gzip,multipart/x-gzip -.h261,video/h261 -.h263,video/h263 -.h264,video/h264 -.hal,application/vnd.hal+xml -.hbci,application/vnd.hbci -.hdf,application/x-hdf -.help,application/x-helpfile -.heic,image/heic -.heif,image/heif -.hgl,application/vnd.hp-hpgl -.hh,text/plain -.hh,text/x-h -.hlb,text/x-script -.hlp,application/hlp -.hlp,application/winhlp -.hlp,application/x-helpfile -.hlp,application/x-winhelp -.hpg,application/vnd.hp-hpgl -.hpgl,application/vnd.hp-hpgl -.hpid,application/vnd.hp-hpid -.hps,application/vnd.hp-hps -.hqx,application/binhex -.hqx,application/binhex4 -.hqx,application/mac-binhex -.hqx,application/mac-binhex40 -.hqx,application/x-binhex40 -.hqx,application/x-mac-binhex40 -.hta,application/hta -.htc,text/x-component -.h,text/plain -.h,text/x-h -.htke,application/vnd.kenameaapp -.htmls,text/html -.html,text/html -.htm,text/html -.htt,text/webviewhtml -.htx,text/html -.hvd,application/vnd.yamaha.hv-dic -.hvp,application/vnd.yamaha.hv-voice -.hvs,application/vnd.yamaha.hv-script -.i2g,application/vnd.intergeo -.icc,application/vnd.iccprofile -.ice,x-conference/x-cooltalk -.ico,image/x-icon -.ics,text/calendar -.idc,text/plain -.ief,image/ief -.iefs,image/ief -.iff,application/iff -.ifm,application/vnd.shana.informed.formdata -.iges,application/iges -.iges,model/iges -.igl,application/vnd.igloader -.igm,application/vnd.insors.igm -.igs,application/iges -.igs,model/iges -.igx,application/vnd.micrografx.igx -.iif,application/vnd.shana.informed.interchange -.ima,application/x-ima -.imap,application/x-httpd-imap -.imp,application/vnd.accpac.simply.imp -.ims,application/vnd.ms-ims -.inf,application/inf -.ins,application/x-internett-signup -.ip,application/x-ip2 -.ipfix,application/ipfix -.ipk,application/vnd.shana.informed.package -.irm,application/vnd.ibm.rights-management -.irp,application/vnd.irepository.package+xml -.isu,video/x-isvideo -.it,audio/it -.itp,application/vnd.shana.informed.formtemplate -.iv,application/x-inventor -.ivp,application/vnd.immervision-ivp -.ivr,i-world/i-vrml -.ivu,application/vnd.immervision-ivu -.ivy,application/x-livescreen -.jad,text/vnd.sun.j2me.app-descriptor -.jam,application/vnd.jam -.jam,audio/x-jam -.jar,application/java-archive -.java,text/plain -.java,text/x-java-source -.jav,text/plain -.jav,text/x-java-source -.jcm,application/x-java-commerce -.jfif,image/jpeg -.jfif,image/pjpeg -.jfif-tbnl,image/jpeg -.jisp,application/vnd.jisp -.jlt,application/vnd.hp-jlyt -.jnlp,application/x-java-jnlp-file -.joda,application/vnd.joost.joda-archive -.jpeg,image/jpeg -.jpe,image/jpeg -.jpg,image/jpeg -.jpgv,video/jpeg -.jpm,video/jpm -.jps,image/x-jps -.js,text/javascript -.js,application/javascript -.json,application/json -.jut,image/jutvision -.kar,audio/midi -.karbon,application/vnd.kde.karbon -.kar,music/x-karaoke -.key,application/pgp-keys -.keychain,application/octet-stream -.kfo,application/vnd.kde.kformula -.kia,application/vnd.kidspiration -.kml,application/vnd.google-earth.kml+xml -.kmz,application/vnd.google-earth.kmz -.kne,application/vnd.kinar -.kon,application/vnd.kde.kontour -.kpr,application/vnd.kde.kpresenter -.ksh,application/x-ksh -.ksh,text/x-script.ksh -.ksp,application/vnd.kde.kspread -.ktx,image/ktx -.ktz,application/vnd.kahootz -.kwd,application/vnd.kde.kword -.la,audio/nspaudio -.la,audio/x-nspaudio -.lam,audio/x-liveaudio -.lasxml,application/vnd.las.las+xml -.latex,application/x-latex -.lbd,application/vnd.llamagraphics.life-balance.desktop -.lbe,application/vnd.llamagraphics.life-balance.exchange+xml -.les,application/vnd.hhe.lesson-player -.lha,application/lha -.lha,application/x-lha -.link66,application/vnd.route66.link66+xml -.list,text/plain -.lma,audio/nspaudio -.lma,audio/x-nspaudio -.log,text/plain -.lrm,application/vnd.ms-lrm -.lsp,application/x-lisp -.lsp,text/x-script.lisp -.lst,text/plain -.lsx,text/x-la-asf -.ltf,application/vnd.frogans.ltf -.ltx,application/x-latex -.lvp,audio/vnd.lucent.voice -.lwp,application/vnd.lotus-wordpro -.lzh,application/octet-stream -.lzh,application/x-lzh -.lzx,application/lzx -.lzx,application/octet-stream -.lzx,application/x-lzx -.m1v,video/mpeg -.m21,application/mp21 -.m2a,audio/mpeg -.m2v,video/mpeg -.m3u8,application/vnd.apple.mpegurl -.m3u,audio/x-mpegurl -.m4a,audio/mp4 -.m4v,video/mp4 -.ma,application/mathematica -.mads,application/mads+xml -.mag,application/vnd.ecowin.chart -.man,application/x-troff-man -.map,application/x-navimap -.mar,text/plain -.mathml,application/mathml+xml -.mbd,application/mbedlet -.mbk,application/vnd.mobius.mbk -.mbox,application/mbox -.mc1,application/vnd.medcalcdata -.mc${'$'},application/x-magic-cap-package-1.0 -.mcd,application/mcad -.mcd,application/vnd.mcd -.mcd,application/x-mathcad -.mcf,image/vasa -.mcf,text/mcf -.mcp,application/netmc -.mcurl,text/vnd.curl.mcurl -.mdb,application/x-msaccess -.mdi,image/vnd.ms-modi -.me,application/x-troff-me -.meta4,application/metalink4+xml -.mets,application/mets+xml -.mfm,application/vnd.mfmp -.mgp,application/vnd.osgeo.mapguide.package -.mgz,application/vnd.proteus.magazine -.mht,message/rfc822 -.mhtml,message/rfc822 -.mid,application/x-midi -.mid,audio/midi -.mid,audio/x-mid -.midi,application/x-midi -.midi,audio/midi -.midi,audio/x-mid -.midi,audio/x-midi -.midi,music/crescendo -.midi,x-music/x-midi -.mid,music/crescendo -.mid,x-music/x-midi -.mif,application/vnd.mif -.mif,application/x-frame -.mif,application/x-mif -.mime,message/rfc822 -.mime,www/mime -.mj2,video/mj2 -.mjf,audio/x-vnd.audioexplosion.mjuicemediafile -.mjpg,video/x-motion-jpeg -.mjs,text/javascript -.mkv,video/x-matroska -.mkv,audio/x-matroska -.mlp,application/vnd.dolby.mlp -.mm,application/base64 -.mm,application/x-meme -.mmd,application/vnd.chipnuts.karaoke-mmd -.mme,application/base64 -.mmf,application/vnd.smaf -.mmr,image/vnd.fujixerox.edmics-mmr -.mny,application/x-msmoney -.mod,audio/mod -.mod,audio/x-mod -.mods,application/mods+xml -.moov,video/quicktime -.movie,video/x-sgi-movie -.mov,video/quicktime -.mp2,audio/mpeg -.mp2,audio/x-mpeg -.mp2,video/mpeg -.mp2,video/x-mpeg -.mp2,video/x-mpeq2a -.mp3,audio/mpeg -.mp3,audio/mpeg3 -.mp4a,audio/mp4 -.mp4,video/mp4 -.mp4,application/mp4 -.mpa,audio/mpeg -.mpc,application/vnd.mophun.certificate -.mpc,application/x-project -.mpeg,video/mpeg -.mpe,video/mpeg -.mpga,audio/mpeg -.mpg,video/mpeg -.mpg,audio/mpeg -.mpkg,application/vnd.apple.installer+xml -.mpm,application/vnd.blueice.multipass -.mpn,application/vnd.mophun.application -.mpp,application/vnd.ms-project -.mpt,application/x-project -.mpv,application/x-project -.mpx,application/x-project -.mpy,application/vnd.ibm.minipay -.mqy,application/vnd.mobius.mqy -.mrc,application/marc -.mrcx,application/marcxml+xml -.ms,application/x-troff-ms -.mscml,application/mediaservercontrol+xml -.mseq,application/vnd.mseq -.msf,application/vnd.epson.msf -.msg,application/vnd.ms-outlook -.msh,model/mesh -.msl,application/vnd.mobius.msl -.msty,application/vnd.muvee.style -.m,text/plain -.m,text/x-m -.mts,model/vnd.mts -.mus,application/vnd.musician -.musicxml,application/vnd.recordare.musicxml+xml -.mvb,application/x-msmediaview -.mv,video/x-sgi-movie -.mwf,application/vnd.mfer -.mxf,application/mxf -.mxl,application/vnd.recordare.musicxml -.mxml,application/xv+xml -.mxs,application/vnd.triscape.mxs -.mxu,video/vnd.mpegurl -.my,audio/make -.mzz,application/x-vnd.audioexplosion.mzz -.n3,text/n3 -N/A,application/andrew-inset -.nap,image/naplps -.naplps,image/naplps -.nbp,application/vnd.wolfram.player -.nc,application/x-netcdf -.ncm,application/vnd.nokia.configuration-message -.ncx,application/x-dtbncx+xml -.n-gage,application/vnd.nokia.n-gage.symbian.install -.ngdat,application/vnd.nokia.n-gage.data -.niff,image/x-niff -.nif,image/x-niff -.nix,application/x-mix-transfer -.nlu,application/vnd.neurolanguage.nlu -.nml,application/vnd.enliven -.nnd,application/vnd.noblenet-directory -.nns,application/vnd.noblenet-sealer -.nnw,application/vnd.noblenet-web -.npx,image/vnd.net-fpx -.nsc,application/x-conference -.nsf,application/vnd.lotus-notes -.nvd,application/x-navidoc -.oa2,application/vnd.fujitsu.oasys2 -.oa3,application/vnd.fujitsu.oasys3 -.o,application/octet-stream -.oas,application/vnd.fujitsu.oasys -.obd,application/x-msbinder -.oda,application/oda -.odb,application/vnd.oasis.opendocument.database -.odc,application/vnd.oasis.opendocument.chart -.odf,application/vnd.oasis.opendocument.formula -.odft,application/vnd.oasis.opendocument.formula-template -.odg,application/vnd.oasis.opendocument.graphics -.odi,application/vnd.oasis.opendocument.image -.odm,application/vnd.oasis.opendocument.text-master -.odp,application/vnd.oasis.opendocument.presentation -.ods,application/vnd.oasis.opendocument.spreadsheet -.odt,application/vnd.oasis.opendocument.text -.oga,audio/ogg -.ogg,audio/ogg -.ogv,video/ogg -.ogx,application/ogg -.omc,application/x-omc -.omcd,application/x-omcdatamaker -.omcr,application/x-omcregerator -.onetoc,application/onenote -.opf,application/oebps-package+xml -.org,application/vnd.lotus-organizer -.osf,application/vnd.yamaha.openscoreformat -.osfpvg,application/vnd.yamaha.openscoreformat.osfpvg+xml -.otc,application/vnd.oasis.opendocument.chart-template -.otf,font/otf -.otg,application/vnd.oasis.opendocument.graphics-template -.oth,application/vnd.oasis.opendocument.text-web -.oti,application/vnd.oasis.opendocument.image-template -.otp,application/vnd.oasis.opendocument.presentation-template -.ots,application/vnd.oasis.opendocument.spreadsheet-template -.ott,application/vnd.oasis.opendocument.text-template -.oxt,application/vnd.openofficeorg.extension -.p10,application/pkcs10 -.p12,application/pkcs-12 -.p7a,application/x-pkcs7-signature -.p7b,application/x-pkcs7-certificates -.p7c,application/pkcs7-mime -.p7m,application/pkcs7-mime -.p7r,application/x-pkcs7-certreqresp -.p7s,application/pkcs7-signature -.p8,application/pkcs8 -.pages,application/vnd.apple.pages -.part,application/pro_eng -.par,text/plain-bas -.pas,text/pascal -.paw,application/vnd.pawaafile -.pbd,application/vnd.powerbuilder6 -.pbm,image/x-portable-bitmap -.pcf,application/x-font-pcf -.pcl,application/vnd.hp-pcl -.pcl,application/x-pcl -.pclxl,application/vnd.hp-pclxl -.pct,image/x-pict -.pcurl,application/vnd.curl.pcurl -.pcx,image/x-pcx -.pdb,application/vnd.palm -.pdb,chemical/x-pdb -.pdf,application/pdf -.pem,application/x-pem-file -.pfa,application/x-font-type1 -.pfr,application/font-tdpfr -.pfunk,audio/make -.pfunk,audio/make.my.funk -.pfx,application/x-pkcs12 -.pgm,image/x-portable-graymap -.pgn,application/x-chess-pgn -.pgp,application/pgp-signature -.pic,image/pict -.pict,image/pict -.pkg,application/x-newton-compatible-pkg -.pki,application/pkixcmp -.pkipath,application/pkix-pkipath -.pko,application/vnd.ms-pki.pko -.plb,application/vnd.3gpp.pic-bw-large -.plc,application/vnd.mobius.plc -.plf,application/vnd.pocketlearn -.pls,application/pls+xml -.pl,text/plain -.pl,text/x-script.perl -.plx,application/x-pixclscript -.pm4,application/x-pagemaker -.pm5,application/x-pagemaker -.pm,image/x-xpixmap -.pml,application/vnd.ctc-posml -.pm,text/x-script.perl-module -.png,image/png -.pnm,application/x-portable-anymap -.pnm,image/x-portable-anymap -.portpkg,application/vnd.macports.portpkg -.pot,application/mspowerpoint -.pot,application/vnd.ms-powerpoint -.potm,application/vnd.ms-powerpoint.template.macroenabled.12 -.potx,application/vnd.openxmlformats-officedocument.presentationml.template -.pov,model/x-pov -.ppa,application/vnd.ms-powerpoint -.ppam,application/vnd.ms-powerpoint.addin.macroenabled.12 -.ppd,application/vnd.cups-ppd -.ppm,image/x-portable-pixmap -.pps,application/mspowerpoint -.pps,application/vnd.ms-powerpoint -.ppsm,application/vnd.ms-powerpoint.slideshow.macroenabled.12 -.ppsx,application/vnd.openxmlformats-officedocument.presentationml.slideshow -.ppt,application/mspowerpoint -.ppt,application/powerpoint -.ppt,application/vnd.ms-powerpoint -.ppt,application/x-mspowerpoint -.pptm,application/vnd.ms-powerpoint.presentation.macroenabled.12 -.pptx,application/vnd.openxmlformats-officedocument.presentationml.presentation -.ppz,application/mspowerpoint -.prc,application/x-mobipocket-ebook -.pre,application/vnd.lotus-freelance -.pre,application/x-freelance -.prf,application/pics-rules -.prt,application/pro_eng -.ps,application/postscript -.psb,application/vnd.3gpp.pic-bw-small -.psd,application/octet-stream -.psd,image/vnd.adobe.photoshop -.psf,application/x-font-linux-psf -.pskcxml,application/pskc+xml -.p,text/x-pascal -.ptid,application/vnd.pvi.ptid1 -.pub,application/x-mspublisher -.pvb,application/vnd.3gpp.pic-bw-var -.pvu,paleovu/x-pv -.pwn,application/vnd.3m.post-it-notes -.pwz,application/vnd.ms-powerpoint -.pya,audio/vnd.ms-playready.media.pya -.pyc,application/x-bytecode.python -.py,text/x-script.python -.pyv,video/vnd.ms-playready.media.pyv -.qam,application/vnd.epson.quickanime -.qbo,application/vnd.intu.qbo -.qcp,audio/vnd.qcelp -.qd3d,x-world/x-3dmf -.qd3,x-world/x-3dmf -.qfx,application/vnd.intu.qfx -.qif,image/x-quicktime -.qps,application/vnd.publishare-delta-tree -.qtc,video/x-qtc -.qtif,image/x-quicktime -.qti,image/x-quicktime -.qt,video/quicktime -.qxd,application/vnd.quark.quarkxpress -.ra,audio/x-pn-realaudio -.ra,audio/x-pn-realaudio-plugin -.ra,audio/x-realaudio -.ram,audio/x-pn-realaudio -.rar,application/x-rar-compressed -.ras,application/x-cmu-raster -.ras,image/cmu-raster -.ras,image/x-cmu-raster -.rast,image/cmu-raster -.rcprofile,application/vnd.ipunplugged.rcprofile -.rdf,application/rdf+xml -.rdz,application/vnd.data-vision.rdz -.rep,application/vnd.businessobjects -.res,application/x-dtbresource+xml -.rexx,text/x-script.rexx -.rf,image/vnd.rn-realflash -.rgb,image/x-rgb -.rif,application/reginfo+xml -.rip,audio/vnd.rip -.rl,application/resource-lists+xml -.rlc,image/vnd.fujixerox.edmics-rlc -.rld,application/resource-lists-diff+xml -.rm,application/vnd.rn-realmedia -.rm,audio/x-pn-realaudio -.rmi,audio/mid -.rmm,audio/x-pn-realaudio -.rmp,audio/x-pn-realaudio -.rmp,audio/x-pn-realaudio-plugin -.rms,application/vnd.jcp.javame.midlet-rms -.rnc,application/relax-ng-compact-syntax -.rng,application/ringing-tones -.rng,application/vnd.nokia.ringing-tone -.rnx,application/vnd.rn-realplayer -.roff,application/x-troff -.rp9,application/vnd.cloanto.rp9 -.rp,image/vnd.rn-realpix -.rpm,audio/x-pn-realaudio-plugin -.rpm,application/x-rpm -.rpss,application/vnd.nokia.radio-presets -.rpst,application/vnd.nokia.radio-preset -.rq,application/sparql-query -.rs,application/rls-services+xml -.rsd,application/rsd+xml -.rss,application/rss+xml -.rtf,application/rtf -.rtf,text/rtf -.rt,text/richtext -.rt,text/vnd.rn-realtext -.rtx,application/rtf -.rtx,text/richtext -.rv,video/vnd.rn-realvideo -.s3m,audio/s3m -.saf,application/vnd.yamaha.smaf-audio -.saveme,application/octet-stream -.sbk,application/x-tbook -.sbml,application/sbml+xml -.sc,application/vnd.ibm.secure-container -.scd,application/x-msschedule -.scm,application/vnd.lotus-screencam -.scm,application/x-lotusscreencam -.scm,text/x-script.guile -.scm,text/x-script.scheme -.scm,video/x-scm -.scq,application/scvp-cv-request -.scs,application/scvp-cv-response -.scurl,text/vnd.curl.scurl -.sda,application/vnd.stardivision.draw -.sdc,application/vnd.stardivision.calc -.sdd,application/vnd.stardivision.impress -.sdf,application/octet-stream -.sdkm,application/vnd.solent.sdkm+xml -.sdml,text/plain -.sdp,application/sdp -.sdp,application/x-sdp -.sdr,application/sounder -.sdw,application/vnd.stardivision.writer -.sea,application/sea -.sea,application/x-sea -.see,application/vnd.seemail -.seed,application/vnd.fdsn.seed -.sema,application/vnd.sema -.semd,application/vnd.semd -.semf,application/vnd.semf -.ser,application/java-serialized-object -.set,application/set -.setpay,application/set-payment-initiation -.setreg,application/set-registration-initiation -.sfd-hdstx,application/vnd.hydrostatix.sof-data -.sfnt,font/sfnt -.sfs,application/vnd.spotfire.sfs -.sgl,application/vnd.stardivision.writer-global -.sgml,text/sgml -.sgml,text/x-sgml -.sgm,text/sgml -.sgm,text/x-sgml -.sh,application/x-bsh -.sh,application/x-sh -.sh,application/x-shar -.shar,application/x-bsh -.shar,application/x-shar -.shf,application/shf+xml -.sh,text/x-script.sh -.shtml,text/html -.shtml,text/x-server-parsed-html -.sid,audio/x-psid -.sis,application/vnd.symbian.install -.sit,application/x-sit -.sit,application/x-stuffit -.sitx,application/x-stuffitx -.skd,application/x-koan -.skm,application/x-koan -.skp,application/vnd.koan -.skp,application/x-koan -.skt,application/x-koan -.sl,application/x-seelogo -.sldm,application/vnd.ms-powerpoint.slide.macroenabled.12 -.sldx,application/vnd.openxmlformats-officedocument.presentationml.slide -.slt,application/vnd.epson.salt -.sm,application/vnd.stepmania.stepchart -.smf,application/vnd.stardivision.math -.smi,application/smil -.smi,application/smil+xml -.smil,application/smil -.snd,audio/basic -.snd,audio/x-adpcm -.snf,application/x-font-snf -.sol,application/solids -.spc,application/x-pkcs7-certificates -.spc,text/x-speech -.spf,application/vnd.yamaha.smaf-phrase -.spl,application/futuresplash -.spl,application/x-futuresplash -.spot,text/vnd.in3d.spot -.spp,application/scvp-vp-response -.spq,application/scvp-vp-request -.spr,application/x-sprite -.sprite,application/x-sprite -.src,application/x-wais-source -.srt,text/srt -.sru,application/sru+xml -.srx,application/sparql-results+xml -.sse,application/vnd.kodak-descriptor -.ssf,application/vnd.epson.ssf -.ssi,text/x-server-parsed-html -.ssm,application/streamingmedia -.ssml,application/ssml+xml -.sst,application/vnd.ms-pki.certstore -.st,application/vnd.sailingtracker.track -.stc,application/vnd.sun.xml.calc.template -.std,application/vnd.sun.xml.draw.template -.step,application/step -.s,text/x-asm -.stf,application/vnd.wt.stf -.sti,application/vnd.sun.xml.impress.template -.stk,application/hyperstudio -.stl,application/sla -.stl,application/vnd.ms-pki.stl -.stl,application/x-navistyle -.stp,application/step -.str,application/vnd.pg.format -.stw,application/vnd.sun.xml.writer.template -.sub,image/vnd.dvb.subtitle -.sus,application/vnd.sus-calendar -.sv4cpio,application/x-sv4cpio -.sv4crc,application/x-sv4crc -.svc,application/vnd.dvb.service -.svd,application/vnd.svd -.svf,image/vnd.dwg -.svf,image/x-dwg -.svg,image/svg+xml -.svr,application/x-world -.svr,x-world/x-svr -.swf,application/x-shockwave-flash -.swi,application/vnd.aristanetworks.swi -.sxc,application/vnd.sun.xml.calc -.sxd,application/vnd.sun.xml.draw -.sxg,application/vnd.sun.xml.writer.global -.sxi,application/vnd.sun.xml.impress -.sxm,application/vnd.sun.xml.math -.sxw,application/vnd.sun.xml.writer -.talk,text/x-speech -.tao,application/vnd.tao.intent-module-archive -.t,application/x-troff -.tar,application/x-tar -.tbk,application/toolbook -.tbk,application/x-tbook -.tcap,application/vnd.3gpp2.tcap -.tcl,application/x-tcl -.tcl,text/x-script.tcl -.tcsh,text/x-script.tcsh -.teacher,application/vnd.smart.teacher -.tei,application/tei+xml -.tex,application/x-tex -.texi,application/x-texinfo -.texinfo,application/x-texinfo -.text,text/plain -.tfi,application/thraud+xml -.tfm,application/x-tex-tfm -.tgz,application/gnutar -.tgz,application/x-compressed -.thmx,application/vnd.ms-officetheme -.tiff,image/tiff -.tif,image/tiff -.tmo,application/vnd.tmobile-livetv -.torrent,application/x-bittorrent -.tpl,application/vnd.groove-tool-template -.tpt,application/vnd.trid.tpt -.tra,application/vnd.trueapp -.tr,application/x-troff -.trm,application/x-msterminal -.tsd,application/timestamped-data -.tsi,audio/tsp-audio -.tsp,application/dsptype -.tsp,audio/tsplayer -.tsv,text/tab-separated-values -.t,text/troff -.ttf,font/ttf -.ttl,text/turtle -.turbot,image/florian -.twd,application/vnd.simtech-mindmapper -.txd,application/vnd.genomatix.tuxedo -.txf,application/vnd.mobius.txf -.txt,text/plain -.ufd,application/vnd.ufdl -.uil,text/x-uil -.umj,application/vnd.umajin -.unis,text/uri-list -.uni,text/uri-list -.unityweb,application/vnd.unity -.unv,application/i-deas -.uoml,application/vnd.uoml+xml -.uris,text/uri-list -.uri,text/uri-list -.ustar,application/x-ustar -.ustar,multipart/x-ustar -.utz,application/vnd.uiq.theme -.uu,application/octet-stream -.uue,text/x-uuencode -.uu,text/x-uuencode -.uva,audio/vnd.dece.audio -.uvh,video/vnd.dece.hd -.uvi,image/vnd.dece.graphic -.uvm,video/vnd.dece.mobile -.uvp,video/vnd.dece.pd -.uvs,video/vnd.dece.sd -.uvu,video/vnd.uvvu.mp4 -.uvv,video/vnd.dece.video -.vcd,application/x-cdlink -.vcf,text/x-vcard -.vcg,application/vnd.groove-vcard -.vcs,text/x-vcalendar -.vcx,application/vnd.vcx -.vda,application/vda -.vdo,video/vdo -.vew,application/groupwise -.vis,application/vnd.visionary -.vivo,video/vivo -.vivo,video/vnd.vivo -.viv,video/vivo -.viv,video/vnd.vivo -.vmd,application/vocaltec-media-desc -.vmf,application/vocaltec-media-file -.vob,video/dvd -.voc,audio/voc -.voc,audio/x-voc -.vos,video/vosaic -.vox,audio/voxware -.vqe,audio/x-twinvq-plugin -.vqf,audio/x-twinvq -.vql,audio/x-twinvq-plugin -.vrml,application/x-vrml -.vrml,model/vrml -.vrml,x-world/x-vrml -.vrt,x-world/x-vrt -.vsd,application/vnd.visio -.vsd,application/x-visio -.vsf,application/vnd.vsf -.vst,application/x-visio -.vsw,application/x-visio -.vtt,text/vtt -.vtu,model/vnd.vtu -.vxml,application/voicexml+xml -.w60,application/wordperfect6.0 -.w61,application/wordperfect6.1 -.w6w,application/msword -.wad,application/x-doom -.war,application/zip -.wasm,application/wasm -.wav,audio/wav -.wax,audio/x-ms-wax -.wb1,application/x-qpro -.wbmp,image/vnd.wap.wbmp -.wbs,application/vnd.criticaltools.wbs+xml -.wbxml,application/vnd.wap.wbxml -.weba,audio/webm -.web,application/vnd.xara -.webm,video/webm -.webmanifest,application/manifest+json -.webp,image/webp -.wg,application/vnd.pmi.widget -.wgt,application/widget -.wiz,application/msword -.wk1,application/x-123 -.wma,audio/x-ms-wma -.wmd,application/x-ms-wmd -.wmf,application/x-msmetafile -.wmf,windows/metafile -.wmlc,application/vnd.wap.wmlc -.wmlsc,application/vnd.wap.wmlscriptc -.wmls,text/vnd.wap.wmlscript -.wml,text/vnd.wap.wml -.wm,video/x-ms-wm -.wmv,video/x-ms-wmv -.wmx,video/x-ms-wmx -.wmz,application/x-ms-wmz -.woff,font/woff -.woff2,font/woff2 -.word,application/msword -.wp5,application/wordperfect -.wp5,application/wordperfect6.0 -.wp6,application/wordperfect -.wp,application/wordperfect -.wpd,application/vnd.wordperfect -.wpd,application/wordperfect -.wpd,application/x-wpwin -.wpl,application/vnd.ms-wpl -.wps,application/vnd.ms-works -.wq1,application/x-lotus -.wqd,application/vnd.wqd -.wri,application/mswrite -.wri,application/x-mswrite -.wri,application/x-wri -.wrl,application/x-world -.wrl,model/vrml -.wrl,x-world/x-vrml -.wrz,model/vrml -.wrz,x-world/x-vrml -.wsc,text/scriplet -.wsdl,application/wsdl+xml -.wspolicy,application/wspolicy+xml -.wsrc,application/x-wais-source -.wtb,application/vnd.webturbo -.wtk,application/x-wintalk -.wvx,video/x-ms-wvx -.x3d,application/vnd.hzn-3d-crossword -.xap,application/x-silverlight-app -.xar,application/vnd.xara -.xbap,application/x-ms-xbap -.xbd,application/vnd.fujixerox.docuworks.binder -.xbm,image/xbm -.xbm,image/x-xbitmap -.xbm,image/x-xbm -.xdf,application/xcap-diff+xml -.xdm,application/vnd.syncml.dm+xml -.xdp,application/vnd.adobe.xdp+xml -.xdr,video/x-amt-demorun -.xdssc,application/dssc+xml -.xdw,application/vnd.fujixerox.docuworks -.xenc,application/xenc+xml -.xer,application/patch-ops-error+xml -.xfdf,application/vnd.adobe.xfdf -.xfdl,application/vnd.xfdl -.xgz,xgl/drawing -.xhtml,application/xhtml+xml -.xif,image/vnd.xiff -.xla,application/excel -.xla,application/x-excel -.xla,application/x-msexcel -.xlam,application/vnd.ms-excel.addin.macroenabled.12 -.xl,application/excel -.xlb,application/excel -.xlb,application/vnd.ms-excel -.xlb,application/x-excel -.xlc,application/excel -.xlc,application/vnd.ms-excel -.xlc,application/x-excel -.xld,application/excel -.xld,application/x-excel -.xlk,application/excel -.xlk,application/x-excel -.xll,application/excel -.xll,application/vnd.ms-excel -.xll,application/x-excel -.xlm,application/excel -.xlm,application/vnd.ms-excel -.xlm,application/x-excel -.xls,application/excel -.xls,application/vnd.ms-excel -.xls,application/x-excel -.xls,application/x-msexcel -.xlsb,application/vnd.ms-excel.sheet.binary.macroenabled.12 -.xlsm,application/vnd.ms-excel.sheet.macroenabled.12 -.xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet -.xlt,application/excel -.xlt,application/x-excel -.xltm,application/vnd.ms-excel.template.macroenabled.12 -.xltx,application/vnd.openxmlformats-officedocument.spreadsheetml.template -.xlv,application/excel -.xlv,application/x-excel -.xlw,application/excel -.xlw,application/vnd.ms-excel -.xlw,application/x-excel -.xlw,application/x-msexcel -.xm,audio/xm -.xml,application/xml -.xml,text/xml -.xmz,xgl/movie -.xo,application/vnd.olpc-sugar -.xop,application/xop+xml -.xpi,application/x-xpinstall -.xpix,application/x-vnd.ls-xpix -.xpm,image/xpm -.xpm,image/x-xpixmap -.x-png,image/png -.xpr,application/vnd.is-xpr -.xps,application/vnd.ms-xpsdocument -.xpw,application/vnd.intercon.formnet -.xslt,application/xslt+xml -.xsm,application/vnd.syncml+xml -.xspf,application/xspf+xml -.xsr,video/x-amt-showrun -.xul,application/vnd.mozilla.xul+xml -.xwd,image/x-xwd -.xwd,image/x-xwindowdump -.xyz,chemical/x-pdb -.xyz,chemical/x-xyz -.xz,application/x-xz -.yaml,text/yaml -.yang,application/yang -.yin,application/yin+xml -.z,application/x-compress -.z,application/x-compressed -.zaz,application/vnd.zzazz.deck+xml -.zip,application/zip -.zip,application/x-compressed -.zip,application/x-zip-compressed -.zip,multipart/x-zip -.zir,application/vnd.zul -.zmm,application/vnd.handheld-entertainment+xml -.zoo,application/octet-stream -.zsh,text/x-script.zsh +application/acad,dwg +application/andrew-inset,ez +application/applixware,aw +application/arj,arj +application/atom+xml,atom +application/atomcat+xml,atomcat +application/atomsvc+xml,atomsvc +application/base64,mm mme +application/binhex,hqx +application/binhex4,hqx +application/book,boo book +application/ccxml+xml,ccxml +application/cdf,cdf +application/cdmi-capability,cdmia +application/cdmi-container,cdmic +application/cdmi-domain,cdmid +application/cdmi-object,cdmio +application/cdmi-queue,cdmiq +application/clariscad,ccad +application/commonground,dp +application/cu-seeme,cu +application/davmount+xml,davmount +application/drafting,drw +application/dsptype,tsp +application/dssc+der,dssc +application/dssc+xml,xdssc +application/dxf,dxf +application/emma+xml,emma +application/envoy,evy +application/epub+zip,epub +application/excel,xl xla xlb xlc xld xlk xll xlm xls xlt xlv xlw +application/exi,exi +application/font-tdpfr,pfr +application/fractals,fif +application/freeloader,frl +application/futuresplash,spl +application/gnutar,tgz +application/groupwise,vew +application/gzip,gz gzip +application/hlp,hlp +application/hta,hta +application/hyperstudio,stk +application/i-deas,unv +application/iff,iff +application/iges,iges igs +application/inf,inf +application/ipfix,ipfix +application/java,class +application/java-archive,jar +application/java-byte-code,class +application/java-serialized-object,ser +application/java-vm,class +application/json,json +application/lha,lha +application/lzx,lzx +application/macbinary,bin +application/mac-binary,bin +application/mac-binhex,hqx +application/mac-binhex40,hqx +application/mac-compactpro,cpt +application/mads+xml,mads +application/manifest+json,webmanifest +application/marc,mrc +application/marcxml+xml,mrcx +application/mathematica,ma +application/mathml+xml,mathml +application/mbedlet,mbd +application/mbox,mbox +application/mcad,mcd +application/mediaservercontrol+xml,mscml +application/metalink4+xml,meta4 +application/mets+xml,mets +application/mime,aps +application/mods+xml,mods +application/mp21,m21 +application/mspowerpoint,pot pps ppt ppz +application/msword,doc dot w6w wiz word +application/mswrite,wri +application/mxf,mxf +application/netmc,mcp +application/octet-stream,a arc arj bin com dump exe keychain lzh lzx o psd saveme sdf uu zoo +application/oda,oda +application/oebps-package+xml,opf +application/ogg,ogx +application/onenote,onetoc +application/patch-ops-error+xml,xer +application/pdf,pdf +application/pgp-encrypted, +application/pgp-keys,key +application/pgp-signature,pgp +application/pics-rules,prf +application/pkcs-12,p12 +application/pkcs-crl,crl +application/pkcs10,p10 +application/pkcs7-mime,p7c p7m +application/pkcs7-signature,p7s +application/pkcs8,p8 +application/pkix-attr-cert,ac +application/pkix-cert,cer crt +application/pkix-crl,crl +application/pkix-pkipath,pkipath +application/pkixcmp,pki +application/pls+xml,pls +application/postscript,ai eps ps +application/powerpoint,ppt +application/pro_eng,part prt +application/prs.cww,cww +application/pskc+xml,pskcxml +application/rdf+xml,rdf +application/reginfo+xml,rif +application/relax-ng-compact-syntax,rnc +application/resource-lists+xml,rl +application/resource-lists-diff+xml,rld +application/ringing-tones,rng +application/rls-services+xml,rs +application/rsd+xml,rsd +application/rss+xml,rss +application/rtf,rtf rtx +application/sbml+xml,sbml +application/scvp-cv-request,scq +application/scvp-cv-response,scs +application/scvp-vp-request,spq +application/scvp-vp-response,spp +application/sdp,sdp +application/sea,sea +application/set,set +application/set-payment-initiation,setpay +application/set-registration-initiation,setreg +application/shf+xml,shf +application/sla,stl +application/smil+xml,smi +application/solids,sol +application/sounder,sdr +application/sparql-query,rq +application/sparql-results+xml,srx +application/srgs+xml,grxml +application/srgs,gram +application/sru+xml,sru +application/ssml+xml,ssml +application/step,step stp +application/streamingmedia,ssm +application/tei+xml,tei +application/thraud+xml,tfi +application/timestamped-data,tsd +application/toolbook,tbk +application/vda,vda +application/vnd.3gpp.pic-bw-large,plb +application/vnd.3gpp.pic-bw-small,psb +application/vnd.3gpp.pic-bw-var,pvb +application/vnd.3gpp2.tcap,tcap +application/vnd.3m.post-it-notes,pwn +application/vnd.accpac.simply.aso,aso +application/vnd.accpac.simply.imp,imp +application/vnd.acucobol,acu +application/vnd.acucorp,atc +application/vnd.adobe.air-application-installer-package+zip,air +application/vnd.adobe.fxp,fxp +application/vnd.adobe.xdp+xml,xdp +application/vnd.adobe.xfdf,xfdf +application/vnd.ahead.space,ahead +application/vnd.airzip.filesecure.azf,azf +application/vnd.airzip.filesecure.azs,azs +application/vnd.amazon.ebook,azw +application/vnd.americandynamics.acc,acc +application/vnd.amiga.ami,ami +application/vnd.android.package-archive,apk +application/vnd.anser-web-certificate-issue-initiation,cii +application/vnd.anser-web-funds-transfer-initiation,fti +application/vnd.antix.game-component,atx +application/vnd.apple.installer+xml,mpkg +application/vnd.apple.mpegurl,m3u8 +application/vnd.apple.pages,pages +application/vnd.aristanetworks.swi,swi +application/vnd.audiograph,aep +application/vnd.blueice.multipass,mpm +application/vnd.bmi,bmi +application/vnd.businessobjects,rep +application/vnd.chemdraw+xml,cdxml +application/vnd.chipnuts.karaoke-mmd,mmd +application/vnd.cinderella,cdy +application/vnd.claymore,cla +application/vnd.cloanto.rp9,rp9 +application/vnd.clonk.c4group,c4g +application/vnd.cluetrust.cartomobile-config,c11amc +application/vnd.cluetrust.cartomobile-config-pkg,c11amz +application/vnd.commonspace,csp +application/vnd.contact.cmsg,cdbcmsg +application/vnd.cosmocaller,cmc +application/vnd.crick.clicker,clkx +application/vnd.crick.clicker.keyboard,clkk +application/vnd.crick.clicker.palette,clkp +application/vnd.crick.clicker.template,clkt +application/vnd.crick.clicker.wordbank,clkw +application/vnd.criticaltools.wbs+xml,wbs +application/vnd.ctc-posml,pml +application/vnd.cups-ppd,ppd +application/vnd.curl.car,car +application/vnd.curl.pcurl,pcurl +application/vnd.data-vision.rdz,rdz +application/vnd.denovo.fcselayout-link,fe_launch +application/vnd.dna,dna +application/vnd.dolby.mlp,mlp +application/vnd.dpgraph,dpg +application/vnd.dreamfactory,dfac +application/vnd.dvb.ait,ait +application/vnd.dvb.service,svc +application/vnd.dynageo,geo +application/vnd.ecowin.chart,mag +application/vnd.enliven,nml +application/vnd.epson.esf,esf +application/vnd.epson.msf,msf +application/vnd.epson.quickanime,qam +application/vnd.epson.salt,slt +application/vnd.epson.ssf,ssf +application/vnd.eszigno3+xml,es3 +application/vnd.ezpix-album,ez2 +application/vnd.ezpix-package,ez3 +application/vnd.fdf,fdf +application/vnd.fdsn.seed,seed +application/vnd.flographit,gph +application/vnd.fluxtime.clip,ftc +application/vnd.framemaker,fm +application/vnd.fsc.weblaunch,fsc +application/vnd.fujitsu.oasys,oas +application/vnd.fujitsu.oasys2,oa2 +application/vnd.fujitsu.oasys3,oa3 +application/vnd.fujitsu.oasysgp,fg5 +application/vnd.fujitsu.oasysprs,bh2 +application/vnd.fujixerox.ddd,ddd +application/vnd.fujixerox.docuworks,xdw +application/vnd.fujixerox.docuworks.binder,xbd +application/vnd.fuzzysheet,fzs +application/vnd.genomatix.tuxedo,txd +application/vnd.geogebra.file,ggb +application/vnd.geogebra.tool,ggt +application/vnd.geometry-explorer,gex +application/vnd.geonext,gxt +application/vnd.geoplan,g2w +application/vnd.geospace,g3w +application/vnd.gmx,gmx +application/vnd.google-earth.kml+xml,kml +application/vnd.google-earth.kmz,kmz +application/vnd.grafeq,gqf +application/vnd.groove-account,gac +application/vnd.groove-help,ghf +application/vnd.groove-identity-message,gim +application/vnd.groove-injector,grv +application/vnd.groove-tool-message,gtm +application/vnd.groove-tool-template,tpl +application/vnd.groove-vcard,vcg +application/vnd.hal+xml,hal +application/vnd.handheld-entertainment+xml,zmm +application/vnd.hbci,hbci +application/vnd.hhe.lesson-player,les +application/vnd.hp-hpgl,hgl hpg hpgl +application/vnd.hp-hpid,hpid +application/vnd.hp-hps,hps +application/vnd.hp-jlyt,jlt +application/vnd.hp-pcl,pcl +application/vnd.hp-pclxl,pclxl +application/vnd.hydrostatix.sof-data,sfd-hdstx +application/vnd.hzn-3d-crossword,x3d +application/vnd.ibm.minipay,mpy +application/vnd.ibm.rights-management,irm +application/vnd.ibm.secure-container,sc +application/vnd.iccprofile,icc +application/vnd.igloader,igl +application/vnd.immervision-ivp,ivp +application/vnd.immervision-ivu,ivu +application/vnd.insors.igm,igm +application/vnd.intercon.formnet,xpw +application/vnd.intergeo,i2g +application/vnd.intu.qbo,qbo +application/vnd.intu.qfx,qfx +application/vnd.ipunplugged.rcprofile,rcprofile +application/vnd.irepository.package+xml,irp +application/vnd.is-xpr,xpr +application/vnd.isac.fcs,fcs +application/vnd.jam,jam +application/vnd.jcp.javame.midlet-rms,rms +application/vnd.jisp,jisp +application/vnd.joost.joda-archive,joda +application/vnd.kahootz,ktz +application/vnd.kde.karbon,karbon +application/vnd.kde.kchart,chrt +application/vnd.kde.kformula,kfo +application/vnd.kde.kivio,flw +application/vnd.kde.kontour,kon +application/vnd.kde.kpresenter,kpr +application/vnd.kde.kspread,ksp +application/vnd.kde.kword,kwd +application/vnd.kenameaapp,htke +application/vnd.kidspiration,kia +application/vnd.kinar,kne +application/vnd.koan,skp +application/vnd.kodak-descriptor,sse +application/vnd.las.las+xml,lasxml +application/vnd.llamagraphics.life-balance.desktop,lbd +application/vnd.llamagraphics.life-balance.exchange+xml,lbe +application/vnd.lotus-1-2-3,123 +application/vnd.lotus-approach,apr +application/vnd.lotus-freelance,pre +application/vnd.lotus-notes,nsf +application/vnd.lotus-organizer,org +application/vnd.lotus-screencam,scm +application/vnd.lotus-wordpro,lwp +application/vnd.macports.portpkg,portpkg +application/vnd.mcd,mcd +application/vnd.medcalcdata,mc1 +application/vnd.mediastation.cdkey,cdkey +application/vnd.mfer,mwf +application/vnd.mfmp,mfm +application/vnd.micrografx.flo,flo +application/vnd.micrografx.igx,igx +application/vnd.mif,mif +application/vnd.mobius.daf,daf +application/vnd.mobius.dis,dis +application/vnd.mobius.mbk,mbk +application/vnd.mobius.mqy,mqy +application/vnd.mobius.msl,msl +application/vnd.mobius.plc,plc +application/vnd.mobius.txf,txf +application/vnd.mophun.application,mpn +application/vnd.mophun.certificate,mpc +application/vnd.mozilla.xul+xml,xul +application/vnd.ms-artgalry,cil +application/vnd.ms-cab-compressed,cab +application/vnd.ms-excel,xlb xlc xll xlm xls xlw +application/vnd.ms-excel.addin.macroenabled.12,xlam +application/vnd.ms-excel.sheet.binary.macroenabled.12,xlsb +application/vnd.ms-excel.sheet.macroenabled.12,xlsm +application/vnd.ms-excel.template.macroenabled.12,xltm +application/vnd.ms-fontobject,eot +application/vnd.ms-htmlhelp,chm +application/vnd.ms-ims,ims +application/vnd.ms-lrm,lrm +application/vnd.ms-officetheme,thmx +application/vnd.ms-outlook,msg +application/vnd.ms-pki.certstore,sst +application/vnd.ms-pki.pko,pko +application/vnd.ms-pki.seccat,cat +application/vnd.ms-pki.stl,stl +application/vnd.ms-powerpoint,pot ppa pps ppt pwz +application/vnd.ms-powerpoint.addin.macroenabled.12,ppam +application/vnd.ms-powerpoint.presentation.macroenabled.12,pptm +application/vnd.ms-powerpoint.slide.macroenabled.12,sldm +application/vnd.ms-powerpoint.slideshow.macroenabled.12,ppsm +application/vnd.ms-powerpoint.template.macroenabled.12,potm +application/vnd.ms-project,mpp +application/vnd.ms-word.document.macroenabled.12,docm +application/vnd.ms-word.template.macroenabled.12,dotm +application/vnd.ms-works,wps +application/vnd.ms-wpl,wpl +application/vnd.ms-xpsdocument,xps +application/vnd.mseq,mseq +application/vnd.musician,mus +application/vnd.muvee.style,msty +application/vnd.neurolanguage.nlu,nlu +application/vnd.noblenet-directory,nnd +application/vnd.noblenet-sealer,nns +application/vnd.noblenet-web,nnw +application/vnd.nokia.configuration-message,ncm +application/vnd.nokia.n-gage.data,ngdat +application/vnd.nokia.radio-preset,rpst +application/vnd.nokia.radio-presets,rpss +application/vnd.nokia.ringing-tone,rng +application/vnd.novadigm.edm,edm +application/vnd.novadigm.edx,edx +application/vnd.novadigm.ext,ext +application/vnd.oasis.opendocument.chart,odc +application/vnd.oasis.opendocument.chart-template,otc +application/vnd.oasis.opendocument.formula,odf +application/vnd.oasis.opendocument.formula-template,odft +application/vnd.oasis.opendocument.graphics,odg +application/vnd.oasis.opendocument.graphics-template,otg +application/vnd.oasis.opendocument.image,odi +application/vnd.oasis.opendocument.image-template,oti +application/vnd.oasis.opendocument.presentation,odp +application/vnd.oasis.opendocument.presentation-template,otp +application/vnd.oasis.opendocument.spreadsheet,ods +application/vnd.oasis.opendocument.spreadsheet-template,ots +application/vnd.oasis.opendocument.text,odt +application/vnd.oasis.opendocument.text-master,odm +application/vnd.oasis.opendocument.text-template,ott +application/vnd.oasis.opendocument.text-web,oth +application/vnd.olpc-sugar,xo +application/vnd.oma.dd2+xml,dd2 +application/vnd.openofficeorg.extension,oxt +application/vnd.openxmlformats-officedocument.presentationml.presentation,pptx +application/vnd.openxmlformats-officedocument.presentationml.slide,sldx +application/vnd.openxmlformats-officedocument.presentationml.slideshow,ppsx +application/vnd.openxmlformats-officedocument.presentationml.template,potx +application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,xlsx +application/vnd.openxmlformats-officedocument.spreadsheetml.template,xltx +application/vnd.openxmlformats-officedocument.wordprocessingml.document,docx +application/vnd.openxmlformats-officedocument.wordprocessingml.template,dotx +application/vnd.osgeo.mapguide.package,mgp +application/vnd.osgi.dp,dp +application/vnd.palm,pdb +application/vnd.pawaafile,paw +application/vnd.pg.format,str +application/vnd.pg.osasli,ei6 +application/vnd.picsel,efif +application/vnd.pmi.widget,wg +application/vnd.pocketlearn,plf +application/vnd.powerbuilder6,pbd +application/vnd.previewsystems.box,box +application/vnd.proteus.magazine,mgz +application/vnd.publishare-delta-tree,qps +application/vnd.pvi.ptid1,ptid +application/vnd.quark.quarkxpress,qxd +application/vnd.realvnc.bed,bed +application/vnd.recordare.musicxml+xml,musicxml +application/vnd.recordare.musicxml,mxl +application/vnd.rig.cryptonote,cryptonote +application/vnd.rim.cod,cod +application/vnd.rn-realmedia,rm +application/vnd.rn-realplayer,rnx +application/vnd.route66.link66+xml,link66 +application/vnd.sailingtracker.track,st +application/vnd.seemail,see +application/vnd.sema,sema +application/vnd.semd,semd +application/vnd.semf,semf +application/vnd.shana.informed.formdata,ifm +application/vnd.shana.informed.formtemplate,itp +application/vnd.shana.informed.interchange,iif +application/vnd.shana.informed.package,ipk +application/vnd.simtech-mindmapper,twd +application/vnd.smaf,mmf +application/vnd.smart.teacher,teacher +application/vnd.solent.sdkm+xml,sdkm +application/vnd.spotfire.dxp,dxp +application/vnd.spotfire.sfs,sfs +application/vnd.stardivision.calc,sdc +application/vnd.stardivision.draw,sda +application/vnd.stardivision.impress,sdd +application/vnd.stardivision.math,smf +application/vnd.stardivision.writer,sdw +application/vnd.stardivision.writer-global,sgl +application/vnd.stepmania.stepchart,sm +application/vnd.sun.xml.calc,sxc +application/vnd.sun.xml.calc.template,stc +application/vnd.sun.xml.draw,sxd +application/vnd.sun.xml.draw.template,std +application/vnd.sun.xml.impress,sxi +application/vnd.sun.xml.impress.template,sti +application/vnd.sun.xml.math,sxm +application/vnd.sun.xml.writer,sxw +application/vnd.sun.xml.writer.global,sxg +application/vnd.sun.xml.writer.template,stw +application/vnd.sus-calendar,sus +application/vnd.svd,svd +application/vnd.symbian.install,sis +application/vnd.syncml+xml,xsm +application/vnd.syncml.dm+wbxml,bdm +application/vnd.syncml.dm+xml,xdm +application/vnd.tao.intent-module-archive,tao +application/vnd.tmobile-livetv,tmo +application/vnd.trid.tpt,tpt +application/vnd.triscape.mxs,mxs +application/vnd.trueapp,tra +application/vnd.ufdl,ufd +application/vnd.uiq.theme,utz +application/vnd.umajin,umj +application/vnd.unity,unityweb +application/vnd.uoml+xml,uoml +application/vnd.vcx,vcx +application/vnd.visio,vsd +application/vnd.visionary,vis +application/vnd.vsf,vsf +application/vnd.wap.wbxml,wbxml +application/vnd.wap.wmlc,wmlc +application/vnd.wap.wmlscriptc,wmlsc +application/vnd.webturbo,wtb +application/vnd.wolfram.player,nbp +application/vnd.wordperfect,wpd +application/vnd.wqd,wqd +application/vnd.wt.stf,stf +application/vnd.xara,web xar +application/vnd.xfdl,xfdl +application/vnd.yamaha.hv-dic,hvd +application/vnd.yamaha.hv-script,hvs +application/vnd.yamaha.hv-voice,hvp +application/vnd.yamaha.openscoreformat,osf +application/vnd.yamaha.openscoreformat.osfpvg+xml,osfpvg +application/vnd.yamaha.smaf-audio,saf +application/vnd.yamaha.smaf-phrase,spf +application/vnd.yellowriver-custom-menu,cmp +application/vnd.zul,zir +application/vnd.zzazz.deck+xml,zaz +application/vocaltec-media-desc,vmd +application/vocaltec-media-file,vmf +application/voicexml+xml,vxml +application/wasm,wasm +application/widget,wgt +application/winhlp,hlp +application/wordperfect,wp wp5 wp6 wpd +application/wordperfect6.0,w60 wp5 +application/wordperfect6.1,w61 +application/wsdl+xml,wsdl +application/wspolicy+xml,wspolicy +application/x-123,wk1 +application/x-7z-compressed,7z +application/x-abiword,abw +application/x-ace-compressed,ace +application/x-aim,aim +application/x-authorware-bin,aab +application/x-authorware-map,aam +application/x-authorware-seg,aas +application/x-bcpio,bcpio +application/x-binary,bin +application/x-binhex40,hqx +application/x-bittorrent,torrent +application/x-bsh,bsh sh shar +application/x-bytecode.python,pyc +application/x-bzip,bz +application/x-bzip2,boz bz2 +application/x-cdf,cdf +application/x-cdlink,vcd +application/x-chat,cha chat +application/x-chess-pgn,pgn +application/x-cmu-raster,ras +application/x-cocoa,cco +application/x-compactpro,cpt +application/x-compress,z +application/zip,zip +application/x-compressed,gz tgz z zip +application/x-conference,nsc +application/x-cpio,cpio +application/x-cpt,cpt +application/x-csh,csh +application/x-debian-package,deb +application/x-deepv,deepv +application/x-director,dcr dir dxr +application/x-doom,wad +application/x-dtbncx+xml,ncx +application/x-dtbook+xml,dtb +application/x-dtbresource+xml,res +application/x-dvi,dvi +application/x-elc,elc +application/x-envoy,env evy +application/x-esrehber,es +application/x-excel,xla xlb xlc xld xlk xll xlm xls xlt xlv xlw +application/x-font-bdf,bdf +application/x-font-ghostscript,gsf +application/x-font-linux-psf,psf +application/x-font-pcf,pcf +application/x-font-snf,snf +application/x-font-type1,pfa +application/x-frame,mif +application/x-freelance,pre +application/x-futuresplash,spl +application/x-gnumeric,gnumeric +application/x-gsp,gsp +application/x-gss,gss +application/x-gtar,gtar +application/x-gzip,gz gzip +application/x-hdf,hdf +application/x-helpfile,help hlp +application/x-httpd-imap,imap +application/x-ima,ima +application/x-internett-signup,ins +application/x-inventor,iv +application/x-ip2,ip +application/x-java-class,class +application/x-java-commerce,jcm +application/x-java-jnlp-file,jnlp +application/x-koan,skd skm skp skt +application/x-ksh,ksh +application/x-latex,latex ltx +application/x-lha,lha +application/x-lisp,lsp +application/x-livescreen,ivy +application/x-lotus,wq1 +application/x-lotusscreencam,scm +application/x-lzh,lzh +application/x-lzx,lzx +application/x-mac-binhex40,hqx +application/x-macbinary,bin +application/x-magic-cap-package-1.0,mc${'$'} +application/x-mathcad,mcd +application/x-meme,mm +application/x-midi,mid midi +application/x-mif,mif +application/x-mix-transfer,nix +application/x-mobipocket-ebook,prc +application/x-mplayer2,asx +application/x-ms-application,application +application/x-ms-wmd,wmd +application/x-ms-wmz,wmz +application/x-ms-xbap,xbap +application/x-msaccess,mdb +application/x-msbinder,obd +application/x-mscardfile,crd +application/x-msclip,clp +application/x-msdownload,exe +application/x-msexcel,xla xls xlw +application/x-msmediaview,mvb +application/x-msmetafile,wmf +application/x-msmoney,mny +application/x-mspowerpoint,ppt +application/x-mspublisher,pub +application/x-msschedule,scd +application/x-msterminal,trm +application/x-mswrite,wri +application/x-navi-animation,ani +application/x-navidoc,nvd +application/x-navimap,map +application/x-navistyle,stl +application/x-netcdf,cdf nc +application/x-newton-compatible-pkg,pkg +application/x-nokia-9000-communicator-add-on-software,aos +application/x-omc,omc +application/x-omcdatamaker,omcd +application/x-omcregerator,omcr +application/x-pagemaker,pm4 pm5 +application/x-pcl,pcl +application/x-pem-file,pem +application/x-pixclscript,plx +application/x-pkcs12,pfx +application/x-pkcs7-certificates,p7b spc +application/x-pkcs7-certreqresp,p7r +application/x-pkcs7-signature,p7a +application/x-portable-anymap,pnm +application/x-project,mpc mpt mpv mpx +application/x-qpro,wb1 +application/x-rar-compressed,rar +application/x-sdp,sdp +application/x-sea,sea +application/x-seelogo,sl +application/x-sh,sh +application/x-shar,sh shar +application/x-shockwave-flash,swf +application/x-silverlight-app,xap +application/x-sit,sit +application/x-sprite,spr sprite +application/x-stuffit,sit +application/x-stuffitx,sitx +application/x-sv4cpio,sv4cpio +application/x-sv4crc,sv4crc +application/x-tar,tar +application/x-tbook,sbk tbk +application/x-tcl,tcl +application/x-tex,tex +application/x-tex-tfm,tfm +application/x-texinfo,texi texinfo +application/x-troff,roff t tr +application/x-troff-man,man +application/x-troff-me,me +application/x-troff-ms,ms +application/x-ustar,ustar +application/x-visio,vsd vst vsw +application/x-vnd.audioexplosion.mzz,mzz +application/x-vnd.ls-xpix,xpix +application/x-vrml,vrml +application/x-wais-source,src wsrc +application/x-winhelp,hlp +application/x-wintalk,wtk +application/x-world,svr wrl +application/x-wpwin,wpd +application/x-wri,wri +application/x-x509-ca-cert,crt der +application/x-x509-user-cert,crt +application/x-xfig,fig +application/x-xpinstall,xpi +application/x-xz,xz +application/x-zip-compressed,zip +application/xcap-diff+xml,xdf +application/xenc+xml,xenc +application/xhtml+xml,xhtml +application/xml,xml +application/xml-dtd,dtd +application/xop+xml,xop +application/xslt+xml,xslt +application/xspf+xml,xspf +application/xv+xml,mxml +application/yang,yang +application/yin+xml,yin +application/zip,war +audio/aac,aac +audio/adpcm,adp +audio/aiff,aif aifc aiff +audio/basic,au snd +audio/it,it +audio/make,funk my pfunk +audio/make.my.funk,pfunk +audio/mid,rmi +audio/midi,kar mid midi +audio/mod,mod +audio/mp4,m4a mp4a +audio/mpeg,m2a mp2 mp3 mpa mpga +audio/mpeg3,mp3 +audio/nspaudio,la lma +audio/ogg,oga ogg +audio/s3m,s3m +audio/tsp-audio,tsi +audio/tsplayer,tsp +audio/vnd.dece.audio,uva +audio/vnd.digital-winds,eol +audio/vnd.dra,dra +audio/vnd.dts,dts +audio/vnd.dts.hd,dtshd +audio/vnd.lucent.voice,lvp +audio/vnd.ms-playready.media.pya,pya +audio/vnd.nuera.ecelp4800,ecelp4800 +audio/vnd.nuera.ecelp7470,ecelp7470 +audio/vnd.nuera.ecelp9600,ecelp9600 +audio/vnd.qcelp,qcp +audio/vnd.rip,rip +audio/voc,voc +audio/voxware,vox +audio/wav,wav +audio/webm,weba +audio/x-adpcm,snd +audio/x-au,au +audio/x-gsm,gsd gsm +audio/x-jam,jam +audio/x-liveaudio,lam +audio/x-mid,mid midi +audio/x-midi,midi +audio/x-mod,mod +audio/x-mpeg,mp2 +audio/x-mpegurl,m3u +audio/x-ms-wax,wax +audio/x-ms-wma,wma +audio/x-nspaudio,la lma +audio/x-pn-realaudio,ra ram rm rmm rmp +audio/x-pn-realaudio-plugin,ra rmp rpm +application/x-rpm,rpm +audio/x-psid,sid +audio/x-realaudio,ra +audio/x-twinvq,vqf +audio/x-twinvq-plugin,vqe vql +audio/x-vnd.audioexplosion.mjuicemediafile,mjf +audio/x-voc,voc +audio/xm,xm +binary/octet-stream,dat +chemical/x-cdx,cdx +chemical/x-cif,cif +chemical/x-cmdf,cmdf +chemical/x-cml,cml +chemical/x-csml,csml +chemical/x-pdb,pdb xyz +chemical/x-xyz,xyz +font/collection ,collection +font/otf,otf +font/sfnt,sfnt +font/ttf,ttf +font/woff,woff +font/woff2,woff2 +i-world/i-vrml,ivr +image/avif,avif avifs +image/bmp,bm bmp +image/cgm,cgm +image/cmu-raster,ras rast +image/fif,fif +image/florian,flo turbot +image/g3fax,g3 +image/gif,gif +image/heic,heic +image/heif,heif +image/ief,ief iefs +image/jpeg,jfif jfif-tbnl jpe jpeg jpg +image/jutvision,jut +image/ktx,ktx +image/naplps,nap naplps +image/pict,pic pict +image/pjpeg,jfif +image/png,png x-png +image/prs.btif,btif +image/svg+xml,svg +image/tiff,tif tiff +image/vasa,mcf +image/vnd.adobe.photoshop,psd +image/vnd.dece.graphic,uvi +image/vnd.djvu,djvu +image/vnd.dvb.subtitle,sub +image/vnd.dwg,dwg dxf svf +image/vnd.dxf,dxf +image/vnd.fastbidsheet,fbs +image/vnd.fpx,fpx +image/vnd.fst,fst +image/vnd.fujixerox.edmics-mmr,mmr +image/vnd.fujixerox.edmics-rlc,rlc +image/vnd.ms-modi,mdi +image/vnd.net-fpx,fpx npx +image/vnd.rn-realflash,rf +image/vnd.rn-realpix,rp +image/vnd.wap.wbmp,wbmp +image/vnd.xiff,xif +image/webp,webp +image/x-cmu-raster,ras +image/x-cmx,cmx +image/x-dwg,dwg dxf svf +image/x-freehand,fh +image/x-icon,ico +image/x-jg,art +image/x-jps,jps +image/x-niff,nif niff +image/x-pcx,pcx +image/x-pict,pct +image/x-portable-anymap,pnm +image/x-portable-bitmap,pbm +image/x-portable-graymap,pgm +image/x-portable-pixmap,ppm +image/x-quicktime,qif qti qtif +image/x-rgb,rgb +image/x-windows-bmp,bmp +image/x-xbitmap,xbm +image/x-xbm,xbm +image/x-xpixmap,pm xpm +image/x-xwd,xwd +image/x-xwindowdump,xwd +image/xbm,xbm +image/xpm,xpm +message/rfc822,eml mht mhtml mime +model/iges,iges igs +model/mesh,msh +model/vnd.collada+xml,dae +model/vnd.dwf,dwf +model/vnd.gdl,gdl +model/vnd.gtw,gtw +model/vnd.mts,mts +model/vnd.vtu,vtu +model/vrml,vrml wrl wrz +model/x-pov,pov +multipart/x-gzip,gzip +multipart/x-ustar,ustar +multipart/x-zip,zip +music/crescendo,mid midi +music/x-karaoke,kar +paleovu/x-pv,pvu +text/asp,asp +text/calendar,ics +text/css,css +text/csv,csv +text/html,acgi htm html htmls htx shtml +text/javascript,js mjs +text/mcf,mcf +text/n3,n3 +text/pascal,pas +text/plain,c c++ cc com conf cxx def f f90 for g h hh idc jav java list log lst m mar pl sdml text txt +text/plain-bas,par +text/prs.lines.tag,dsc +text/richtext,rt rtx +text/rtf,rtf +text/scriplet,wsc +text/sgml,sgm sgml +text/srt,srt +text/tab-separated-values,tsv +text/troff,t +text/turtle,ttl +text/uri-list,uni unis uri uris +text/vnd.abc,abc +text/vnd.curl,curl +text/vnd.curl.dcurl,dcurl +text/vnd.curl.mcurl,mcurl +text/vnd.curl.scurl,scurl +text/vnd.fly,fly +text/vnd.fmi.flexstor,flx +text/vnd.graphviz,gv +text/vnd.in3d.3dml,3dml +text/vnd.in3d.spot,spot +text/vnd.rn-realtext,rt +text/vnd.sun.j2me.app-descriptor,jad +text/vnd.wap.wml,wml +text/vnd.wap.wmlscript,wmls +text/vtt,vtt +text/webviewhtml,htt +text/x-asm,asm s +text/x-audiosoft-intra,aip +text/x-c,c cc cpp +text/x-component,htc +text/x-fortran,f f77 f90 for +text/x-h,h hh +text/x-java-source,jav java +text/x-la-asf,lsx +text/x-m,m +text/x-pascal,p +text/x-script,hlb +text/x-script.csh,csh +text/x-script.elisp,el +text/x-script.guile,scm +text/x-script.ksh,ksh +text/x-script.lisp,lsp +text/x-script.perl,pl +text/x-script.perl-module,pm +text/x-script.python,py +text/x-script.rexx,rexx +text/x-script.scheme,scm +text/x-script.sh,sh +text/x-script.tcl,tcl +text/x-script.tcsh,tcsh +text/x-script.zsh,zsh +text/x-server-parsed-html,shtml ssi +text/x-setext,etx +text/x-sgml,sgm sgml +text/x-speech,spc talk +text/x-uil,uil +text/x-uuencode,uu uue +text/x-vcalendar,vcs +text/x-vcard,vcf +text/xml,xml +text/yaml,yaml +video/3gpp,3gp +video/3gpp2,3g2 +video/animaflex,afl +video/avi,avi +video/avs-video,avs +video/dl,dl +video/dvd,vob +video/fli,fli +video/gl,gl +video/h261,h261 +video/h263,h263 +video/h264,h264 +video/jpeg,jpgv +video/jpm,jpm +video/mj2,mj2 +video/mp4,m4v mp4 +application/mp4,mp4 +video/mpeg,m1v m2v mp2 mpe mpeg mpg +audio/mpeg,mpg +video/msvideo,avi +video/ogg,ogv +video/quicktime,moov mov qt +video/vdo,vdo +video/vivo,viv vivo +video/vnd.dece.hd,uvh +video/vnd.dece.mobile,uvm +video/vnd.dece.pd,uvp +video/vnd.dece.sd,uvs +video/vnd.dece.video,uvv +video/vnd.fvt,fvt +video/vnd.mpegurl,mxu +video/vnd.ms-playready.media.pyv,pyv +video/vnd.rn-realvideo,rv +video/vnd.uvvu.mp4,uvu +video/vnd.vivo,viv vivo +video/vosaic,vos +video/webm,webm +video/x-amt-demorun,xdr +video/x-amt-showrun,xsr +video/x-atomic3d-feature,fmf +video/x-dl,dl +video/x-dv,dif dv +video/x-f4v,f4v +video/x-fli,fli +video/x-flv,flv +video/x-gl,gl +video/x-isvideo,isu +video/x-matroska,mkv +audio/x-matroska,mkv +video/x-motion-jpeg,mjpg +video/x-mpeg,mp2 +video/x-mpeq2a,mp2 +video/x-ms-asf,asf asx +video/x-ms-asf-plugin,asx +video/x-ms-wm,wm +video/x-ms-wmv,wmv +video/x-ms-wmx,wmx +video/x-ms-wvx,wvx +video/x-msvideo,avi +video/x-qtc,qtc +video/x-scm,scm +video/x-sgi-movie,movie mv +windows/metafile,wmf +www/mime,mime +x-conference/x-cooltalk,ice +x-music/x-midi,mid midi +x-world/x-3dmf,3dm 3dmf qd3 qd3d +x-world/x-svr,svr +x-world/x-vrml,vrml wrl wrz +x-world/x-vrt,vrt +xgl/drawing,xgz +xgl/movie,xmz +# Deprecated media types +application/ecmascript,es +application/javascript,js +application/smil,smi sml +application/vnd.frogans.fnc,fnc +application/vnd.frogans.ltf,ltf +application/vnd.ibm.modcap,afp +application/vnd.nokia.n-gage.symbian.install,n-gage +application/vnd.oasis.opendocument.database,odb """ internal fun loadMimes(): List> { - return rawMimes.lineSequence().mapNotNull { + return rawMimes.lineSequence().flatMapTo(ArrayList(INITIAL_MIMES_LIST_SIZE)) { val line = it.trim() - if (line.isEmpty()) return@mapNotNull null - - val index = line.indexOf(',') - val extension = line.substring(0, index) - val mime = line.substring(index + 1) + if (line.isEmpty() || line.startsWith("#")) return@flatMapTo emptySequence() - extension.removePrefix(".").toLowerCasePreservingASCIIRules() to mime.toContentType() - }.toList() + val (mime, extensions) = line.split(",", limit = 2) + val contentType = mime.toContentType() + extensions.splitToSequence(" ").map { ext -> + ext.toLowerCasePreservingASCIIRules() to contentType + } + } } internal val mimes: List> by lazy { loadMimes() } diff --git a/ktor-http/common/src/io/ktor/http/URLProtocol.kt b/ktor-http/common/src/io/ktor/http/URLProtocol.kt index 5095eb6fd4c..b6f9fc9e141 100644 --- a/ktor-http/common/src/io/ktor/http/URLProtocol.kt +++ b/ktor-http/common/src/io/ktor/http/URLProtocol.kt @@ -5,13 +5,15 @@ package io.ktor.http import io.ktor.util.* +import io.ktor.utils.io.* /** * Represents URL protocol * @property name of protocol (schema) * @property defaultPort default port for protocol or `-1` if not known */ -public data class URLProtocol(val name: String, val defaultPort: Int) { +@OptIn(InternalAPI::class) +public data class URLProtocol(val name: String, val defaultPort: Int) : JvmSerializable { init { require(name.all { it.isLowerCase() }) { "All characters should be lower case" } } diff --git a/ktor-http/common/src/io/ktor/http/Url.kt b/ktor-http/common/src/io/ktor/http/Url.kt index d50c96d8c4a..8f492789b28 100644 --- a/ktor-http/common/src/io/ktor/http/Url.kt +++ b/ktor-http/common/src/io/ktor/http/Url.kt @@ -2,8 +2,15 @@ * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ +@file:OptIn(InternalAPI::class) + package io.ktor.http +import io.ktor.utils.io.* +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* + /** * Represents an immutable URL * @@ -18,6 +25,7 @@ package io.ktor.http * @property password password part of URL * @property trailingQuery keep trailing question character even if there are no query parameters */ +@Serializable(with = UrlSerializer::class) public class Url internal constructor( protocol: URLProtocol?, public val host: String, @@ -29,7 +37,7 @@ public class Url internal constructor( public val password: String?, public val trailingQuery: Boolean, private val urlString: String -) { +) : JvmSerializable { init { require(specifiedPort in 0..65535) { "Port must be between 0 and 65535, or $DEFAULT_PORT if not set. Provided: $specifiedPort" @@ -222,6 +230,8 @@ public class Url internal constructor( return urlString.hashCode() } + private fun writeReplace(): Any = JvmSerializerReplacement(UrlJvmSerializer, this) + public companion object } @@ -254,3 +264,23 @@ internal val Url.encodedUserAndPassword: String get() = buildString { appendUserAndPassword(encodedUser, encodedPassword) } + +public object UrlSerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("io.ktor.http.Url", PrimitiveKind.STRING) + + override fun deserialize(decoder: Decoder): Url = + Url(decoder.decodeString()) + + override fun serialize(encoder: Encoder, value: Url) { + encoder.encodeString(value.toString()) + } +} + +internal object UrlJvmSerializer : JvmSerializer { + override fun jvmSerialize(value: Url): ByteArray = + value.toString().encodeToByteArray() + + override fun jvmDeserialize(value: ByteArray): Url = + Url(value.decodeToString()) +} diff --git a/ktor-http/common/test/io/ktor/tests/http/ContentTypeLookupTest.kt b/ktor-http/common/test/io/ktor/tests/http/ContentTypeLookupTest.kt index 7a26a16f01e..dece101f2b9 100644 --- a/ktor-http/common/test/io/ktor/tests/http/ContentTypeLookupTest.kt +++ b/ktor-http/common/test/io/ktor/tests/http/ContentTypeLookupTest.kt @@ -24,6 +24,59 @@ class ContentTypeLookupTest { ), ContentType.fromFileExtension(".rpm") ) + + assertEquals( + listOf( + ContentType.parse("application/macbinary"), + ContentType.parse("application/mac-binary"), + ContentType.parse("application/octet-stream"), + ContentType.parse("application/x-binary"), + ContentType.parse("application/x-macbinary") + ), + ContentType.fromFileExtension(".bin") + ) + + assertEquals( + listOf( + ContentType.parse("application/zip"), + ContentType.parse("application/x-compressed"), + ContentType.parse("application/x-zip-compressed"), + ContentType.parse("multipart/x-zip") + ), + ContentType.fromFileExtension(".zip") + ) + + assertEquals( + listOf( + ContentType.parse("video/mpeg"), + ContentType.parse("audio/mpeg") + ), + ContentType.fromFileExtension(".mpg") + ) + + assertEquals( + listOf( + ContentType.parse("video/mp4"), + ContentType.parse("application/mp4") + ), + ContentType.fromFileExtension(".mp4") + ) + + assertEquals( + listOf( + ContentType.parse("video/x-matroska"), + ContentType.parse("audio/x-matroska"), + ), + ContentType.fromFileExtension(".mkv") + ) + + assertEquals( + listOf( + ContentType.parse("text/javascript"), + ContentType.parse("application/javascript"), + ), + ContentType.fromFileExtension(".js") + ) } @Test diff --git a/ktor-http/common/test/io/ktor/tests/http/MimesTest.kt b/ktor-http/common/test/io/ktor/tests/http/MimesTest.kt new file mode 100644 index 00000000000..af9c9f4a989 --- /dev/null +++ b/ktor-http/common/test/io/ktor/tests/http/MimesTest.kt @@ -0,0 +1,32 @@ +/* + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + +package io.ktor.tests.http + +import io.ktor.http.* +import kotlin.test.* + +class MimesTest { + + @Test + fun testMimeWithMultipleExtensions() { + val textPlain = "text/plain".toContentType() + val textMime = "text" to textPlain + val txtMime = "txt" to textPlain + assertTrue(mimes.contains(textMime)) + assertTrue(mimes.contains(txtMime)) + } + + @Test + fun testMimeWithSingleExtension() { + val acad = "application/acad".toContentType() + val dwgMime = "dwg" to acad + assertTrue(mimes.contains(dwgMime)) + } + + @Test + fun testMimesSizeMatchesPreallocatedListSize() { + assertEquals(INITIAL_MIMES_LIST_SIZE, mimes.size) + } +} diff --git a/ktor-http/jvm/test/io/ktor/tests/http/SerializableTest.kt b/ktor-http/jvm/test/io/ktor/tests/http/SerializableTest.kt new file mode 100644 index 00000000000..e3df54915e2 --- /dev/null +++ b/ktor-http/jvm/test/io/ktor/tests/http/SerializableTest.kt @@ -0,0 +1,22 @@ +// ktlint-disable filename +/* + * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + +package io.ktor.tests.http + +import io.ktor.http.* +import io.ktor.junit.* +import kotlin.test.* + +class SerializableTest { + @Test + fun urlTest() { + assertSerializable(Url("https://localhost/path?key=value#fragment")) + } + + @Test + fun cookieTest() { + assertSerializable(Cookie("key", "value")) + } +} diff --git a/ktor-http/ktor-http-cio/api/ktor-http-cio.api b/ktor-http/ktor-http-cio/api/ktor-http-cio.api index be316981f41..d322a02cec2 100644 --- a/ktor-http/ktor-http-cio/api/ktor-http-cio.api +++ b/ktor-http/ktor-http-cio/api/ktor-http-cio.api @@ -155,3 +155,7 @@ public final class io/ktor/http/cio/internals/MutableRange { public fun toString ()Ljava/lang/String; } +public final class io/ktor/http/cio/internals/UnsupportedMediaTypeExceptionCIO : java/io/IOException { + public fun (Ljava/lang/String;)V +} + diff --git a/ktor-http/ktor-http-cio/api/ktor-http-cio.klib.api b/ktor-http/ktor-http-cio/api/ktor-http-cio.klib.api index b9a6c9df8b6..39891106013 100644 --- a/ktor-http/ktor-http-cio/api/ktor-http-cio.klib.api +++ b/ktor-http/ktor-http-cio/api/ktor-http-cio.klib.api @@ -27,6 +27,10 @@ final class io.ktor.http.cio.internals/MutableRange { // io.ktor.http.cio.intern final fun toString(): kotlin/String // io.ktor.http.cio.internals/MutableRange.toString|toString(){}[0] } +final class io.ktor.http.cio.internals/UnsupportedMediaTypeExceptionCIO : kotlinx.io/IOException { // io.ktor.http.cio.internals/UnsupportedMediaTypeExceptionCIO|null[0] + constructor (kotlin/String) // io.ktor.http.cio.internals/UnsupportedMediaTypeExceptionCIO.|(kotlin.String){}[0] +} + final class io.ktor.http.cio/CIOHeaders : io.ktor.http/Headers { // io.ktor.http.cio/CIOHeaders|null[0] constructor (io.ktor.http.cio/HttpHeadersMap) // io.ktor.http.cio/CIOHeaders.|(io.ktor.http.cio.HttpHeadersMap){}[0] @@ -40,6 +44,15 @@ final class io.ktor.http.cio/CIOHeaders : io.ktor.http/Headers { // io.ktor.http final fun names(): kotlin.collections/Set // io.ktor.http.cio/CIOHeaders.names|names(){}[0] } +final class io.ktor.http.cio/CIOMultipartDataBase : io.ktor.http.content/MultiPartData, kotlinx.coroutines/CoroutineScope { // io.ktor.http.cio/CIOMultipartDataBase|null[0] + constructor (kotlin.coroutines/CoroutineContext, io.ktor.utils.io/ByteReadChannel, kotlin/CharSequence, kotlin/Long?, kotlin/Long = ...) // io.ktor.http.cio/CIOMultipartDataBase.|(kotlin.coroutines.CoroutineContext;io.ktor.utils.io.ByteReadChannel;kotlin.CharSequence;kotlin.Long?;kotlin.Long){}[0] + + final val coroutineContext // io.ktor.http.cio/CIOMultipartDataBase.coroutineContext|{}coroutineContext[0] + final fun (): kotlin.coroutines/CoroutineContext // io.ktor.http.cio/CIOMultipartDataBase.coroutineContext.|(){}[0] + + final suspend fun readPart(): io.ktor.http.content/PartData? // io.ktor.http.cio/CIOMultipartDataBase.readPart|readPart(){}[0] +} + final class io.ktor.http.cio/ConnectionOptions { // io.ktor.http.cio/ConnectionOptions|null[0] constructor (kotlin/Boolean = ..., kotlin/Boolean = ..., kotlin/Boolean = ..., kotlin.collections/List = ...) // io.ktor.http.cio/ConnectionOptions.|(kotlin.Boolean;kotlin.Boolean;kotlin.Boolean;kotlin.collections.List){}[0] @@ -117,9 +130,44 @@ final class io.ktor.http.cio/Response : io.ktor.http.cio/HttpMessage { // io.kto final fun (): kotlin/CharSequence // io.ktor.http.cio/Response.version.|(){}[0] } +sealed class io.ktor.http.cio/MultipartEvent { // io.ktor.http.cio/MultipartEvent|null[0] + abstract fun release() // io.ktor.http.cio/MultipartEvent.release|release(){}[0] + + final class Epilogue : io.ktor.http.cio/MultipartEvent { // io.ktor.http.cio/MultipartEvent.Epilogue|null[0] + constructor (kotlinx.io/Source) // io.ktor.http.cio/MultipartEvent.Epilogue.|(kotlinx.io.Source){}[0] + + final val body // io.ktor.http.cio/MultipartEvent.Epilogue.body|{}body[0] + final fun (): kotlinx.io/Source // io.ktor.http.cio/MultipartEvent.Epilogue.body.|(){}[0] + + final fun release() // io.ktor.http.cio/MultipartEvent.Epilogue.release|release(){}[0] + } + + final class MultipartPart : io.ktor.http.cio/MultipartEvent { // io.ktor.http.cio/MultipartEvent.MultipartPart|null[0] + constructor (kotlinx.coroutines/Deferred, io.ktor.utils.io/ByteReadChannel) // io.ktor.http.cio/MultipartEvent.MultipartPart.|(kotlinx.coroutines.Deferred;io.ktor.utils.io.ByteReadChannel){}[0] + + final val body // io.ktor.http.cio/MultipartEvent.MultipartPart.body|{}body[0] + final fun (): io.ktor.utils.io/ByteReadChannel // io.ktor.http.cio/MultipartEvent.MultipartPart.body.|(){}[0] + final val headers // io.ktor.http.cio/MultipartEvent.MultipartPart.headers|{}headers[0] + final fun (): kotlinx.coroutines/Deferred // io.ktor.http.cio/MultipartEvent.MultipartPart.headers.|(){}[0] + + final fun release() // io.ktor.http.cio/MultipartEvent.MultipartPart.release|release(){}[0] + } + + final class Preamble : io.ktor.http.cio/MultipartEvent { // io.ktor.http.cio/MultipartEvent.Preamble|null[0] + constructor (kotlinx.io/Source) // io.ktor.http.cio/MultipartEvent.Preamble.|(kotlinx.io.Source){}[0] + + final val body // io.ktor.http.cio/MultipartEvent.Preamble.body|{}body[0] + final fun (): kotlinx.io/Source // io.ktor.http.cio/MultipartEvent.Preamble.body.|(){}[0] + + final fun release() // io.ktor.http.cio/MultipartEvent.Preamble.release|release(){}[0] + } +} + final fun (kotlin/CharSequence).io.ktor.http.cio.internals/parseDecLong(): kotlin/Long // io.ktor.http.cio.internals/parseDecLong|parseDecLong@kotlin.CharSequence(){}[0] final fun (kotlinx.coroutines/CoroutineScope).io.ktor.http.cio/decodeChunked(io.ktor.utils.io/ByteReadChannel): io.ktor.utils.io/WriterJob // io.ktor.http.cio/decodeChunked|decodeChunked@kotlinx.coroutines.CoroutineScope(io.ktor.utils.io.ByteReadChannel){}[0] final fun (kotlinx.coroutines/CoroutineScope).io.ktor.http.cio/decodeChunked(io.ktor.utils.io/ByteReadChannel, kotlin/Long): io.ktor.utils.io/WriterJob // io.ktor.http.cio/decodeChunked|decodeChunked@kotlinx.coroutines.CoroutineScope(io.ktor.utils.io.ByteReadChannel;kotlin.Long){}[0] +final fun (kotlinx.coroutines/CoroutineScope).io.ktor.http.cio/parseMultipart(io.ktor.utils.io/ByteReadChannel, io.ktor.http.cio/HttpHeadersMap, kotlin/Long = ...): kotlinx.coroutines.channels/ReceiveChannel // io.ktor.http.cio/parseMultipart|parseMultipart@kotlinx.coroutines.CoroutineScope(io.ktor.utils.io.ByteReadChannel;io.ktor.http.cio.HttpHeadersMap;kotlin.Long){}[0] +final fun (kotlinx.coroutines/CoroutineScope).io.ktor.http.cio/parseMultipart(io.ktor.utils.io/ByteReadChannel, kotlin/CharSequence, kotlin/Long?, kotlin/Long = ...): kotlinx.coroutines.channels/ReceiveChannel // io.ktor.http.cio/parseMultipart|parseMultipart@kotlinx.coroutines.CoroutineScope(io.ktor.utils.io.ByteReadChannel;kotlin.CharSequence;kotlin.Long?;kotlin.Long){}[0] final fun io.ktor.http.cio/encodeChunked(io.ktor.utils.io/ByteWriteChannel, kotlin.coroutines/CoroutineContext): io.ktor.utils.io/ReaderJob // io.ktor.http.cio/encodeChunked|encodeChunked(io.ktor.utils.io.ByteWriteChannel;kotlin.coroutines.CoroutineContext){}[0] final fun io.ktor.http.cio/expectHttpBody(io.ktor.http.cio/Request): kotlin/Boolean // io.ktor.http.cio/expectHttpBody|expectHttpBody(io.ktor.http.cio.Request){}[0] final fun io.ktor.http.cio/expectHttpBody(io.ktor.http/HttpMethod, kotlin/Long, kotlin/CharSequence?, io.ktor.http.cio/ConnectionOptions?, kotlin/CharSequence?): kotlin/Boolean // io.ktor.http.cio/expectHttpBody|expectHttpBody(io.ktor.http.HttpMethod;kotlin.Long;kotlin.CharSequence?;io.ktor.http.cio.ConnectionOptions?;kotlin.CharSequence?){}[0] diff --git a/ktor-http/ktor-http-cio/jvm/src/io/ktor/http/cio/CIOMultipartDataBase.kt b/ktor-http/ktor-http-cio/common/src/io/ktor/http/cio/CIOMultipartDataBase.kt similarity index 88% rename from ktor-http/ktor-http-cio/jvm/src/io/ktor/http/cio/CIOMultipartDataBase.kt rename to ktor-http/ktor-http-cio/common/src/io/ktor/http/cio/CIOMultipartDataBase.kt index 0003a26548a..65c45647029 100644 --- a/ktor-http/ktor-http-cio/jvm/src/io/ktor/http/cio/CIOMultipartDataBase.kt +++ b/ktor-http/ktor-http-cio/common/src/io/ktor/http/cio/CIOMultipartDataBase.kt @@ -49,7 +49,7 @@ public class CIOMultipartDataBase( val event = events.receive() eventToData(event)?.let { return it } } - } catch (t: ClosedReceiveChannelException) { + } catch (_: ClosedReceiveChannelException) { return null } } @@ -77,13 +77,7 @@ public class CIOMultipartDataBase( val body = part.body if (filename == null) { - val packet = body.readRemaining() // formFieldLimit.toLong()) -// if (!body.exhausted()) { -// val cause = IllegalStateException("Form field size limit exceeded: $formFieldLimit") -// body.cancel(cause) -// throw cause -// } - + val packet = body.readRemaining() packet.use { return PartData.FormItem(it.readText(), { part.release() }, CIOHeaders(headers)) } diff --git a/ktor-http/ktor-http-cio/jvm/src/io/ktor/http/cio/Multipart.kt b/ktor-http/ktor-http-cio/common/src/io/ktor/http/cio/Multipart.kt similarity index 56% rename from ktor-http/ktor-http-cio/jvm/src/io/ktor/http/cio/Multipart.kt rename to ktor-http/ktor-http-cio/common/src/io/ktor/http/cio/Multipart.kt index 231b85cf487..8f98c8674fc 100644 --- a/ktor-http/ktor-http-cio/jvm/src/io/ktor/http/cio/Multipart.kt +++ b/ktor-http/ktor-http-cio/common/src/io/ktor/http/cio/Multipart.kt @@ -7,14 +7,16 @@ package io.ktor.http.cio import io.ktor.http.cio.internals.* import io.ktor.utils.io.* import io.ktor.utils.io.core.* -import kotlinx.coroutines.* +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Deferred +import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.ReceiveChannel import kotlinx.coroutines.channels.produce +import kotlinx.io.EOFException import kotlinx.io.IOException import kotlinx.io.Source import kotlinx.io.bytestring.ByteString -import java.io.EOFException -import java.nio.ByteBuffer /** * Represents a multipart content starting event. Every part need to be completely consumed or released via [release] @@ -57,9 +59,8 @@ public sealed class MultipartEvent { headers.getCompleted().release() } } - runBlocking { - body.discard() - } + + body.discardBlocking() } } @@ -76,11 +77,12 @@ public sealed class MultipartEvent { } } +internal expect fun ByteReadChannel.discardBlocking() + /** * Parse a multipart preamble * @return number of bytes copied */ - private suspend fun parsePreambleImpl( boundary: ByteString, input: ByteReadChannel, @@ -134,12 +136,15 @@ private suspend fun ByteReadChannel.skipIfFoundReadCount(prefix: ByteString): Lo /** * Starts a multipart parser coroutine producing multipart events */ +@OptIn(InternalAPI::class) public fun CoroutineScope.parseMultipart( input: ByteReadChannel, headers: HttpHeadersMap, maxPartSize: Long = Long.MAX_VALUE ): ReceiveChannel { - val contentType = headers["Content-Type"] ?: throw IOException("Failed to parse multipart: no Content-Type header") + val contentType = headers["Content-Type"] ?: throw UnsupportedMediaTypeExceptionCIO( + "Failed to parse multipart: no Content-Type header" + ) val contentLength = headers["Content-Length"]?.parseDecLong() return parseMultipart(input, contentType, contentLength, maxPartSize) @@ -148,6 +153,7 @@ public fun CoroutineScope.parseMultipart( /** * Starts a multipart parser coroutine producing multipart events */ +@OptIn(InternalAPI::class) public fun CoroutineScope.parseMultipart( input: ByteReadChannel, contentType: CharSequence, @@ -155,7 +161,9 @@ public fun CoroutineScope.parseMultipart( maxPartSize: Long = Long.MAX_VALUE, ): ReceiveChannel { if (!contentType.startsWith("multipart/", ignoreCase = true)) { - throw IOException("Failed to parse multipart: Content-Type should be multipart/* but it is $contentType") + throw UnsupportedMediaTypeExceptionCIO( + "Failed to parse multipart: Content-Type should be multipart/* but it is $contentType" + ) } val boundaryByteBuffer = parseBoundaryInternal(contentType) val boundaryBytes = ByteString(boundaryByteBuffer) @@ -166,74 +174,73 @@ public fun CoroutineScope.parseMultipart( private val CrLf = ByteString("\r\n".toByteArray()) -@OptIn(ExperimentalCoroutinesApi::class, InternalAPI::class) +@OptIn(ExperimentalCoroutinesApi::class) private fun CoroutineScope.parseMultipart( boundaryPrefixed: ByteString, input: ByteReadChannel, totalLength: Long?, maxPartSize: Long -): ReceiveChannel = - produce { - val countedInput = input.counted() - val readBeforeParse = countedInput.totalBytesRead - val firstBoundary = boundaryPrefixed.substring(PrefixString.size) - - val preambleData = writer { - parsePreambleImpl(firstBoundary, countedInput, channel, 8192) - channel.flushAndClose() - }.channel.readRemaining() - - if (preambleData.remaining > 0L) { - send(MultipartEvent.Preamble(preambleData)) - } - - while (!countedInput.isClosedForRead && !countedInput.skipIfFound(PrefixString)) { - countedInput.skipIfFound(CrLf) - - val body = ByteChannel() - val headers = CompletableDeferred() - val part = MultipartEvent.MultipartPart(headers, body) - send(part) - - var headersMap: HttpHeadersMap? = null - try { - headersMap = parsePartHeadersImpl(countedInput) - if (!headers.complete(headersMap)) { - headersMap.release() - throw kotlin.coroutines.cancellation.CancellationException( - "Multipart processing has been cancelled" - ) - } - parsePartBodyImpl(boundaryPrefixed, countedInput, body, headersMap, maxPartSize) - body.close() - } catch (cause: Throwable) { - if (headers.completeExceptionally(cause)) { - headersMap?.release() - } - body.close(cause) - throw cause - } - } +): ReceiveChannel = produce { + val countedInput = input.counted() + val readBeforeParse = countedInput.totalBytesRead + val firstBoundary = boundaryPrefixed.substring(PrefixString.size) + + val preambleData = writer { + parsePreambleImpl(firstBoundary, countedInput, channel, 8193) + channel.flushAndClose() + }.channel.readRemaining() + + if (preambleData.remaining > 0L) { + send(MultipartEvent.Preamble(preambleData)) + } - // Can be followed by two carriage returns - countedInput.skipIfFound(CrLf) + while (!countedInput.isClosedForRead && !countedInput.skipIfFound(PrefixString)) { countedInput.skipIfFound(CrLf) - if (totalLength != null) { - val consumedExceptEpilogue = countedInput.totalBytesRead - readBeforeParse - val size = totalLength - consumedExceptEpilogue - if (size > Int.MAX_VALUE) throw IOException("Failed to parse multipart: prologue is too long") - if (size > 0) { - send(MultipartEvent.Epilogue(countedInput.readPacket(size.toInt()))) + val body = ByteChannel() + val headers = CompletableDeferred() + val part = MultipartEvent.MultipartPart(headers, body) + send(part) + + var headersMap: HttpHeadersMap? = null + try { + headersMap = parsePartHeadersImpl(countedInput) + if (!headers.complete(headersMap)) { + headersMap.release() + throw kotlin.coroutines.cancellation.CancellationException( + "Multipart processing has been cancelled" + ) } - } else { - val epilogueContent = countedInput.readRemaining() - if (!epilogueContent.exhausted()) { - send(MultipartEvent.Epilogue(epilogueContent)) + parsePartBodyImpl(boundaryPrefixed, countedInput, body, headersMap, maxPartSize) + body.close() + } catch (cause: Throwable) { + if (headers.completeExceptionally(cause)) { + headersMap?.release() } + body.close(cause) + throw cause } } + // Can be followed by two carriage returns + countedInput.skipIfFound(CrLf) + countedInput.skipIfFound(CrLf) + + if (totalLength != null) { + val consumedExceptEpilogue = countedInput.totalBytesRead - readBeforeParse + val size = totalLength - consumedExceptEpilogue + if (size > Int.MAX_VALUE) throw IOException("Failed to parse multipart: prologue is too long") + if (size > 0) { + send(MultipartEvent.Epilogue(countedInput.readPacket(size.toInt()))) + } + } else { + val epilogueContent = countedInput.readRemaining() + if (!epilogueContent.exhausted()) { + send(MultipartEvent.Epilogue(epilogueContent)) + } + } +} + private const val PrefixChar = '-'.code.toByte() private val PrefixString = ByteString(PrefixChar, PrefixChar) @@ -298,7 +305,7 @@ private fun findBoundary(contentType: CharSequence): Int { * Parse multipart boundary encoded in [contentType] header value * @return a buffer containing CRLF, prefix '--' and boundary bytes */ -internal fun parseBoundaryInternal(contentType: CharSequence): ByteBuffer { +internal fun parseBoundaryInternal(contentType: CharSequence): ByteArray { val boundaryParameter = findBoundary(contentType) if (boundaryParameter == -1) { @@ -306,11 +313,22 @@ internal fun parseBoundaryInternal(contentType: CharSequence): ByteBuffer { } val boundaryStart = boundaryParameter + 9 - val boundaryBytes: ByteBuffer = ByteBuffer.allocate(74) - boundaryBytes.put(0x0d) - boundaryBytes.put(0x0a) - boundaryBytes.put(PrefixChar) - boundaryBytes.put(PrefixChar) + val boundaryBytes = ByteArray(74) + var position = 0 + + fun put(value: Byte) { + if (position >= boundaryBytes.size) { + throw IOException( + "Failed to parse multipart: boundary shouldn't be longer than 70 characters" + ) + } + boundaryBytes[position++] = value + } + + put(0x0d) + put(0x0a) + put(PrefixChar) + put(PrefixChar) var state = 0 // 0 - skipping spaces, 1 - unquoted characters, 2 - quoted no escape, 3 - quoted after escape @@ -337,154 +355,39 @@ internal fun parseBoundaryInternal(contentType: CharSequence): ByteBuffer { } else -> { state = 1 - boundaryBytes.put(v.toByte()) + put(v.toByte()) } } } 1 -> { // non-quoted string if (ch == ' ' || ch == ',' || ch == ';') { // space, comma or semicolon (;) break@loop - } else if (boundaryBytes.hasRemaining()) { - boundaryBytes.put(v.toByte()) } else { - // RFC 2046, sec 5.1.1 - throw IOException("Failed to parse multipart: boundary shouldn't be longer than 70 characters") + put(v.toByte()) } } + 2 -> { if (ch == '\\') { state = 3 } else if (ch == '"') { break@loop - } else if (boundaryBytes.hasRemaining()) { - boundaryBytes.put(v.toByte()) } else { - // RFC 2046, sec 5.1.1 - throw IOException("Failed to parse multipart: boundary shouldn't be longer than 70 characters") + put(v.toByte()) } } 3 -> { - if (boundaryBytes.hasRemaining()) { - boundaryBytes.put(v.toByte()) - state = 2 - } else { - // RFC 2046, sec 5.1.1 - throw IOException("Failed to parse multipart: boundary shouldn't be longer than 70 characters") - } + put(v.toByte()) + state = 2 } } } - boundaryBytes.flip() - - if (boundaryBytes.remaining() == 4) { + if (position == 4) { throw IOException("Empty multipart boundary is not allowed") } - return boundaryBytes -} - -/** - * Tries to skip the specified [delimiter] or fails if encounters bytes differs from the required. - * @return `true` if the delimiter was found and skipped or `false` when EOF. - */ -internal suspend fun ByteReadChannel.skipDelimiterOrEof(delimiter: ByteBuffer): Boolean { - require(delimiter.hasRemaining()) - require(delimiter.remaining() <= DEFAULT_BUFFER_SIZE) { - "Delimiter of ${delimiter.remaining()} bytes is too long: at most $DEFAULT_BUFFER_SIZE bytes could be checked" - } - - var found = false - - lookAhead { - found = tryEnsureDelimiter(delimiter) == delimiter.remaining() - } - - if (found) { - return true - } - - return trySkipDelimiterSuspend(delimiter) -} - -private suspend fun ByteReadChannel.trySkipDelimiterSuspend(delimiter: ByteBuffer): Boolean { - var result = true - - lookAheadSuspend { - if (!awaitAtLeast(delimiter.remaining()) && !awaitAtLeast(1)) { - result = false - return@lookAheadSuspend - } - if (tryEnsureDelimiter(delimiter) != delimiter.remaining()) throw IOException("Broken delimiter occurred") - } - - return result -} - -private fun LookAheadSession.tryEnsureDelimiter(delimiter: ByteBuffer): Int { - val found = startsWithDelimiter(delimiter) - if (found == -1) throw IOException("Failed to skip delimiter: actual bytes differ from delimiter bytes") - if (found < delimiter.remaining()) return found - - consumed(delimiter.remaining()) - return delimiter.remaining() -} - -@Suppress("LoopToCallChain") -private fun ByteBuffer.startsWith( - prefix: ByteBuffer, - prefixSkip: Int = 0 -): Boolean { - val size = minOf(remaining(), prefix.remaining() - prefixSkip) - if (size <= 0) return false - - val position = position() - val prefixPosition = prefix.position() + prefixSkip - - for (i in 0 until size) { - if (get(position + i) != prefix.get(prefixPosition + i)) return false - } - - return true -} - -/** - * @return Number of bytes of the delimiter found (possibly 0 if no bytes available yet) or -1 if it doesn't start - */ -private fun LookAheadSession.startsWithDelimiter(delimiter: ByteBuffer): Int { - val buffer = request(0, 1) ?: return 0 - val index = buffer.indexOfPartial(delimiter) - if (index != 0) return -1 - - val found = minOf(buffer.remaining() - index, delimiter.remaining()) - val notKnown = delimiter.remaining() - found - - if (notKnown > 0) { - val next = request(index + found, notKnown) ?: return found - if (!next.startsWith(delimiter, found)) return -1 - } - - return delimiter.remaining() -} - -@Suppress("LoopToCallChain") -private fun ByteBuffer.indexOfPartial(sub: ByteBuffer): Int { - val subPosition = sub.position() - val subSize = sub.remaining() - val first = sub[subPosition] - val limit = limit() - - outer@ for (idx in position() until limit) { - if (get(idx) == first) { - for (j in 1 until subSize) { - if (idx + j == limit) break - if (get(idx + j) != sub.get(subPosition + j)) continue@outer - } - return idx - position() - } - } - - return -1 + return boundaryBytes.copyOfRange(0, position) } private fun throwLimitExceeded(actual: Long, limit: Long): Nothing = diff --git a/ktor-http/ktor-http-cio/common/src/io/ktor/http/cio/RequestResponseBuilderCommon.kt b/ktor-http/ktor-http-cio/common/src/io/ktor/http/cio/RequestResponseBuilderCommon.kt index 98d7c72e043..082354377aa 100644 --- a/ktor-http/ktor-http-cio/common/src/io/ktor/http/cio/RequestResponseBuilderCommon.kt +++ b/ktor-http/ktor-http-cio/common/src/io/ktor/http/cio/RequestResponseBuilderCommon.kt @@ -5,7 +5,6 @@ package io.ktor.http.cio import io.ktor.http.* -import io.ktor.utils.io.core.* import kotlinx.io.* /** @@ -53,7 +52,3 @@ public expect class RequestResponseBuilder() { */ public fun release() } - -private const val SP: Byte = 0x20 -private const val CR: Byte = 0x0d -private const val LF: Byte = 0x0a diff --git a/ktor-http/ktor-http-cio/common/src/io/ktor/http/cio/internals/Errors.kt b/ktor-http/ktor-http-cio/common/src/io/ktor/http/cio/internals/Errors.kt new file mode 100644 index 00000000000..cb9fa810822 --- /dev/null +++ b/ktor-http/ktor-http-cio/common/src/io/ktor/http/cio/internals/Errors.kt @@ -0,0 +1,11 @@ +/* + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + +package io.ktor.http.cio.internals + +import io.ktor.utils.io.* +import kotlinx.io.IOException + +@InternalAPI +public class UnsupportedMediaTypeExceptionCIO(message: String) : IOException(message) diff --git a/ktor-http/ktor-http-cio/jsAndWasmShared/src/io/ktor/http/cio/MultipartJsAndWasm.kt b/ktor-http/ktor-http-cio/jsAndWasmShared/src/io/ktor/http/cio/MultipartJsAndWasm.kt new file mode 100644 index 00000000000..2fb66098744 --- /dev/null +++ b/ktor-http/ktor-http-cio/jsAndWasmShared/src/io/ktor/http/cio/MultipartJsAndWasm.kt @@ -0,0 +1,11 @@ +package io.ktor.http.cio + +import io.ktor.utils.io.* + +/* + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + +internal actual fun ByteReadChannel.discardBlocking() { + cancel() +} diff --git a/ktor-http/ktor-http-cio/jvm/test/io/ktor/tests/http/cio/MultipartTest.kt b/ktor-http/ktor-http-cio/jvm/test/io/ktor/tests/http/cio/MultipartTest.kt index ca9372fbbfc..cc539c2cfac 100644 --- a/ktor-http/ktor-http-cio/jvm/test/io/ktor/tests/http/cio/MultipartTest.kt +++ b/ktor-http/ktor-http-cio/jvm/test/io/ktor/tests/http/cio/MultipartTest.kt @@ -432,11 +432,7 @@ class MultipartTest { private fun testBoundary(expectedBoundary: String, headerValue: String) { val boundary = parseBoundaryInternal(headerValue) - val actualBoundary = String( - boundary.array(), - boundary.arrayOffset() + boundary.position(), - boundary.remaining() - ) + val actualBoundary = String(boundary) assertEquals(expectedBoundary, actualBoundary) } diff --git a/ktor-http/ktor-http-cio/jvm/test/io/ktor/tests/http/cio/TrySkipDelimiterTest.kt b/ktor-http/ktor-http-cio/jvm/test/io/ktor/tests/http/cio/TrySkipDelimiterTest.kt deleted file mode 100644 index a2d7ff24930..00000000000 --- a/ktor-http/ktor-http-cio/jvm/test/io/ktor/tests/http/cio/TrySkipDelimiterTest.kt +++ /dev/null @@ -1,153 +0,0 @@ -/* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ - -package io.ktor.tests.http.cio - -import io.ktor.http.cio.* -import io.ktor.utils.io.* -import kotlinx.coroutines.* -import kotlinx.coroutines.test.* -import java.nio.* -import kotlin.test.* - -class TrySkipDelimiterTest { - private val ch = ByteChannel() - - @Test - fun testSmoke(): Unit = runTest { - ch.writeFully(byteArrayOf(1, 2, 3)) - ch.close() - - val delimiter = ByteBuffer.wrap(byteArrayOf(1, 2)) - assertTrue(ch.skipDelimiterOrEof(delimiter)) - assertEquals(3, ch.readByte()) - assertTrue(ch.isClosedForRead) - } - - @OptIn(InternalAPI::class) - @Test - fun testSmokeWithOffsetShift(): Unit = runTest { - ch.writeFully(byteArrayOf(9, 1, 2, 3)) - ch.close() - - val delimiter = ByteBuffer.wrap(byteArrayOf(1, 2)) - ch.discard(1) - assertTrue(ch.skipDelimiterOrEof(delimiter)) - assertEquals(3, ch.readByte()) - assertTrue(ch.isClosedForRead) - } - - @OptIn(InternalAPI::class) - @Test - fun testEmpty(): Unit = runTest { - ch.close() - - val delimiter = ByteBuffer.wrap(byteArrayOf(1, 2)) - assertFalse(ch.skipDelimiterOrEof(delimiter)) - } - - @OptIn(InternalAPI::class) - @Test - fun testFull(): Unit = runTest { - ch.writeFully(byteArrayOf(1, 2)) - ch.close() - - val delimiter = ByteBuffer.wrap(byteArrayOf(1, 2)) - assertTrue(ch.skipDelimiterOrEof(delimiter)) - assertTrue(ch.isClosedForRead) - } - - @OptIn(InternalAPI::class) - @Test - fun testIncomplete(): Unit = runTest { - ch.writeFully(byteArrayOf(1, 2)) - ch.close() - - val delimiter = ByteBuffer.wrap(byteArrayOf(1, 2, 3)) - assertFails { - ch.skipDelimiterOrEof(delimiter) - } - } - - @OptIn(InternalAPI::class) - @Test - fun testOtherBytes(): Unit = runTest { - ch.writeFully(byteArrayOf(7, 8)) - ch.close() - - val delimiter = ByteBuffer.wrap(byteArrayOf(1, 2)) - - assertFails { - ch.skipDelimiterOrEof(delimiter) - } - - // content shouldn't be consumed - assertEquals(7, ch.readByte()) - assertEquals(8, ch.readByte()) - assertTrue(ch.isClosedForRead) - } - - @Test - fun testTimeSplit(): Unit = runTest { - val writer = launch(CoroutineName("writer"), start = CoroutineStart.LAZY) { - ch.writeByte(2) - ch.close() - } - - ch.writeByte(1) - ch.flush() - writer.start() - - val delimiter = ByteBuffer.wrap(byteArrayOf(1, 2)) - - assertTrue(ch.skipDelimiterOrEof(delimiter)) - - assertTrue(ch.isClosedForRead) - } - - @Test - fun testTimeSplitNonClosed(): Unit = runTest { - val writer = launch(CoroutineName("writer"), start = CoroutineStart.LAZY) { - ch.writeByte(2) - ch.flush() - } - - ch.writeByte(1) - ch.flush() - writer.start() - - val delimiter = ByteBuffer.wrap(byteArrayOf(1, 2)) - - assertTrue(ch.skipDelimiterOrEof(delimiter)) - assertFalse(ch.isClosedForRead) - ch.cancel() - } - - @Test - fun testTimeSplitWrongBytes(): Unit = runTest { - val writer = launch(CoroutineName("writer"), start = CoroutineStart.LAZY) { - ch.writeByte(33) - ch.flush() - } - - ch.writeByte(1) - ch.flush() - writer.start() - - val delimiter = ByteBuffer.wrap(byteArrayOf(1, 2)) - - assertFails { - ch.skipDelimiterOrEof(delimiter) - } - - assertEquals(2, ch.availableForRead) - } - - @Test - fun testSkipTooLongDelimiter(): Unit = runTest { - assertFails { - ch.skipDelimiterOrEof(ByteBuffer.allocate(DEFAULT_BUFFER_SIZE * 2)) - } - } -} diff --git a/ktor-http/ktor-http-cio/jvmAndPosix/src/MultipartJvmAndPosix.kt b/ktor-http/ktor-http-cio/jvmAndPosix/src/MultipartJvmAndPosix.kt new file mode 100644 index 00000000000..b3f276a0f98 --- /dev/null +++ b/ktor-http/ktor-http-cio/jvmAndPosix/src/MultipartJvmAndPosix.kt @@ -0,0 +1,14 @@ +package io.ktor.http.cio + +import io.ktor.utils.io.* +import kotlinx.coroutines.* + +/* + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + +internal actual fun ByteReadChannel.discardBlocking() { + runBlocking { + discard() + } +} diff --git a/ktor-io/api/ktor-io.api b/ktor-io/api/ktor-io.api index d7bdcc9a7ae..9adc665a32b 100644 --- a/ktor-io/api/ktor-io.api +++ b/ktor-io/api/ktor-io.api @@ -173,6 +173,10 @@ public abstract interface class io/ktor/utils/io/ChannelJob { public abstract fun getJob ()Lkotlinx/coroutines/Job; } +public final class io/ktor/utils/io/CloseHookByteWriteChannelKt { + public static final fun onClose (Lio/ktor/utils/io/ByteWriteChannel;Lkotlin/jvm/functions/Function1;)Lio/ktor/utils/io/ByteWriteChannel; +} + public final class io/ktor/utils/io/ConcurrentIOException : java/lang/IllegalStateException { public fun (Ljava/lang/String;Ljava/lang/Throwable;)V public synthetic fun (Ljava/lang/String;Ljava/lang/Throwable;ILkotlin/jvm/internal/DefaultConstructorMarker;)V @@ -210,6 +214,17 @@ public final class io/ktor/utils/io/CountedByteWriteChannelKt { public static final fun counted (Lio/ktor/utils/io/ByteWriteChannel;)Lio/ktor/utils/io/CountedByteWriteChannel; } +public final class io/ktor/utils/io/DefaultJvmSerializerReplacement : java/io/Externalizable { + public static final field Companion Lio/ktor/utils/io/DefaultJvmSerializerReplacement$Companion; + public fun ()V + public fun (Lio/ktor/utils/io/JvmSerializer;Ljava/lang/Object;)V + public fun readExternal (Ljava/io/ObjectInput;)V + public fun writeExternal (Ljava/io/ObjectOutput;)V +} + +public final class io/ktor/utils/io/DefaultJvmSerializerReplacement$Companion { +} + public final class io/ktor/utils/io/DeprecationKt { public static final fun readText (Lkotlinx/io/Source;)Ljava/lang/String; public static final fun release (Lkotlinx/io/Sink;)V @@ -218,6 +233,15 @@ public final class io/ktor/utils/io/DeprecationKt { public abstract interface annotation class io/ktor/utils/io/InternalAPI : java/lang/annotation/Annotation { } +public final class io/ktor/utils/io/JvmSerializable_jvmKt { + public static final fun JvmSerializerReplacement (Lio/ktor/utils/io/JvmSerializer;Ljava/lang/Object;)Ljava/lang/Object; +} + +public abstract interface class io/ktor/utils/io/JvmSerializer : java/io/Serializable { + public abstract fun jvmDeserialize ([B)Ljava/lang/Object; + public abstract fun jvmSerialize (Ljava/lang/Object;)[B +} + public abstract interface annotation class io/ktor/utils/io/KtorDsl : java/lang/annotation/Annotation { } diff --git a/ktor-io/api/ktor-io.klib.api b/ktor-io/api/ktor-io.klib.api index d7e3c725c70..a26bd58db5c 100644 --- a/ktor-io/api/ktor-io.klib.api +++ b/ktor-io/api/ktor-io.klib.api @@ -53,7 +53,12 @@ abstract interface <#A: kotlin/Any> io.ktor.utils.io.pool/ObjectPool : kotlin/Au open fun close() // io.ktor.utils.io.pool/ObjectPool.close|close(){}[0] } -abstract interface io.ktor.utils.io.core/Closeable { // io.ktor.utils.io.core/Closeable|null[0] +abstract interface <#A: kotlin/Any?> io.ktor.utils.io/JvmSerializer : io.ktor.utils.io/JvmSerializable { // io.ktor.utils.io/JvmSerializer|null[0] + abstract fun jvmDeserialize(kotlin/ByteArray): #A // io.ktor.utils.io/JvmSerializer.jvmDeserialize|jvmDeserialize(kotlin.ByteArray){}[0] + abstract fun jvmSerialize(#A): kotlin/ByteArray // io.ktor.utils.io/JvmSerializer.jvmSerialize|jvmSerialize(1:0){}[0] +} + +abstract interface io.ktor.utils.io.core/Closeable : kotlin/AutoCloseable { // io.ktor.utils.io.core/Closeable|null[0] abstract fun close() // io.ktor.utils.io.core/Closeable.close|close(){}[0] } @@ -97,6 +102,8 @@ abstract interface io.ktor.utils.io/ChannelJob { // io.ktor.utils.io/ChannelJob| abstract fun (): kotlinx.coroutines/Job // io.ktor.utils.io/ChannelJob.job.|(){}[0] } +abstract interface io.ktor.utils.io/JvmSerializable // io.ktor.utils.io/JvmSerializable|null[0] + abstract class <#A: kotlin/Any> io.ktor.utils.io.pool/DefaultPool : io.ktor.utils.io.pool/ObjectPool<#A> { // io.ktor.utils.io.pool/DefaultPool|null[0] constructor (kotlin/Int) // io.ktor.utils.io.pool/DefaultPool.|(kotlin.Int){}[0] @@ -357,6 +364,7 @@ final fun (io.ktor.utils.io/ByteWriteChannel).io.ktor.utils.io/cancel() // io.kt final fun (io.ktor.utils.io/ByteWriteChannel).io.ktor.utils.io/close() // io.ktor.utils.io/close|close@io.ktor.utils.io.ByteWriteChannel(){}[0] final fun (io.ktor.utils.io/ByteWriteChannel).io.ktor.utils.io/close(kotlin/Throwable?) // io.ktor.utils.io/close|close@io.ktor.utils.io.ByteWriteChannel(kotlin.Throwable?){}[0] final fun (io.ktor.utils.io/ByteWriteChannel).io.ktor.utils.io/counted(): io.ktor.utils.io/CountedByteWriteChannel // io.ktor.utils.io/counted|counted@io.ktor.utils.io.ByteWriteChannel(){}[0] +final fun (io.ktor.utils.io/ByteWriteChannel).io.ktor.utils.io/onClose(kotlin.coroutines/SuspendFunction0): io.ktor.utils.io/ByteWriteChannel // io.ktor.utils.io/onClose|onClose@io.ktor.utils.io.ByteWriteChannel(kotlin.coroutines.SuspendFunction0){}[0] final fun (io.ktor.utils.io/ByteWriteChannel).io.ktor.utils.io/rethrowCloseCauseIfNeeded() // io.ktor.utils.io/rethrowCloseCauseIfNeeded|rethrowCloseCauseIfNeeded@io.ktor.utils.io.ByteWriteChannel(){}[0] final fun (io.ktor.utils.io/ChannelJob).io.ktor.utils.io/cancel() // io.ktor.utils.io/cancel|cancel@io.ktor.utils.io.ChannelJob(){}[0] final fun (io.ktor.utils.io/ChannelJob).io.ktor.utils.io/getCancellationException(): kotlin.coroutines.cancellation/CancellationException // io.ktor.utils.io/getCancellationException|getCancellationException@io.ktor.utils.io.ChannelJob(){}[0] @@ -399,6 +407,7 @@ final fun (kotlinx.io/Source).io.ktor.utils.io.core/readTextExactCharacters(kotl final fun (kotlinx.io/Source).io.ktor.utils.io.core/release() // io.ktor.utils.io.core/release|release@kotlinx.io.Source(){}[0] final fun (kotlinx.io/Source).io.ktor.utils.io.core/takeWhile(kotlin/Function1) // io.ktor.utils.io.core/takeWhile|takeWhile@kotlinx.io.Source(kotlin.Function1){}[0] final fun (kotlinx.io/Source).io.ktor.utils.io/readText(): kotlin/String // io.ktor.utils.io/readText|readText@kotlinx.io.Source(){}[0] +final fun <#A: kotlin/Any> io.ktor.utils.io/JvmSerializerReplacement(io.ktor.utils.io/JvmSerializer<#A>, #A): kotlin/Any // io.ktor.utils.io/JvmSerializerReplacement|JvmSerializerReplacement(io.ktor.utils.io.JvmSerializer<0:0>;0:0){0§}[0] final fun <#A: kotlin/Any?> (kotlinx.io/Sink).io.ktor.utils.io.core/preview(kotlin/Function1): #A // io.ktor.utils.io.core/preview|preview@kotlinx.io.Sink(kotlin.Function1){0§}[0] final fun <#A: kotlin/Any?> (kotlinx.io/Source).io.ktor.utils.io.core/preview(kotlin/Function1): #A // io.ktor.utils.io.core/preview|preview@kotlinx.io.Source(kotlin.Function1){0§}[0] final fun <#A: kotlin/Any?> io.ktor.utils.io.core/withMemory(kotlin/Int, kotlin/Function1): #A // io.ktor.utils.io.core/withMemory|withMemory(kotlin.Int;kotlin.Function1){0§}[0] diff --git a/ktor-io/common/src/io/ktor/utils/io/ByteReadChannelOperations.kt b/ktor-io/common/src/io/ktor/utils/io/ByteReadChannelOperations.kt index eee738d5b1b..d686a372393 100644 --- a/ktor-io/common/src/io/ktor/utils/io/ByteReadChannelOperations.kt +++ b/ktor-io/common/src/io/ktor/utils/io/ByteReadChannelOperations.kt @@ -14,7 +14,6 @@ import kotlinx.io.Buffer import kotlinx.io.bytestring.* import kotlinx.io.unsafe.* import kotlin.coroutines.* -import kotlin.jvm.* import kotlin.math.* @OptIn(InternalAPI::class) @@ -309,7 +308,7 @@ public fun CoroutineScope.reader( } } - return ReaderJob(channel, job) + return ReaderJob(channel.onClose { job.join() }, job) } /** diff --git a/ktor-io/common/src/io/ktor/utils/io/CloseHookByteWriteChannel.kt b/ktor-io/common/src/io/ktor/utils/io/CloseHookByteWriteChannel.kt new file mode 100644 index 00000000000..d5925c7b2db --- /dev/null +++ b/ktor-io/common/src/io/ktor/utils/io/CloseHookByteWriteChannel.kt @@ -0,0 +1,24 @@ +/* + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + +package io.ktor.utils.io + +/** + * Wraps this channel to execute the provided action when closed using `flushAndClose()`. + * + * @param onClose The action to execute when the channel is closed. + * @return A new `ByteWriteChannel` that executes the given action upon closure. + */ +public fun ByteWriteChannel.onClose(onClose: suspend () -> Unit): ByteWriteChannel = + CloseHookByteWriteChannel(this, onClose) + +internal class CloseHookByteWriteChannel( + private val delegate: ByteWriteChannel, + private val onClose: suspend () -> Unit +) : ByteWriteChannel by delegate { + override suspend fun flushAndClose() { + delegate.flushAndClose() + onClose() + } +} diff --git a/ktor-io/common/src/io/ktor/utils/io/JvmSerializable.kt b/ktor-io/common/src/io/ktor/utils/io/JvmSerializable.kt new file mode 100644 index 00000000000..ae6f583e692 --- /dev/null +++ b/ktor-io/common/src/io/ktor/utils/io/JvmSerializable.kt @@ -0,0 +1,20 @@ +/* + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + +package io.ktor.utils.io + +/** Alias for `java.io.Serializable` on JVM. Empty interface otherwise. */ +@InternalAPI +public expect interface JvmSerializable + +@InternalAPI +public interface JvmSerializer : JvmSerializable { + public fun jvmSerialize(value: T): ByteArray + public fun jvmDeserialize(value: ByteArray): T +} + +@InternalAPI +public expect fun JvmSerializerReplacement(serializer: JvmSerializer, value: T): Any + +internal object DummyJvmSimpleSerializerReplacement diff --git a/ktor-io/common/src/io/ktor/utils/io/core/Closeable.kt b/ktor-io/common/src/io/ktor/utils/io/core/Closeable.kt index 90567a0231f..043fab49be2 100644 --- a/ktor-io/common/src/io/ktor/utils/io/core/Closeable.kt +++ b/ktor-io/common/src/io/ktor/utils/io/core/Closeable.kt @@ -4,25 +4,9 @@ package io.ktor.utils.io.core -public expect interface Closeable { - public fun close() -} +import kotlin.use as stdlibUse -public inline fun T.use(block: (T) -> R): R { - var closed = false - try { - return block(this) - } catch (cause: Throwable) { - closed = true - try { - this?.close() - } catch (closeException: Throwable) { - cause.addSuppressed(closeException) - } - throw cause - } finally { - if (!closed) { - this?.close() - } - } -} +public expect interface Closeable : AutoCloseable + +@Deprecated("Use stdlib implementation instead. Remove import of this function", ReplaceWith("stdlibUse(block)")) +public inline fun T.use(block: (T) -> R): R = stdlibUse(block) diff --git a/ktor-io/js/src/io/ktor/utils/io/core/Closeable.js.kt b/ktor-io/js/src/io/ktor/utils/io/core/Closeable.js.kt index 09561abbac7..63ae1eeb0f4 100644 --- a/ktor-io/js/src/io/ktor/utils/io/core/Closeable.js.kt +++ b/ktor-io/js/src/io/ktor/utils/io/core/Closeable.js.kt @@ -4,6 +4,6 @@ package io.ktor.utils.io.core -public actual interface Closeable { - public actual fun close() +public actual interface Closeable : AutoCloseable { + override fun close() } diff --git a/ktor-io/jsAndWasmShared/src/io/ktor/utils/io/JvmSerializable.jsAndWasmShared.kt b/ktor-io/jsAndWasmShared/src/io/ktor/utils/io/JvmSerializable.jsAndWasmShared.kt new file mode 100644 index 00000000000..44454f494a0 --- /dev/null +++ b/ktor-io/jsAndWasmShared/src/io/ktor/utils/io/JvmSerializable.jsAndWasmShared.kt @@ -0,0 +1,12 @@ +/* + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + +package io.ktor.utils.io + +@InternalAPI +public actual interface JvmSerializable + +@InternalAPI +public actual fun JvmSerializerReplacement(serializer: JvmSerializer, value: T): Any = + DummyJvmSimpleSerializerReplacement diff --git a/ktor-io/jvm/src/io/ktor/utils/io/JvmSerializable.jvm.kt b/ktor-io/jvm/src/io/ktor/utils/io/JvmSerializable.jvm.kt new file mode 100644 index 00000000000..608cc65229a --- /dev/null +++ b/ktor-io/jvm/src/io/ktor/utils/io/JvmSerializable.jvm.kt @@ -0,0 +1,42 @@ +/* + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + +package io.ktor.utils.io + +import java.io.* + +@InternalAPI +public actual typealias JvmSerializable = Serializable + +@Suppress("UNCHECKED_CAST") +@InternalAPI +public actual fun JvmSerializerReplacement(serializer: JvmSerializer, value: T): Any = + DefaultJvmSerializerReplacement(serializer, value) + +@OptIn(InternalAPI::class) +@PublishedApi // IMPORTANT: changing the class name would result in serialization incompatibility +internal class DefaultJvmSerializerReplacement( + private var serializer: JvmSerializer?, + private var value: T? +) : Externalizable { + constructor() : this(null, null) + + override fun writeExternal(out: ObjectOutput) { + out.writeObject(serializer) + out.writeObject(serializer!!.jvmSerialize(value!!)) + } + + @Suppress("UNCHECKED_CAST") + override fun readExternal(`in`: ObjectInput) { + serializer = `in`.readObject() as JvmSerializer + value = serializer!!.jvmDeserialize(`in`.readObject() as ByteArray) + } + + private fun readResolve(): Any = + value!! + + companion object { + private const val serialVersionUID: Long = 0L + } +} diff --git a/ktor-io/posix/src/io/ktor/utils/io/JvmSerializable.posix.kt b/ktor-io/posix/src/io/ktor/utils/io/JvmSerializable.posix.kt new file mode 100644 index 00000000000..44454f494a0 --- /dev/null +++ b/ktor-io/posix/src/io/ktor/utils/io/JvmSerializable.posix.kt @@ -0,0 +1,12 @@ +/* + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + +package io.ktor.utils.io + +@InternalAPI +public actual interface JvmSerializable + +@InternalAPI +public actual fun JvmSerializerReplacement(serializer: JvmSerializer, value: T): Any = + DummyJvmSimpleSerializerReplacement diff --git a/ktor-io/posix/src/io/ktor/utils/io/core/Closeable.posix.kt b/ktor-io/posix/src/io/ktor/utils/io/core/Closeable.posix.kt index 09561abbac7..63ae1eeb0f4 100644 --- a/ktor-io/posix/src/io/ktor/utils/io/core/Closeable.posix.kt +++ b/ktor-io/posix/src/io/ktor/utils/io/core/Closeable.posix.kt @@ -4,6 +4,6 @@ package io.ktor.utils.io.core -public actual interface Closeable { - public actual fun close() +public actual interface Closeable : AutoCloseable { + override fun close() } diff --git a/ktor-io/wasmJs/src/io/ktor/utils/io/core/Closeable.wasmJs.kt b/ktor-io/wasmJs/src/io/ktor/utils/io/core/Closeable.wasmJs.kt index 09561abbac7..63ae1eeb0f4 100644 --- a/ktor-io/wasmJs/src/io/ktor/utils/io/core/Closeable.wasmJs.kt +++ b/ktor-io/wasmJs/src/io/ktor/utils/io/core/Closeable.wasmJs.kt @@ -4,6 +4,6 @@ package io.ktor.utils.io.core -public actual interface Closeable { - public actual fun close() +public actual interface Closeable : AutoCloseable { + override fun close() } diff --git a/ktor-network/api/ktor-network.api b/ktor-network/api/ktor-network.api index 13d0d4eb9fd..7fb6a096f8a 100644 --- a/ktor-network/api/ktor-network.api +++ b/ktor-network/api/ktor-network.api @@ -341,7 +341,9 @@ public final class io/ktor/network/sockets/TypeOfService$Companion { public final class io/ktor/network/sockets/UDPSocketBuilder : io/ktor/network/sockets/Configurable { public final fun bind (Lio/ktor/network/sockets/SocketAddress;Lkotlin/jvm/functions/Function1;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; + public final fun bind (Ljava/lang/String;ILkotlin/jvm/functions/Function1;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public static synthetic fun bind$default (Lio/ktor/network/sockets/UDPSocketBuilder;Lio/ktor/network/sockets/SocketAddress;Lkotlin/jvm/functions/Function1;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; + public static synthetic fun bind$default (Lio/ktor/network/sockets/UDPSocketBuilder;Ljava/lang/String;ILkotlin/jvm/functions/Function1;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; public synthetic fun configure (Lkotlin/jvm/functions/Function1;)Lio/ktor/network/sockets/Configurable; public fun configure (Lkotlin/jvm/functions/Function1;)Lio/ktor/network/sockets/UDPSocketBuilder; public final fun connect (Lio/ktor/network/sockets/SocketAddress;Lio/ktor/network/sockets/SocketAddress;Lkotlin/jvm/functions/Function1;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; diff --git a/ktor-network/api/ktor-network.klib.api b/ktor-network/api/ktor-network.klib.api index d2cdca9a47b..3af84ac69cc 100644 --- a/ktor-network/api/ktor-network.klib.api +++ b/ktor-network/api/ktor-network.klib.api @@ -1,5 +1,6 @@ // Klib ABI Dump -// Targets: [androidNativeArm32, androidNativeArm64, androidNativeX64, androidNativeX86, iosArm64, iosSimulatorArm64, iosX64, linuxArm64, linuxX64, macosArm64, macosX64, mingwX64, tvosArm64, tvosSimulatorArm64, tvosX64, watchosArm32, watchosArm64, watchosDeviceArm64, watchosSimulatorArm64, watchosX64] +// Targets: [androidNativeArm32, androidNativeArm64, androidNativeX64, androidNativeX86, iosArm64, iosSimulatorArm64, iosX64, js, linuxArm64, linuxX64, macosArm64, macosX64, mingwX64, tvosArm64, tvosSimulatorArm64, tvosX64, wasmJs, watchosArm32, watchosArm64, watchosDeviceArm64, watchosSimulatorArm64, watchosX64] +// Alias: native => [androidNativeArm32, androidNativeArm64, androidNativeX64, androidNativeX86, iosArm64, iosSimulatorArm64, iosX64, linuxArm64, linuxX64, macosArm64, macosX64, mingwX64, tvosArm64, tvosSimulatorArm64, tvosX64, watchosArm32, watchosArm64, watchosDeviceArm64, watchosSimulatorArm64, watchosX64] // Rendering settings: // - Signature version: 2 // - Show manifest properties: true @@ -36,11 +37,6 @@ abstract interface <#A: out io.ktor.network.sockets/Configurable<#A, #B>, #B: io open fun configure(kotlin/Function1<#B, kotlin/Unit>): #A // io.ktor.network.sockets/Configurable.configure|configure(kotlin.Function1<1:1,kotlin.Unit>){}[0] } -abstract interface io.ktor.network.selector/Selectable { // io.ktor.network.selector/Selectable|null[0] - abstract val descriptor // io.ktor.network.selector/Selectable.descriptor|{}descriptor[0] - abstract fun (): kotlin/Int // io.ktor.network.selector/Selectable.descriptor.|(){}[0] -} - abstract interface io.ktor.network.selector/SelectorManager : io.ktor.utils.io.core/Closeable, kotlinx.coroutines/CoroutineScope { // io.ktor.network.selector/SelectorManager|null[0] abstract fun notifyClosed(io.ktor.network.selector/Selectable) // io.ktor.network.selector/SelectorManager.notifyClosed|notifyClosed(io.ktor.network.selector.Selectable){}[0] abstract suspend fun select(io.ktor.network.selector/Selectable, io.ktor.network.selector/SelectInterest) // io.ktor.network.selector/SelectorManager.select|select(io.ktor.network.selector.Selectable;io.ktor.network.selector.SelectInterest){}[0] @@ -103,10 +99,6 @@ final class io.ktor.network.selector/ClosedChannelCancellationException : kotlin constructor () // io.ktor.network.selector/ClosedChannelCancellationException.|(){}[0] } -final class io.ktor.network.selector/SocketError : kotlin/IllegalStateException { // io.ktor.network.selector/SocketError|null[0] - constructor () // io.ktor.network.selector/SocketError.|(){}[0] -} - final class io.ktor.network.sockets/Connection { // io.ktor.network.sockets/Connection|null[0] constructor (io.ktor.network.sockets/Socket, io.ktor.utils.io/ByteReadChannel, io.ktor.utils.io/ByteWriteChannel) // io.ktor.network.sockets/Connection.|(io.ktor.network.sockets.Socket;io.ktor.utils.io.ByteReadChannel;io.ktor.utils.io.ByteWriteChannel){}[0] @@ -174,6 +166,7 @@ final class io.ktor.network.sockets/UDPSocketBuilder : io.ktor.network.sockets/C final fun (io.ktor.network.sockets/SocketOptions.UDPSocketOptions) // io.ktor.network.sockets/UDPSocketBuilder.options.|(io.ktor.network.sockets.SocketOptions.UDPSocketOptions){}[0] final suspend fun bind(io.ktor.network.sockets/SocketAddress? = ..., kotlin/Function1 = ...): io.ktor.network.sockets/BoundDatagramSocket // io.ktor.network.sockets/UDPSocketBuilder.bind|bind(io.ktor.network.sockets.SocketAddress?;kotlin.Function1){}[0] + final suspend fun bind(kotlin/String = ..., kotlin/Int = ..., kotlin/Function1 = ...): io.ktor.network.sockets/BoundDatagramSocket // io.ktor.network.sockets/UDPSocketBuilder.bind|bind(kotlin.String;kotlin.Int;kotlin.Function1){}[0] final suspend fun connect(io.ktor.network.sockets/SocketAddress, io.ktor.network.sockets/SocketAddress? = ..., kotlin/Function1 = ...): io.ktor.network.sockets/ConnectedDatagramSocket // io.ktor.network.sockets/UDPSocketBuilder.connect|connect(io.ktor.network.sockets.SocketAddress;io.ktor.network.sockets.SocketAddress?;kotlin.Function1){}[0] } @@ -284,3 +277,17 @@ final fun <#A: io.ktor.network.sockets/Configurable<#A, *>> (#A).io.ktor.network final fun io.ktor.network.selector/SelectorManager(kotlin.coroutines/CoroutineContext = ...): io.ktor.network.selector/SelectorManager // io.ktor.network.selector/SelectorManager|SelectorManager(kotlin.coroutines.CoroutineContext){}[0] final fun io.ktor.network.sockets/aSocket(io.ktor.network.selector/SelectorManager): io.ktor.network.sockets/SocketBuilder // io.ktor.network.sockets/aSocket|aSocket(io.ktor.network.selector.SelectorManager){}[0] final suspend fun (io.ktor.network.sockets/ASocket).io.ktor.network.sockets/awaitClosed() // io.ktor.network.sockets/awaitClosed|awaitClosed@io.ktor.network.sockets.ASocket(){}[0] + +// Targets: [native] +abstract interface io.ktor.network.selector/Selectable { // io.ktor.network.selector/Selectable|null[0] + abstract val descriptor // io.ktor.network.selector/Selectable.descriptor|{}descriptor[0] + abstract fun (): kotlin/Int // io.ktor.network.selector/Selectable.descriptor.|(){}[0] +} + +// Targets: [native] +final class io.ktor.network.selector/SocketError : kotlin/IllegalStateException { // io.ktor.network.selector/SocketError|null[0] + constructor () // io.ktor.network.selector/SocketError.|(){}[0] +} + +// Targets: [js, wasmJs] +abstract interface io.ktor.network.selector/Selectable // io.ktor.network.selector/Selectable|null[0] diff --git a/ktor-network/build.gradle.kts b/ktor-network/build.gradle.kts index a3c871ddec5..b2ac809bb7d 100644 --- a/ktor-network/build.gradle.kts +++ b/ktor-network/build.gradle.kts @@ -10,13 +10,13 @@ kotlin { } sourceSets { - jvmAndPosixMain { + commonMain { dependencies { api(project(":ktor-utils")) } } - jvmAndPosixTest { + commonTest { dependencies { api(project(":ktor-test-dispatcher")) } diff --git a/ktor-network/jvmAndPosix/src/io/ktor/network/selector/Selectable.kt b/ktor-network/common/src/io/ktor/network/selector/Selectable.kt similarity index 100% rename from ktor-network/jvmAndPosix/src/io/ktor/network/selector/Selectable.kt rename to ktor-network/common/src/io/ktor/network/selector/Selectable.kt diff --git a/ktor-network/jvmAndPosix/src/io/ktor/network/selector/SelectorManagerCommon.kt b/ktor-network/common/src/io/ktor/network/selector/SelectorManagerCommon.kt similarity index 98% rename from ktor-network/jvmAndPosix/src/io/ktor/network/selector/SelectorManagerCommon.kt rename to ktor-network/common/src/io/ktor/network/selector/SelectorManagerCommon.kt index beb54cbb3ac..214c1571ab6 100644 --- a/ktor-network/jvmAndPosix/src/io/ktor/network/selector/SelectorManagerCommon.kt +++ b/ktor-network/common/src/io/ktor/network/selector/SelectorManagerCommon.kt @@ -11,7 +11,6 @@ import kotlin.coroutines.* /** * Creates the selector manager for current platform. */ -@Suppress("FunctionName") public expect fun SelectorManager( dispatcher: CoroutineContext = EmptyCoroutineContext ): SelectorManager diff --git a/ktor-network/jvmAndPosix/src/io/ktor/network/sockets/Builders.kt b/ktor-network/common/src/io/ktor/network/sockets/Builders.kt similarity index 100% rename from ktor-network/jvmAndPosix/src/io/ktor/network/sockets/Builders.kt rename to ktor-network/common/src/io/ktor/network/sockets/Builders.kt diff --git a/ktor-network/jvmAndPosix/src/io/ktor/network/sockets/Datagram.kt b/ktor-network/common/src/io/ktor/network/sockets/Datagram.kt similarity index 92% rename from ktor-network/jvmAndPosix/src/io/ktor/network/sockets/Datagram.kt rename to ktor-network/common/src/io/ktor/network/sockets/Datagram.kt index 003f542ce60..ea916b86f9f 100644 --- a/ktor-network/jvmAndPosix/src/io/ktor/network/sockets/Datagram.kt +++ b/ktor-network/common/src/io/ktor/network/sockets/Datagram.kt @@ -1,6 +1,6 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.network.sockets diff --git a/ktor-network/jvmAndPosix/src/io/ktor/network/sockets/SocketAddress.kt b/ktor-network/common/src/io/ktor/network/sockets/SocketAddress.kt similarity index 96% rename from ktor-network/jvmAndPosix/src/io/ktor/network/sockets/SocketAddress.kt rename to ktor-network/common/src/io/ktor/network/sockets/SocketAddress.kt index eb66b7062bc..d7df452da83 100644 --- a/ktor-network/jvmAndPosix/src/io/ktor/network/sockets/SocketAddress.kt +++ b/ktor-network/common/src/io/ktor/network/sockets/SocketAddress.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.network.sockets diff --git a/ktor-network/common/src/io/ktor/network/sockets/SocketEngine.kt b/ktor-network/common/src/io/ktor/network/sockets/SocketEngine.kt new file mode 100644 index 00000000000..479cb567153 --- /dev/null +++ b/ktor-network/common/src/io/ktor/network/sockets/SocketEngine.kt @@ -0,0 +1,32 @@ +/* + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + +package io.ktor.network.sockets + +import io.ktor.network.selector.* + +internal expect suspend fun tcpConnect( + selector: SelectorManager, + remoteAddress: SocketAddress, + socketOptions: SocketOptions.TCPClientSocketOptions +): Socket + +internal expect suspend fun tcpBind( + selector: SelectorManager, + localAddress: SocketAddress?, + socketOptions: SocketOptions.AcceptorOptions +): ServerSocket + +internal expect suspend fun udpConnect( + selector: SelectorManager, + remoteAddress: SocketAddress, + localAddress: SocketAddress?, + options: SocketOptions.UDPSocketOptions +): ConnectedDatagramSocket + +internal expect suspend fun udpBind( + selector: SelectorManager, + localAddress: SocketAddress?, + options: SocketOptions.UDPSocketOptions +): BoundDatagramSocket diff --git a/ktor-network/jvmAndPosix/src/io/ktor/network/sockets/SocketOptions.kt b/ktor-network/common/src/io/ktor/network/sockets/SocketOptions.kt similarity index 96% rename from ktor-network/jvmAndPosix/src/io/ktor/network/sockets/SocketOptions.kt rename to ktor-network/common/src/io/ktor/network/sockets/SocketOptions.kt index 539536086da..5bf016ac4e7 100644 --- a/ktor-network/jvmAndPosix/src/io/ktor/network/sockets/SocketOptions.kt +++ b/ktor-network/common/src/io/ktor/network/sockets/SocketOptions.kt @@ -4,12 +4,11 @@ package io.ktor.network.sockets -internal const val INFINITE_TIMEOUT_MS = Long.MAX_VALUE +private const val INFINITE_TIMEOUT_MS = Long.MAX_VALUE /** * Socket options builder */ -@OptIn(ExperimentalUnsignedTypes::class) public sealed class SocketOptions( protected val customOptions: MutableMap ) { @@ -30,7 +29,7 @@ public sealed class SocketOptions( } } - internal fun acceptor(): AcceptorOptions { + internal fun tcpAccept(): AcceptorOptions { return AcceptorOptions(HashMap(customOptions)).apply { copyCommon(this@SocketOptions) } @@ -113,7 +112,7 @@ public sealed class SocketOptions( } } - internal fun tcp(): TCPClientSocketOptions { + internal fun tcpConnect(): TCPClientSocketOptions { return TCPClientSocketOptions(HashMap(customOptions)).apply { copyCommon(this@PeerSocketOptions) } diff --git a/ktor-network/jvmAndPosix/src/io/ktor/network/sockets/Sockets.kt b/ktor-network/common/src/io/ktor/network/sockets/Sockets.kt similarity index 96% rename from ktor-network/jvmAndPosix/src/io/ktor/network/sockets/Sockets.kt rename to ktor-network/common/src/io/ktor/network/sockets/Sockets.kt index cdaca9436ca..c8a9fa005b7 100644 --- a/ktor-network/jvmAndPosix/src/io/ktor/network/sockets/Sockets.kt +++ b/ktor-network/common/src/io/ktor/network/sockets/Sockets.kt @@ -1,6 +1,6 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.network.sockets diff --git a/ktor-network/jvmAndPosix/src/io/ktor/network/sockets/TcpSocketBuilder.kt b/ktor-network/common/src/io/ktor/network/sockets/TcpSocketBuilder.kt similarity index 88% rename from ktor-network/jvmAndPosix/src/io/ktor/network/sockets/TcpSocketBuilder.kt rename to ktor-network/common/src/io/ktor/network/sockets/TcpSocketBuilder.kt index 99342ff9e32..ec88283f44e 100644 --- a/ktor-network/jvmAndPosix/src/io/ktor/network/sockets/TcpSocketBuilder.kt +++ b/ktor-network/common/src/io/ktor/network/sockets/TcpSocketBuilder.kt @@ -37,7 +37,7 @@ public class TcpSocketBuilder internal constructor( public suspend fun connect( remoteAddress: SocketAddress, configure: SocketOptions.TCPClientSocketOptions.() -> Unit = {} - ): Socket = connect(selector, remoteAddress, options.tcp().apply(configure)) + ): Socket = tcpConnect(selector, remoteAddress, options.tcpConnect().apply(configure)) /** * Bind server socket to listen to [localAddress]. @@ -45,5 +45,5 @@ public class TcpSocketBuilder internal constructor( public suspend fun bind( localAddress: SocketAddress? = null, configure: SocketOptions.AcceptorOptions.() -> Unit = {} - ): ServerSocket = bind(selector, localAddress, options.acceptor().apply(configure)) + ): ServerSocket = tcpBind(selector, localAddress, options.tcpAccept().apply(configure)) } diff --git a/ktor-network/jvmAndPosix/src/io/ktor/network/sockets/TypeOfService.kt b/ktor-network/common/src/io/ktor/network/sockets/TypeOfService.kt similarity index 87% rename from ktor-network/jvmAndPosix/src/io/ktor/network/sockets/TypeOfService.kt rename to ktor-network/common/src/io/ktor/network/sockets/TypeOfService.kt index df2fb6324e0..f080844b264 100644 --- a/ktor-network/jvmAndPosix/src/io/ktor/network/sockets/TypeOfService.kt +++ b/ktor-network/common/src/io/ktor/network/sockets/TypeOfService.kt @@ -1,6 +1,6 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.network.sockets diff --git a/ktor-network/jvmAndPosix/src/io/ktor/network/sockets/UDPSocketBuilder.kt b/ktor-network/common/src/io/ktor/network/sockets/UDPSocketBuilder.kt similarity index 67% rename from ktor-network/jvmAndPosix/src/io/ktor/network/sockets/UDPSocketBuilder.kt rename to ktor-network/common/src/io/ktor/network/sockets/UDPSocketBuilder.kt index 5fb65194de3..7b680260c45 100644 --- a/ktor-network/jvmAndPosix/src/io/ktor/network/sockets/UDPSocketBuilder.kt +++ b/ktor-network/common/src/io/ktor/network/sockets/UDPSocketBuilder.kt @@ -19,7 +19,16 @@ public class UDPSocketBuilder internal constructor( public suspend fun bind( localAddress: SocketAddress? = null, configure: SocketOptions.UDPSocketOptions.() -> Unit = {} - ): BoundDatagramSocket = bindUDP(selector, localAddress, options.udp().apply(configure)) + ): BoundDatagramSocket = udpBind(selector, localAddress, options.udp().apply(configure)) + + /** + * Bind server socket at [port] to listen to [hostname]. + */ + public suspend fun bind( + hostname: String = "0.0.0.0", + port: Int = 0, + configure: SocketOptions.UDPSocketOptions.() -> Unit = {} + ): BoundDatagramSocket = bind(InetSocketAddress(hostname, port), configure) /** * Create a datagram socket to listen datagrams at [localAddress] and set to [remoteAddress]. @@ -28,18 +37,5 @@ public class UDPSocketBuilder internal constructor( remoteAddress: SocketAddress, localAddress: SocketAddress? = null, configure: SocketOptions.UDPSocketOptions.() -> Unit = {} - ): ConnectedDatagramSocket = connectUDP(selector, remoteAddress, localAddress, options.udp().apply(configure)) + ): ConnectedDatagramSocket = udpConnect(selector, remoteAddress, localAddress, options.udp().apply(configure)) } - -internal expect fun connectUDP( - selector: SelectorManager, - remoteAddress: SocketAddress, - localAddress: SocketAddress?, - options: SocketOptions.UDPSocketOptions -): ConnectedDatagramSocket - -internal expect fun bindUDP( - selector: SelectorManager, - localAddress: SocketAddress?, - options: SocketOptions.UDPSocketOptions -): BoundDatagramSocket diff --git a/ktor-network/jvmAndPosix/test/io/ktor/network/sockets/tests/TCPSocketTest.kt b/ktor-network/common/test/io/ktor/network/sockets/tests/TCPSocketTest.kt similarity index 72% rename from ktor-network/jvmAndPosix/test/io/ktor/network/sockets/tests/TCPSocketTest.kt rename to ktor-network/common/test/io/ktor/network/sockets/tests/TCPSocketTest.kt index bece892c452..3687478c547 100644 --- a/ktor-network/jvmAndPosix/test/io/ktor/network/sockets/tests/TCPSocketTest.kt +++ b/ktor-network/common/test/io/ktor/network/sockets/tests/TCPSocketTest.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.network.sockets.tests @@ -7,7 +7,6 @@ package io.ktor.network.sockets.tests import io.ktor.network.sockets.* import io.ktor.utils.io.* import io.ktor.utils.io.CancellationException -import io.ktor.utils.io.core.* import kotlinx.coroutines.* import kotlinx.io.* import kotlin.test.* @@ -63,48 +62,49 @@ class TCPSocketTest { if (!supportsUnixDomainSockets()) return@testSockets val socketPath = createTempFilePath("ktor-echo-test") + try { + val tcp = aSocket(selector).tcp() + val server = tcp.bind(UnixSocketAddress(socketPath)) - val tcp = aSocket(selector).tcp() - val server = tcp.bind(UnixSocketAddress(socketPath)) + val serverConnectionPromise = async { + server.accept() + } - val serverConnectionPromise = async { - server.accept() - } + val clientConnection = tcp.connect(UnixSocketAddress(socketPath)) + val serverConnection = serverConnectionPromise.await() - val clientConnection = tcp.connect(UnixSocketAddress(socketPath)) - val serverConnection = serverConnectionPromise.await() + val clientOutput = clientConnection.openWriteChannel() + try { + clientOutput.writeStringUtf8("Hello, world\n") + clientOutput.flush() + } finally { + clientOutput.flushAndClose() + } - val clientOutput = clientConnection.openWriteChannel() - try { - clientOutput.writeStringUtf8("Hello, world\n") - clientOutput.flush() - } finally { - clientOutput.flushAndClose() - } + val serverInput = serverConnection.openReadChannel() + val message = serverInput.readUTF8Line() + assertEquals("Hello, world", message) - val serverInput = serverConnection.openReadChannel() - val message = serverInput.readUTF8Line() - assertEquals("Hello, world", message) + val serverOutput = serverConnection.openWriteChannel() + try { + serverOutput.writeStringUtf8("Hello From Server\n") + serverOutput.flush() - val serverOutput = serverConnection.openWriteChannel() - try { - serverOutput.writeStringUtf8("Hello From Server\n") - serverOutput.flush() + val clientInput = clientConnection.openReadChannel() + val echo = clientInput.readUTF8Line() - val clientInput = clientConnection.openReadChannel() - val echo = clientInput.readUTF8Line() + assertEquals("Hello From Server", echo) + } finally { + serverOutput.flushAndClose() + } - assertEquals("Hello From Server", echo) + serverConnection.close() + clientConnection.close() + + server.close() } finally { - serverOutput.flushAndClose() + removeFile(socketPath) } - - serverConnection.close() - clientConnection.close() - - server.close() - - removeFile(socketPath) } @Test diff --git a/ktor-network/common/test/io/ktor/network/sockets/tests/TestUtils.kt b/ktor-network/common/test/io/ktor/network/sockets/tests/TestUtils.kt new file mode 100644 index 00000000000..d80261d204c --- /dev/null +++ b/ktor-network/common/test/io/ktor/network/sockets/tests/TestUtils.kt @@ -0,0 +1,35 @@ +/* + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + +package io.ktor.network.sockets.tests + +import io.ktor.network.selector.* +import io.ktor.test.dispatcher.* +import io.ktor.utils.io.core.* +import kotlinx.coroutines.* +import kotlinx.coroutines.test.* +import kotlinx.io.files.* +import kotlin.time.* +import kotlin.time.Duration.Companion.minutes +import kotlin.uuid.* + +internal fun testSockets( + timeout: Duration = 1.minutes, + block: suspend CoroutineScope.(SelectorManager) -> Unit +): TestResult = runTestWithRealTime(timeout = timeout) { + SelectorManager().use { selector -> + block(selector) + } +} + +internal expect fun Any.supportsUnixDomainSockets(): Boolean + +@OptIn(ExperimentalUuidApi::class) +internal fun createTempFilePath(basename: String): String { + return Path(SystemTemporaryDirectory, "$basename-${Uuid.random()}").toString() +} + +internal fun removeFile(path: String) { + SystemFileSystem.delete(Path(path), mustExist = false) +} diff --git a/ktor-network/gradle.properties b/ktor-network/gradle.properties new file mode 100644 index 00000000000..d12c10bfad8 --- /dev/null +++ b/ktor-network/gradle.properties @@ -0,0 +1,5 @@ +# +# Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. +# +target.js.browser=false +target.wasmJs.browser=false diff --git a/ktor-network/ios/test/io/ktor/network/sockets/tests/TestUtilsIos.kt b/ktor-network/ios/test/io/ktor/network/sockets/tests/TestUtilsIos.kt deleted file mode 100644 index 190092748d8..00000000000 --- a/ktor-network/ios/test/io/ktor/network/sockets/tests/TestUtilsIos.kt +++ /dev/null @@ -1,7 +0,0 @@ -/* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. - */ - -package io.ktor.network.sockets.tests - -internal actual fun Any.supportsUnixDomainSockets(): Boolean = false diff --git a/ktor-network/js/src/io/ktor/network/sockets/nodejs/node.net.js.kt b/ktor-network/js/src/io/ktor/network/sockets/nodejs/node.net.js.kt new file mode 100644 index 00000000000..7a89dc616b7 --- /dev/null +++ b/ktor-network/js/src/io/ktor/network/sockets/nodejs/node.net.js.kt @@ -0,0 +1,45 @@ +/* + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + +package io.ktor.network.sockets.nodejs + +import io.ktor.network.sockets.* +import org.khronos.webgl.* + +internal actual fun nodeNet(): NodeNet? = js("eval('require')('node:net')").unsafeCast() + +internal actual fun TcpCreateConnectionOptions( + block: TcpCreateConnectionOptions.() -> Unit +): TcpCreateConnectionOptions = createObject(block) + +internal actual fun IpcCreateConnectionOptions( + block: IpcCreateConnectionOptions.() -> Unit +): IpcCreateConnectionOptions = createObject(block) + +internal actual fun CreateServerOptions( + block: CreateServerOptions.() -> Unit +): CreateServerOptions = createObject(block) + +internal actual fun ServerListenOptions( + block: ServerListenOptions.() -> Unit +): ServerListenOptions = createObject(block) + +private fun createObject(block: T.() -> Unit): T = js("{}").unsafeCast().apply(block) + +internal actual fun JsError.toThrowable(): Throwable = unsafeCast() +internal actual fun Throwable.toJsError(): JsError? = unsafeCast() + +internal actual fun ByteArray.toJsBuffer(fromIndex: Int, toIndex: Int): JsBuffer { + return unsafeCast().subarray(fromIndex, toIndex).unsafeCast() +} + +internal actual fun JsBuffer.toByteArray(): ByteArray { + return Int8Array(unsafeCast()).unsafeCast() +} + +internal actual fun ServerLocalAddressInfo.toSocketAddress(): SocketAddress { + if (jsTypeOf(this) == "string") return UnixSocketAddress(unsafeCast()) + val info = unsafeCast() + return InetSocketAddress(info.address, info.port) +} diff --git a/ktor-network/windows/test/io/ktor/network/sockets/tests/TestUtilsWindows.kt b/ktor-network/jsAndWasmShared/src/io/ktor/network/selector/Selectable.jsAndWasmShared.kt similarity index 54% rename from ktor-network/windows/test/io/ktor/network/sockets/tests/TestUtilsWindows.kt rename to ktor-network/jsAndWasmShared/src/io/ktor/network/selector/Selectable.jsAndWasmShared.kt index 5006b7bb955..d462ef91350 100644 --- a/ktor-network/windows/test/io/ktor/network/sockets/tests/TestUtilsWindows.kt +++ b/ktor-network/jsAndWasmShared/src/io/ktor/network/selector/Selectable.jsAndWasmShared.kt @@ -2,6 +2,6 @@ * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ -package io.ktor.network.sockets.tests +package io.ktor.network.selector -internal actual fun Any.supportsUnixDomainSockets(): Boolean = false +public actual interface Selectable diff --git a/ktor-network/jsAndWasmShared/src/io/ktor/network/selector/SelectorManager.jsAndWasmShared.kt b/ktor-network/jsAndWasmShared/src/io/ktor/network/selector/SelectorManager.jsAndWasmShared.kt new file mode 100644 index 00000000000..4331d052a50 --- /dev/null +++ b/ktor-network/jsAndWasmShared/src/io/ktor/network/selector/SelectorManager.jsAndWasmShared.kt @@ -0,0 +1,63 @@ +/* +* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. +*/ + +package io.ktor.network.selector + +import io.ktor.utils.io.core.* +import kotlinx.coroutines.* +import kotlin.coroutines.* + +public actual fun SelectorManager(dispatcher: CoroutineContext): SelectorManager = NoopSelectorManager + +public actual interface SelectorManager : CoroutineScope, Closeable { + /** + * Notifies the selector that selectable has been closed. + */ + public actual fun notifyClosed(selectable: Selectable) + + /** + * Suspends until [interest] is selected for [selectable] + * May cause manager to allocate and run selector instance if not yet created. + * + * Only one selection is allowed per [interest] per [selectable] but you can + * select for different interests for the same selectable simultaneously. + * In other words you can select for read and write at the same time but should never + * try to read twice for the same selectable. + */ + public actual suspend fun select( + selectable: Selectable, + interest: SelectInterest + ) + + public actual companion object +} + +/** + * Select interest kind + */ +public actual enum class SelectInterest { + READ, WRITE, ACCEPT, CONNECT; + + public actual companion object { + public actual val AllInterests: Array + get() = entries.toTypedArray() + } +} + +// TODO: how coroutine context should be used? +private object NoopSelectorManager : SelectorManager { + override val coroutineContext: CoroutineContext get() = EmptyCoroutineContext + + override fun notifyClosed(selectable: Selectable) { + error("not supported") + } + + override suspend fun select(selectable: Selectable, interest: SelectInterest) { + error("not supported") + } + + override fun close() { + // no-op so it can be called in common code + } +} diff --git a/ktor-network/jsAndWasmShared/src/io/ktor/network/sockets/ServerSocketContext.kt b/ktor-network/jsAndWasmShared/src/io/ktor/network/sockets/ServerSocketContext.kt new file mode 100644 index 00000000000..f14801e28e8 --- /dev/null +++ b/ktor-network/jsAndWasmShared/src/io/ktor/network/sockets/ServerSocketContext.kt @@ -0,0 +1,73 @@ +/* + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + +package io.ktor.network.sockets + +import io.ktor.network.sockets.nodejs.* +import kotlinx.coroutines.* +import kotlinx.coroutines.channels.* +import kotlinx.io.* +import kotlin.coroutines.* + +internal class ServerSocketContext( + private val server: Server, + private val localAddress: SocketAddress?, + parentContext: Job? +) { + private val incomingSockets = Channel(Channel.UNLIMITED) + private val serverContext = SupervisorJob(parentContext) + + fun initiate(cont: CancellableContinuation) { + cont.invokeOnCancellation { + server.close() + + serverContext.cancel() + incomingSockets.cancel() + } + + server.onConnection { socket -> + val context = SocketContext(socket, localAddress, serverContext) + context.initiate(null) + incomingSockets.trySend(context.createSocket()) + } + server.onClose { + if (cont.isActive) { + cont.resumeWithException(IOException("Failed to bind")) + } else { + serverContext.job.cancel("Server closed") + } + } + server.onError { error -> + if (cont.isActive) { + cont.resumeWithException(IOException("Failed to bind", error.toThrowable())) + } else { + serverContext.job.cancel("Server failed", error.toThrowable()) + } + } + server.onListening { + cont.resume(ServerSocketImpl(server.address()!!.toSocketAddress(), serverContext, incomingSockets, server)) + } + server.listen(ServerListenOptions(localAddress)) + } +} + +private class ServerSocketImpl( + override val localAddress: SocketAddress, + override val socketContext: Job, + private val incoming: ReceiveChannel, + private val server: Server +) : ServerSocket { + override suspend fun accept(): Socket = incoming.receive() + + init { + socketContext.invokeOnCompletion { + server.close() + incoming.cancel() + } + } + + override fun close() { + socketContext.cancel("Server socket closed") + } +} diff --git a/ktor-network/jsAndWasmShared/src/io/ktor/network/sockets/SocketContext.kt b/ktor-network/jsAndWasmShared/src/io/ktor/network/sockets/SocketContext.kt new file mode 100644 index 00000000000..909d86b0ed2 --- /dev/null +++ b/ktor-network/jsAndWasmShared/src/io/ktor/network/sockets/SocketContext.kt @@ -0,0 +1,116 @@ +/* + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + +package io.ktor.network.sockets + +import io.ktor.network.sockets.nodejs.* +import io.ktor.utils.io.* +import kotlinx.coroutines.* +import kotlinx.coroutines.channels.* +import kotlinx.io.* +import kotlin.coroutines.* +import io.ktor.network.sockets.nodejs.Socket as NodejsSocket + +internal class SocketContext( + private val socket: NodejsSocket, + private val address: SocketAddress?, + parentContext: Job? +) { + private val incomingFrames: Channel = Channel(Channel.UNLIMITED) + private val socketContext = Job(parentContext) + + fun initiate(connectCont: CancellableContinuation?) { + connectCont?.invokeOnCancellation { + socket.destroy(it?.toJsError()) + + socketContext.cancel() + incomingFrames.cancel() + } + socket.onError { error -> + when (connectCont?.isActive) { + true -> connectCont.resumeWithException(IOException("Failed to connect", error.toThrowable())) + else -> socketContext.job.cancel("Socket error", error.toThrowable()) + } + } + socket.onTimeout { + when (connectCont?.isActive) { + true -> connectCont.resumeWithException(SocketTimeoutException("timeout")) + else -> socketContext.job.cancel("Socket timeout", SocketTimeoutException("timeout")) + } + } + socket.onEnd { + incomingFrames.close() + } + socket.onClose { + socketContext.job.cancel("Socket closed") + } + socket.onData { data -> + incomingFrames.trySend(data) + } + + if (connectCont != null) { + socket.onConnect { + connectCont.resume(createSocket()) + } + } + } + + // Socket real address could be resolved only after the ` connect ` event. + // Also, Node.js doesn't give access to unix address from the ` socket ` object, + // so we need to store it. + fun createSocket(): Socket = SocketImpl( + localAddress = when (address) { + is UnixSocketAddress -> address + else -> InetSocketAddress(socket.localAddress, socket.localPort) + }, + remoteAddress = when (address) { + is UnixSocketAddress -> address + else -> InetSocketAddress(socket.remoteAddress, socket.remotePort) + }, + coroutineContext = socketContext, + incoming = incomingFrames, + socket = socket + ) +} + +private class SocketImpl( + override val localAddress: SocketAddress, + override val remoteAddress: SocketAddress, + override val coroutineContext: CoroutineContext, + private val incoming: ReceiveChannel, + private val socket: NodejsSocket +) : Socket { + override val socketContext: Job get() = coroutineContext.job + + init { + socketContext.invokeOnCompletion { + socket.destroy(it?.toJsError()) + incoming.cancel(CancellationException("Socket closed", it)) + } + } + + override fun attachForReading(channel: ByteChannel): WriterJob = writer(Dispatchers.Unconfined, channel = channel) { + incoming.consumeEach { buffer -> + channel.writeByteArray(buffer.toByteArray()) + channel.flush() + } + } + + override fun attachForWriting(channel: ByteChannel): ReaderJob = reader(Dispatchers.Unconfined, channel = channel) { + while (true) { + val result = channel.read { bytes, startIndex, endIndex -> + socket.write(bytes.toJsBuffer(startIndex, endIndex)) + endIndex - startIndex + } + if (result == -1) { + socket.end() + break + } + } + } + + override fun close() { + socketContext.cancel("Socket closed") + } +} diff --git a/ktor-network/jsAndWasmShared/src/io/ktor/network/sockets/SocketEngine.jsAndWasmShared.kt b/ktor-network/jsAndWasmShared/src/io/ktor/network/sockets/SocketEngine.jsAndWasmShared.kt new file mode 100644 index 00000000000..9a404891f34 --- /dev/null +++ b/ktor-network/jsAndWasmShared/src/io/ktor/network/sockets/SocketEngine.jsAndWasmShared.kt @@ -0,0 +1,40 @@ +/* + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + +package io.ktor.network.sockets + +import io.ktor.network.selector.* +import io.ktor.network.sockets.nodejs.* +import kotlinx.coroutines.* + +internal actual suspend fun tcpConnect( + selector: SelectorManager, + remoteAddress: SocketAddress, + socketOptions: SocketOptions.TCPClientSocketOptions +): Socket = suspendCancellableCoroutine { cont -> + val socket = nodeNet.createConnection(CreateConnectionOptions(remoteAddress, socketOptions)) + SocketContext(socket, remoteAddress, null).initiate(cont) +} + +internal actual suspend fun tcpBind( + selector: SelectorManager, + localAddress: SocketAddress?, + socketOptions: SocketOptions.AcceptorOptions +): ServerSocket = suspendCancellableCoroutine { cont -> + val server = nodeNet.createServer(CreateServerOptions {}) + ServerSocketContext(server, localAddress, null).initiate(cont) +} + +internal actual suspend fun udpConnect( + selector: SelectorManager, + remoteAddress: SocketAddress, + localAddress: SocketAddress?, + options: SocketOptions.UDPSocketOptions +): ConnectedDatagramSocket = error("UDP sockets are unsupported on WASM/JS") + +internal actual suspend fun udpBind( + selector: SelectorManager, + localAddress: SocketAddress?, + options: SocketOptions.UDPSocketOptions +): BoundDatagramSocket = error("UDP sockets are unsupported on WASM/JS") diff --git a/ktor-network/jsAndWasmShared/src/io/ktor/network/sockets/nodejs/node.net.kt b/ktor-network/jsAndWasmShared/src/io/ktor/network/sockets/nodejs/node.net.kt new file mode 100644 index 00000000000..ed3541b0cde --- /dev/null +++ b/ktor-network/jsAndWasmShared/src/io/ktor/network/sockets/nodejs/node.net.kt @@ -0,0 +1,177 @@ +/* + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + +package io.ktor.network.sockets.nodejs + +import io.ktor.network.sockets.* + +// js.Error +internal external interface JsError { + val message: String? +} + +internal expect fun JsError.toThrowable(): Throwable +internal expect fun Throwable.toJsError(): JsError? + +internal external interface JsBuffer // Int8Array + +internal expect fun ByteArray.toJsBuffer(fromIndex: Int, toIndex: Int): JsBuffer +internal expect fun JsBuffer.toByteArray(): ByteArray + +internal external interface NodeNet { + fun createConnection(options: CreateConnectionOptions): Socket + fun createServer(options: CreateServerOptions): Server +} + +internal expect fun nodeNet(): NodeNet? + +internal val nodeNet by lazy { + requireNotNull(runCatching { nodeNet() }.getOrNull()) { + "Node.js net module is not available. Please verify that you are using Node.js" + } +} + +internal fun CreateConnectionOptions( + remoteAddress: SocketAddress, + socketOptions: SocketOptions.TCPClientSocketOptions +): CreateConnectionOptions = when (remoteAddress) { + is InetSocketAddress -> TcpCreateConnectionOptions { + host = remoteAddress.hostname + port = remoteAddress.port + noDelay = socketOptions.noDelay + timeout = when (socketOptions.socketTimeout) { + Long.MAX_VALUE -> Int.MAX_VALUE + else -> socketOptions.socketTimeout.toInt() + } + keepAlive = socketOptions.keepAlive + } + + is UnixSocketAddress -> IpcCreateConnectionOptions { + path = remoteAddress.path + timeout = when (socketOptions.socketTimeout) { + Long.MAX_VALUE -> Int.MAX_VALUE + else -> socketOptions.socketTimeout.toInt() + } + } +} + +internal external interface CreateConnectionOptions { + var timeout: Int? + var allowHalfOpen: Boolean? +} + +internal expect fun TcpCreateConnectionOptions( + block: TcpCreateConnectionOptions.() -> Unit +): TcpCreateConnectionOptions + +internal external interface TcpCreateConnectionOptions : CreateConnectionOptions { + var port: Int + var host: String? + + var localAddress: String? + var localPort: Int? + var family: Int? // ip stack + var noDelay: Boolean? + var keepAlive: Boolean? +} + +internal expect fun IpcCreateConnectionOptions( + block: IpcCreateConnectionOptions.() -> Unit +): IpcCreateConnectionOptions + +internal external interface IpcCreateConnectionOptions : CreateConnectionOptions { + var path: String +} + +internal external interface Socket { + val localAddress: String + val localPort: Int + + val remoteAddress: String + val remotePort: Int + + fun write(buffer: JsBuffer): Boolean + + fun destroy(error: JsError?) + + // sends FIN + fun end() + + fun on(event: String /* "close" */, listener: (hadError: Boolean) -> Unit) + fun on(event: String /* "connect", "end", "timeout", */, listener: () -> Unit) + fun on(event: String /* "data" */, listener: (data: JsBuffer) -> Unit) + fun on(event: String /* "error" */, listener: (error: JsError) -> Unit) +} + +internal fun Socket.onClose(block: (hadError: Boolean) -> Unit): Unit = on("close", block) +internal fun Socket.onConnect(block: () -> Unit): Unit = on("connect", block) +internal fun Socket.onEnd(block: () -> Unit): Unit = on("end", block) +internal fun Socket.onTimeout(block: () -> Unit): Unit = on("timeout", block) +internal fun Socket.onData(block: (data: JsBuffer) -> Unit): Unit = on("data", block) +internal fun Socket.onError(block: (error: JsError) -> Unit): Unit = on("error", block) + +internal expect fun CreateServerOptions( + block: CreateServerOptions.() -> Unit +): CreateServerOptions + +internal external interface CreateServerOptions { + var allowHalfOpen: Boolean? + var keepAlive: Boolean? + var noDelay: Boolean? +} + +internal external interface Server { + fun address(): ServerLocalAddressInfo? + fun listen(options: ServerListenOptions) + + // stop accepting new connections + fun close() + + fun on(event: String /* "close", "listening" */, listener: () -> Unit) + fun on(event: String /* "connection" */, listener: (socket: Socket) -> Unit) + fun on(event: String /* "error" */, listener: (error: JsError) -> Unit) +} + +internal fun Server.onClose(block: () -> Unit): Unit = on("close", block) +internal fun Server.onListening(block: () -> Unit): Unit = on("listening", block) +internal fun Server.onConnection(block: (socket: Socket) -> Unit): Unit = on("connection", block) +internal fun Server.onError(block: (error: JsError) -> Unit): Unit = on("error", block) + +internal fun ServerListenOptions(localAddress: SocketAddress?): ServerListenOptions = ServerListenOptions { + when (localAddress) { + is InetSocketAddress -> { + port = localAddress.port + host = localAddress.hostname + } + + is UnixSocketAddress -> { + path = localAddress.path + } + + null -> { + host = "0.0.0.0" + port = 0 + } + } +} + +internal expect fun ServerListenOptions( + block: ServerListenOptions.() -> Unit +): ServerListenOptions + +internal external interface ServerListenOptions { + var port: Int? + var host: String? + var path: String? +} + +internal external interface ServerLocalAddressInfo + +internal external interface TcpServerLocalAddressInfo : ServerLocalAddressInfo { + val address: String + val family: String + val port: Int +} + +internal expect fun ServerLocalAddressInfo.toSocketAddress(): SocketAddress diff --git a/ktor-network/linux/test/io/ktor/network/sockets/tests/TestUtilsLinux.kt b/ktor-network/jsAndWasmShared/test/io/ktor/network/sockets/tests/TestUtils.kt similarity index 72% rename from ktor-network/linux/test/io/ktor/network/sockets/tests/TestUtilsLinux.kt rename to ktor-network/jsAndWasmShared/test/io/ktor/network/sockets/tests/TestUtils.kt index a283858bbb3..51820258638 100644 --- a/ktor-network/linux/test/io/ktor/network/sockets/tests/TestUtilsLinux.kt +++ b/ktor-network/jsAndWasmShared/test/io/ktor/network/sockets/tests/TestUtils.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.network.sockets.tests diff --git a/ktor-network/jvm/src/io/ktor/network/selector/SelectorManager.kt b/ktor-network/jvm/src/io/ktor/network/selector/SelectorManager.kt index d47045bf021..6041df1ce3b 100644 --- a/ktor-network/jvm/src/io/ktor/network/selector/SelectorManager.kt +++ b/ktor-network/jvm/src/io/ktor/network/selector/SelectorManager.kt @@ -64,7 +64,6 @@ public inline fun SelectorManager.buildOrClose( * Select interest kind * @property [flag] to be set in NIO selector */ - public actual enum class SelectInterest(public val flag: Int) { READ(SelectionKey.OP_READ), WRITE(SelectionKey.OP_WRITE), diff --git a/ktor-network/jvm/src/io/ktor/network/sockets/ConnectUtilsJvm.kt b/ktor-network/jvm/src/io/ktor/network/sockets/ConnectUtilsJvm.kt index 95827ae803f..7ac5c105c77 100644 --- a/ktor-network/jvm/src/io/ktor/network/sockets/ConnectUtilsJvm.kt +++ b/ktor-network/jvm/src/io/ktor/network/sockets/ConnectUtilsJvm.kt @@ -1,6 +1,6 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.network.sockets @@ -9,7 +9,7 @@ import java.net.* import java.nio.channels.* import java.nio.channels.spi.* -internal actual suspend fun connect( +internal actual suspend fun tcpConnect( selector: SelectorManager, remoteAddress: SocketAddress, socketOptions: SocketOptions.TCPClientSocketOptions @@ -22,7 +22,7 @@ internal actual suspend fun connect( } } -internal actual fun bind( +internal actual suspend fun tcpBind( selector: SelectorManager, localAddress: SocketAddress?, socketOptions: SocketOptions.AcceptorOptions diff --git a/ktor-network/jvm/src/io/ktor/network/sockets/UDPSocketBuilderJvm.kt b/ktor-network/jvm/src/io/ktor/network/sockets/UDPSocketBuilderJvm.kt index deb8bd96365..0b465b7cb58 100644 --- a/ktor-network/jvm/src/io/ktor/network/sockets/UDPSocketBuilderJvm.kt +++ b/ktor-network/jvm/src/io/ktor/network/sockets/UDPSocketBuilderJvm.kt @@ -6,7 +6,7 @@ package io.ktor.network.sockets import io.ktor.network.selector.* -internal actual fun connectUDP( +internal actual suspend fun udpConnect( selector: SelectorManager, remoteAddress: SocketAddress, localAddress: SocketAddress?, @@ -25,7 +25,7 @@ internal actual fun connectUDP( return DatagramSocketImpl(this, selector) } -internal actual fun bindUDP( +internal actual suspend fun udpBind( selector: SelectorManager, localAddress: SocketAddress?, options: SocketOptions.UDPSocketOptions diff --git a/ktor-network/jvm/test/io/ktor/network/sockets/tests/TestUtilsJvm.kt b/ktor-network/jvm/test/io/ktor/network/sockets/tests/TestUtilsJvm.kt index 55f12746864..8d4a8a5e72e 100644 --- a/ktor-network/jvm/test/io/ktor/network/sockets/tests/TestUtilsJvm.kt +++ b/ktor-network/jvm/test/io/ktor/network/sockets/tests/TestUtilsJvm.kt @@ -1,12 +1,9 @@ /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.network.sockets.tests -import java.nio.file.* -import kotlin.io.path.* - private const val UNIX_DOMAIN_SOCKET_ADDRESS_CLASS = "java.net.UnixDomainSocketAddress" internal actual fun Any.supportsUnixDomainSockets(): Boolean { @@ -17,13 +14,3 @@ internal actual fun Any.supportsUnixDomainSockets(): Boolean { false } } - -internal actual fun createTempFilePath(basename: String): String { - val tempFile = Files.createTempFile(basename, "") - tempFile.deleteIfExists() - return tempFile.toString() -} - -internal actual fun removeFile(path: String) { - Files.deleteIfExists(Path(path)) -} diff --git a/ktor-network/jvmAndPosix/src/io/ktor/network/sockets/ConnectUtils.kt b/ktor-network/jvmAndPosix/src/io/ktor/network/sockets/ConnectUtils.kt deleted file mode 100644 index 15db7cce981..00000000000 --- a/ktor-network/jvmAndPosix/src/io/ktor/network/sockets/ConnectUtils.kt +++ /dev/null @@ -1,19 +0,0 @@ -/* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ - -package io.ktor.network.sockets - -import io.ktor.network.selector.* - -internal expect suspend fun connect( - selector: SelectorManager, - remoteAddress: SocketAddress, - socketOptions: SocketOptions.TCPClientSocketOptions -): Socket - -internal expect fun bind( - selector: SelectorManager, - localAddress: SocketAddress?, - socketOptions: SocketOptions.AcceptorOptions -): ServerSocket diff --git a/ktor-network/jvmAndPosix/test/io/ktor/network/sockets/tests/TestUtils.kt b/ktor-network/jvmAndPosix/test/io/ktor/network/sockets/tests/TestUtils.kt deleted file mode 100644 index 3e7f36121bb..00000000000 --- a/ktor-network/jvmAndPosix/test/io/ktor/network/sockets/tests/TestUtils.kt +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. - */ - -package io.ktor.network.sockets.tests - -import io.ktor.network.selector.* -import io.ktor.test.dispatcher.* -import io.ktor.util.* -import io.ktor.utils.io.core.* -import kotlinx.coroutines.* -import kotlin.time.* -import kotlin.time.Duration.Companion.seconds - -internal fun testSockets(timeout: Duration = 1.seconds, block: suspend CoroutineScope.(SelectorManager) -> Unit) { - if (!PlatformUtils.IS_JVM && !PlatformUtils.IS_NATIVE) return - testSuspend { - withTimeout(timeout) { - SelectorManager().use { selector -> - block(selector) - } - } - } -} - -internal expect fun Any.supportsUnixDomainSockets(): Boolean - -internal expect fun createTempFilePath(basename: String): String -internal expect fun removeFile(path: String) diff --git a/ktor-network/jvmAndPosix/test/io/ktor/network/sockets/tests/UDPSocketTest.kt b/ktor-network/jvmAndPosix/test/io/ktor/network/sockets/tests/UDPSocketTest.kt index 5c9d784b5d7..9ed72e30ba6 100644 --- a/ktor-network/jvmAndPosix/test/io/ktor/network/sockets/tests/UDPSocketTest.kt +++ b/ktor-network/jvmAndPosix/test/io/ktor/network/sockets/tests/UDPSocketTest.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.network.sockets.tests @@ -11,13 +11,14 @@ import kotlinx.coroutines.* import kotlinx.io.* import kotlin.random.* import kotlin.test.* +import kotlin.use class UDPSocketTest { private val done = atomic(0) @Test - fun testBroadcastFails(): Unit = testSockets { selector -> + fun testBroadcastFails() = testSockets { selector -> if (isJvmWindows()) { return@testSockets } @@ -102,7 +103,7 @@ class UDPSocketTest { } @Test - fun testClose(): Unit = testSockets { selector -> + fun testClose() = testSockets { selector -> val socket = aSocket(selector) .udp() .bind() @@ -193,10 +194,10 @@ class UDPSocketTest { } @Test - fun testSendReceive(): Unit = testSockets { selector -> + fun testSendReceive() = testSockets { selector -> aSocket(selector) .udp() - .bind(InetSocketAddress("127.0.0.1", 8000)) { + .bind("127.0.0.1", 8000) { reuseAddress = true } .use { socket -> @@ -223,7 +224,7 @@ class UDPSocketTest { } @Test - fun testSendReceiveLarge(): Unit = testSockets { selector -> + fun testSendReceiveLarge() = testSockets { selector -> val datagramSize = 10000 // must be larger than Segment.SIZE (8192) for this test val largeData = Random.nextBytes(datagramSize) diff --git a/ktor-network/ktor-network-tls/api/ktor-network-tls.klib.api b/ktor-network/ktor-network-tls/api/ktor-network-tls.klib.api index 980bd2d90a5..4b5d8c1eb10 100644 --- a/ktor-network/ktor-network-tls/api/ktor-network-tls.klib.api +++ b/ktor-network/ktor-network-tls/api/ktor-network-tls.klib.api @@ -1,5 +1,5 @@ // Klib ABI Dump -// Targets: [androidNativeArm32, androidNativeArm64, androidNativeX64, androidNativeX86, iosArm64, iosSimulatorArm64, iosX64, linuxArm64, linuxX64, macosArm64, macosX64, mingwX64, tvosArm64, tvosSimulatorArm64, tvosX64, watchosArm32, watchosArm64, watchosDeviceArm64, watchosSimulatorArm64, watchosX64] +// Targets: [androidNativeArm32, androidNativeArm64, androidNativeX64, androidNativeX86, iosArm64, iosSimulatorArm64, iosX64, js, linuxArm64, linuxX64, macosArm64, macosX64, mingwX64, tvosArm64, tvosSimulatorArm64, tvosX64, wasmJs, watchosArm32, watchosArm64, watchosDeviceArm64, watchosSimulatorArm64, watchosX64] // Rendering settings: // - Signature version: 2 // - Show manifest properties: true diff --git a/ktor-network/ktor-network-tls/build.gradle.kts b/ktor-network/ktor-network-tls/build.gradle.kts index e4c2e74679e..92422408839 100644 --- a/ktor-network/ktor-network-tls/build.gradle.kts +++ b/ktor-network/ktor-network-tls/build.gradle.kts @@ -1,5 +1,9 @@ +/* + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + kotlin.sourceSets { - jvmAndPosixMain { + commonMain { dependencies { api(project(":ktor-http")) api(project(":ktor-network")) diff --git a/ktor-network/ktor-network-tls/jvmAndPosix/src/io/ktor/network/tls/CipherSuites.kt b/ktor-network/ktor-network-tls/common/src/io/ktor/network/tls/CipherSuites.kt similarity index 96% rename from ktor-network/ktor-network-tls/jvmAndPosix/src/io/ktor/network/tls/CipherSuites.kt rename to ktor-network/ktor-network-tls/common/src/io/ktor/network/tls/CipherSuites.kt index 4e95b5b59f2..9c96e828c80 100644 --- a/ktor-network/ktor-network-tls/jvmAndPosix/src/io/ktor/network/tls/CipherSuites.kt +++ b/ktor-network/ktor-network-tls/common/src/io/ktor/network/tls/CipherSuites.kt @@ -1,12 +1,11 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.network.tls import io.ktor.network.tls.extensions.* -import io.ktor.utils.io.errors.* -import kotlinx.io.IOException +import kotlinx.io.* /** * TLS secret key exchange type. diff --git a/ktor-network/ktor-network-tls/jvmAndPosix/src/io/ktor/network/tls/OID.kt b/ktor-network/ktor-network-tls/common/src/io/ktor/network/tls/OID.kt similarity index 95% rename from ktor-network/ktor-network-tls/jvmAndPosix/src/io/ktor/network/tls/OID.kt rename to ktor-network/ktor-network-tls/common/src/io/ktor/network/tls/OID.kt index 7f63bd72713..78b3fc88d5c 100644 --- a/ktor-network/ktor-network-tls/jvmAndPosix/src/io/ktor/network/tls/OID.kt +++ b/ktor-network/ktor-network-tls/common/src/io/ktor/network/tls/OID.kt @@ -1,11 +1,9 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.network.tls -import io.ktor.util.* - public data class OID(public val identifier: String) { public val asArray: IntArray = identifier.split(".", " ").map { it.trim().toInt() }.toIntArray() diff --git a/ktor-network/ktor-network-tls/jvmAndPosix/src/io/ktor/network/tls/TLSClientSession.kt b/ktor-network/ktor-network-tls/common/src/io/ktor/network/tls/TLSClientSession.kt similarity index 71% rename from ktor-network/ktor-network-tls/jvmAndPosix/src/io/ktor/network/tls/TLSClientSession.kt rename to ktor-network/ktor-network-tls/common/src/io/ktor/network/tls/TLSClientSession.kt index 766791b048b..aceb68b683a 100644 --- a/ktor-network/ktor-network-tls/jvmAndPosix/src/io/ktor/network/tls/TLSClientSession.kt +++ b/ktor-network/ktor-network-tls/common/src/io/ktor/network/tls/TLSClientSession.kt @@ -1,6 +1,6 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.network.tls diff --git a/ktor-network/ktor-network-tls/jvmAndPosix/src/io/ktor/network/tls/TLSCommon.kt b/ktor-network/ktor-network-tls/common/src/io/ktor/network/tls/TLSCommon.kt similarity index 92% rename from ktor-network/ktor-network-tls/jvmAndPosix/src/io/ktor/network/tls/TLSCommon.kt rename to ktor-network/ktor-network-tls/common/src/io/ktor/network/tls/TLSCommon.kt index 1f3e1aa18a2..358f3e0bf91 100644 --- a/ktor-network/ktor-network-tls/jvmAndPosix/src/io/ktor/network/tls/TLSCommon.kt +++ b/ktor-network/ktor-network-tls/common/src/io/ktor/network/tls/TLSCommon.kt @@ -1,6 +1,6 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.network.tls diff --git a/ktor-network/androidNative/test/io/ktor/network/sockets/tests/TestUtils.androidNative.kt b/ktor-network/ktor-network-tls/common/src/io/ktor/network/tls/TLSConfig.kt similarity index 54% rename from ktor-network/androidNative/test/io/ktor/network/sockets/tests/TestUtils.androidNative.kt rename to ktor-network/ktor-network-tls/common/src/io/ktor/network/tls/TLSConfig.kt index 5006b7bb955..10a3f75b4e1 100644 --- a/ktor-network/androidNative/test/io/ktor/network/sockets/tests/TestUtils.androidNative.kt +++ b/ktor-network/ktor-network-tls/common/src/io/ktor/network/tls/TLSConfig.kt @@ -2,6 +2,6 @@ * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ -package io.ktor.network.sockets.tests +package io.ktor.network.tls -internal actual fun Any.supportsUnixDomainSockets(): Boolean = false +public expect class TLSConfig diff --git a/ktor-network/ktor-network-tls/jvmAndPosix/src/io/ktor/network/tls/TLSConfigBuilderCommon.kt b/ktor-network/ktor-network-tls/common/src/io/ktor/network/tls/TLSConfigBuilderCommon.kt similarity index 79% rename from ktor-network/ktor-network-tls/jvmAndPosix/src/io/ktor/network/tls/TLSConfigBuilderCommon.kt rename to ktor-network/ktor-network-tls/common/src/io/ktor/network/tls/TLSConfigBuilderCommon.kt index a9e1e369789..1054ce0b90f 100644 --- a/ktor-network/ktor-network-tls/jvmAndPosix/src/io/ktor/network/tls/TLSConfigBuilderCommon.kt +++ b/ktor-network/ktor-network-tls/common/src/io/ktor/network/tls/TLSConfigBuilderCommon.kt @@ -1,6 +1,6 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.network.tls diff --git a/ktor-network/ktor-network-tls/jvmAndPosix/src/io/ktor/network/tls/extensions/NamedCurves.kt b/ktor-network/ktor-network-tls/common/src/io/ktor/network/tls/extensions/NamedCurves.kt similarity index 91% rename from ktor-network/ktor-network-tls/jvmAndPosix/src/io/ktor/network/tls/extensions/NamedCurves.kt rename to ktor-network/ktor-network-tls/common/src/io/ktor/network/tls/extensions/NamedCurves.kt index ad79f272939..ad1059b53b4 100644 --- a/ktor-network/ktor-network-tls/jvmAndPosix/src/io/ktor/network/tls/extensions/NamedCurves.kt +++ b/ktor-network/ktor-network-tls/common/src/io/ktor/network/tls/extensions/NamedCurves.kt @@ -1,11 +1,9 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.network.tls.extensions -import kotlin.native.concurrent.* - /** * Named curves for Elliptic Curves. * @property code curve numeric code diff --git a/ktor-network/ktor-network-tls/jvmAndPosix/src/io/ktor/network/tls/extensions/PointFormat.kt b/ktor-network/ktor-network-tls/common/src/io/ktor/network/tls/extensions/PointFormat.kt similarity index 81% rename from ktor-network/ktor-network-tls/jvmAndPosix/src/io/ktor/network/tls/extensions/PointFormat.kt rename to ktor-network/ktor-network-tls/common/src/io/ktor/network/tls/extensions/PointFormat.kt index 609b6c03e6b..9b3e4c54ffd 100644 --- a/ktor-network/ktor-network-tls/jvmAndPosix/src/io/ktor/network/tls/extensions/PointFormat.kt +++ b/ktor-network/ktor-network-tls/common/src/io/ktor/network/tls/extensions/PointFormat.kt @@ -1,11 +1,9 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.network.tls.extensions -import kotlin.native.concurrent.* - /** * Elliptic curve point format * @property code numeric point format code diff --git a/ktor-network/ktor-network-tls/jvmAndPosix/src/io/ktor/network/tls/extensions/SignatureAlgorithm.kt b/ktor-network/ktor-network-tls/common/src/io/ktor/network/tls/extensions/SignatureAlgorithm.kt similarity index 96% rename from ktor-network/ktor-network-tls/jvmAndPosix/src/io/ktor/network/tls/extensions/SignatureAlgorithm.kt rename to ktor-network/ktor-network-tls/common/src/io/ktor/network/tls/extensions/SignatureAlgorithm.kt index d1a700860fe..f62b86a09c1 100644 --- a/ktor-network/ktor-network-tls/jvmAndPosix/src/io/ktor/network/tls/extensions/SignatureAlgorithm.kt +++ b/ktor-network/ktor-network-tls/common/src/io/ktor/network/tls/extensions/SignatureAlgorithm.kt @@ -1,6 +1,6 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.network.tls.extensions diff --git a/ktor-network/ktor-network-tls/jvmAndPosix/src/io/ktor/network/tls/extensions/TLSExtension.kt b/ktor-network/ktor-network-tls/common/src/io/ktor/network/tls/extensions/TLSExtension.kt similarity index 86% rename from ktor-network/ktor-network-tls/jvmAndPosix/src/io/ktor/network/tls/extensions/TLSExtension.kt rename to ktor-network/ktor-network-tls/common/src/io/ktor/network/tls/extensions/TLSExtension.kt index b009c4748ec..d5b5f4e8a6b 100644 --- a/ktor-network/ktor-network-tls/jvmAndPosix/src/io/ktor/network/tls/extensions/TLSExtension.kt +++ b/ktor-network/ktor-network-tls/common/src/io/ktor/network/tls/extensions/TLSExtension.kt @@ -1,6 +1,6 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.network.tls.extensions diff --git a/ktor-network/ktor-network-tls/jvm/src/io/ktor/network/tls/TLSClientHandshake.kt b/ktor-network/ktor-network-tls/jvm/src/io/ktor/network/tls/TLSClientHandshake.kt index a10fe5caf7b..e47b551ca9b 100644 --- a/ktor-network/ktor-network-tls/jvm/src/io/ktor/network/tls/TLSClientHandshake.kt +++ b/ktor-network/ktor-network-tls/jvm/src/io/ktor/network/tls/TLSClientHandshake.kt @@ -1,6 +1,6 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.network.tls @@ -21,6 +21,7 @@ import javax.crypto.* import javax.crypto.spec.* import javax.security.auth.x500.* import kotlin.coroutines.* +import kotlin.use internal class TLSClientHandshake( rawInput: ByteReadChannel, diff --git a/ktor-network/ktor-network-tls/jvmAndPosix/src/io/ktor/network/tls/TLSConfig.kt b/ktor-network/ktor-network-tls/jvmAndPosix/src/io/ktor/network/tls/TLSConfig.kt deleted file mode 100644 index ca84d859e16..00000000000 --- a/ktor-network/ktor-network-tls/jvmAndPosix/src/io/ktor/network/tls/TLSConfig.kt +++ /dev/null @@ -1,7 +0,0 @@ -/* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ - -package io.ktor.network.tls - -public expect class TLSConfig diff --git a/ktor-network/ktor-network-tls/ktor-network-tls-certificates/jvm/src/io/ktor/network/tls/certificates/Certificates.kt b/ktor-network/ktor-network-tls/ktor-network-tls-certificates/jvm/src/io/ktor/network/tls/certificates/Certificates.kt index 08d306311be..5c7c295d778 100644 --- a/ktor-network/ktor-network-tls/ktor-network-tls-certificates/jvm/src/io/ktor/network/tls/certificates/Certificates.kt +++ b/ktor-network/ktor-network-tls/ktor-network-tls-certificates/jvm/src/io/ktor/network/tls/certificates/Certificates.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.network.tls.certificates @@ -23,6 +23,7 @@ import javax.security.auth.x500.* import kotlin.time.* import kotlin.time.Duration import kotlin.time.Duration.Companion.days +import kotlin.use internal val DEFAULT_PRINCIPAL = X500Principal("CN=localhost, OU=Kotlin, O=JetBrains, C=RU") private val DEFAULT_CA_PRINCIPAL = X500Principal("CN=localhostCA, OU=Kotlin, O=JetBrains, C=RU") diff --git a/ktor-network/ktor-network-tls/ktor-network-tls-certificates/jvm/src/io/ktor/network/tls/certificates/builders.kt b/ktor-network/ktor-network-tls/ktor-network-tls-certificates/jvm/src/io/ktor/network/tls/certificates/builders.kt index b8895edcb4c..ebd9ddf7694 100644 --- a/ktor-network/ktor-network-tls/ktor-network-tls-certificates/jvm/src/io/ktor/network/tls/certificates/builders.kt +++ b/ktor-network/ktor-network-tls/ktor-network-tls-certificates/jvm/src/io/ktor/network/tls/certificates/builders.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.network.tls.certificates @@ -7,7 +7,6 @@ package io.ktor.network.tls.certificates import io.ktor.network.tls.* import io.ktor.network.tls.extensions.* import io.ktor.util.* -import io.ktor.utils.io.core.* import java.io.* import java.net.* import java.security.* diff --git a/ktor-network/ktor-network-tls/posix/src/io/ktor/network/tls/CipherSuitesNative.kt b/ktor-network/ktor-network-tls/nonJvm/src/io/ktor/network/tls/CipherSuites.nonJvm.kt similarity index 100% rename from ktor-network/ktor-network-tls/posix/src/io/ktor/network/tls/CipherSuitesNative.kt rename to ktor-network/ktor-network-tls/nonJvm/src/io/ktor/network/tls/CipherSuites.nonJvm.kt diff --git a/ktor-network/ktor-network-tls/posix/src/io/ktor/network/tls/TLSNative.kt b/ktor-network/ktor-network-tls/nonJvm/src/io/ktor/network/tls/TLS.nonJvm.kt similarity index 100% rename from ktor-network/ktor-network-tls/posix/src/io/ktor/network/tls/TLSNative.kt rename to ktor-network/ktor-network-tls/nonJvm/src/io/ktor/network/tls/TLS.nonJvm.kt diff --git a/ktor-network/ktor-network-tls/posix/src/io/ktor/network/tls/TLSClientSessionNative.kt b/ktor-network/ktor-network-tls/nonJvm/src/io/ktor/network/tls/TLSClientSession.nonJvm.kt similarity index 100% rename from ktor-network/ktor-network-tls/posix/src/io/ktor/network/tls/TLSClientSessionNative.kt rename to ktor-network/ktor-network-tls/nonJvm/src/io/ktor/network/tls/TLSClientSession.nonJvm.kt diff --git a/ktor-network/ktor-network-tls/posix/src/io/ktor/network/tls/TLSConfigNative.kt b/ktor-network/ktor-network-tls/nonJvm/src/io/ktor/network/tls/TLSConfig.nonJvm.kt similarity index 100% rename from ktor-network/ktor-network-tls/posix/src/io/ktor/network/tls/TLSConfigNative.kt rename to ktor-network/ktor-network-tls/nonJvm/src/io/ktor/network/tls/TLSConfig.nonJvm.kt diff --git a/ktor-network/ktor-network-tls/posix/src/io/ktor/network/tls/TLSConfigBuilderNative.kt b/ktor-network/ktor-network-tls/nonJvm/src/io/ktor/network/tls/TLSConfigBuilder.nonJvm.kt similarity index 100% rename from ktor-network/ktor-network-tls/posix/src/io/ktor/network/tls/TLSConfigBuilderNative.kt rename to ktor-network/ktor-network-tls/nonJvm/src/io/ktor/network/tls/TLSConfigBuilder.nonJvm.kt diff --git a/ktor-network/macos/test/io/ktor/network/sockets/tests/TestUtilsMacos.kt b/ktor-network/macos/test/io/ktor/network/sockets/tests/TestUtilsMacos.kt deleted file mode 100644 index a283858bbb3..00000000000 --- a/ktor-network/macos/test/io/ktor/network/sockets/tests/TestUtilsMacos.kt +++ /dev/null @@ -1,7 +0,0 @@ -/* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. - */ - -package io.ktor.network.sockets.tests - -internal actual fun Any.supportsUnixDomainSockets(): Boolean = true diff --git a/ktor-network/posix/src/io/ktor/network/sockets/SocketAddressNative.kt b/ktor-network/nonJvm/src/io/ktor/network/sockets/SocketAddress.nonJvm.kt similarity index 100% rename from ktor-network/posix/src/io/ktor/network/sockets/SocketAddressNative.kt rename to ktor-network/nonJvm/src/io/ktor/network/sockets/SocketAddress.nonJvm.kt diff --git a/ktor-network/posix/src/io/ktor/network/sockets/SocketTimeoutException.kt b/ktor-network/nonJvm/src/io/ktor/network/sockets/SocketTimeoutException.kt similarity index 51% rename from ktor-network/posix/src/io/ktor/network/sockets/SocketTimeoutException.kt rename to ktor-network/nonJvm/src/io/ktor/network/sockets/SocketTimeoutException.kt index 7bbab1cc4cc..ca54b0fb353 100644 --- a/ktor-network/posix/src/io/ktor/network/sockets/SocketTimeoutException.kt +++ b/ktor-network/nonJvm/src/io/ktor/network/sockets/SocketTimeoutException.kt @@ -1,13 +1,11 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.network.sockets -import io.ktor.utils.io.errors.* -import kotlinx.io.IOException +import kotlinx.io.* -@Suppress("EXPECT_WITHOUT_ACTUAL") public actual class SocketTimeoutException( message: String, cause: Throwable? diff --git a/ktor-network/posix/src/io/ktor/network/selector/SelectorManager.kt b/ktor-network/posix/src/io/ktor/network/selector/SelectorManager.kt index 55746637530..fbc2cb85f52 100644 --- a/ktor-network/posix/src/io/ktor/network/selector/SelectorManager.kt +++ b/ktor-network/posix/src/io/ktor/network/selector/SelectorManager.kt @@ -38,7 +38,6 @@ public actual interface SelectorManager : CoroutineScope, Closeable { /** * Select interest kind */ -@Suppress("KDocMissingDocumentation", "NO_EXPLICIT_VISIBILITY_IN_API_MODE_WARNING") public actual enum class SelectInterest { READ, WRITE, ACCEPT, CONNECT; diff --git a/ktor-network/posix/src/io/ktor/network/sockets/ConnectUtilsNative.kt b/ktor-network/posix/src/io/ktor/network/sockets/ConnectUtilsNative.kt index ec9c0f4e3bb..c54d7cd90aa 100644 --- a/ktor-network/posix/src/io/ktor/network/sockets/ConnectUtilsNative.kt +++ b/ktor-network/posix/src/io/ktor/network/sockets/ConnectUtilsNative.kt @@ -1,6 +1,6 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.network.sockets @@ -14,7 +14,7 @@ import platform.posix.* private const val DEFAULT_BACKLOG_SIZE = 50 @OptIn(UnsafeNumber::class, ExperimentalForeignApi::class) -internal actual suspend fun connect( +internal actual suspend fun tcpConnect( selector: SelectorManager, remoteAddress: SocketAddress, socketOptions: SocketOptions.TCPClientSocketOptions @@ -79,7 +79,7 @@ internal actual suspend fun connect( } @OptIn(UnsafeNumber::class, ExperimentalForeignApi::class) -internal actual fun bind( +internal actual suspend fun tcpBind( selector: SelectorManager, localAddress: SocketAddress?, socketOptions: SocketOptions.AcceptorOptions diff --git a/ktor-network/posix/src/io/ktor/network/sockets/UDPSocketBuilderNative.kt b/ktor-network/posix/src/io/ktor/network/sockets/UDPSocketBuilderNative.kt index eb4fd26ec59..cfb45545d9d 100644 --- a/ktor-network/posix/src/io/ktor/network/sockets/UDPSocketBuilderNative.kt +++ b/ktor-network/posix/src/io/ktor/network/sockets/UDPSocketBuilderNative.kt @@ -10,7 +10,7 @@ import kotlinx.cinterop.* import platform.posix.* @OptIn(UnsafeNumber::class, ExperimentalForeignApi::class) -internal actual fun connectUDP( +internal actual suspend fun udpConnect( selector: SelectorManager, remoteAddress: SocketAddress, localAddress: SocketAddress?, @@ -51,7 +51,7 @@ internal actual fun connectUDP( } @OptIn(UnsafeNumber::class, ExperimentalForeignApi::class) -internal actual fun bindUDP( +internal actual suspend fun udpBind( selector: SelectorManager, localAddress: SocketAddress?, options: SocketOptions.UDPSocketOptions diff --git a/ktor-network/posix/test/io/ktor/network/sockets/tests/TestUtils.posix.kt b/ktor-network/posix/test/io/ktor/network/sockets/tests/TestUtils.posix.kt new file mode 100644 index 00000000000..df03ca53d52 --- /dev/null +++ b/ktor-network/posix/test/io/ktor/network/sockets/tests/TestUtils.posix.kt @@ -0,0 +1,13 @@ +/* + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + +package io.ktor.network.sockets.tests + +import kotlin.experimental.* + +@OptIn(ExperimentalNativeApi::class) +internal actual fun Any.supportsUnixDomainSockets(): Boolean = when (Platform.osFamily) { + OsFamily.MACOSX, OsFamily.LINUX -> true + else -> false +} diff --git a/ktor-network/posix/test/io/ktor/network/sockets/tests/TestUtilsNix.kt b/ktor-network/posix/test/io/ktor/network/sockets/tests/TestUtilsNix.kt deleted file mode 100644 index d1d3d99310b..00000000000 --- a/ktor-network/posix/test/io/ktor/network/sockets/tests/TestUtilsNix.kt +++ /dev/null @@ -1,13 +0,0 @@ -/* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. - */ - -package io.ktor.network.sockets.tests - -import platform.posix.* - -internal actual fun createTempFilePath(basename: String): String = "/tmp/$basename" - -internal actual fun removeFile(path: String) { - if (remove(path) != 0) error("Failed to delete socket node") -} diff --git a/ktor-network/tvos/test/io/ktor/network/sockets/tests/TestUtilsTvos.kt b/ktor-network/tvos/test/io/ktor/network/sockets/tests/TestUtilsTvos.kt deleted file mode 100644 index 5964f2a095f..00000000000 --- a/ktor-network/tvos/test/io/ktor/network/sockets/tests/TestUtilsTvos.kt +++ /dev/null @@ -1,7 +0,0 @@ -/* - * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. - */ - -package io.ktor.network.sockets.tests - -internal actual fun Any.supportsUnixDomainSockets(): Boolean = false diff --git a/ktor-network/wasmJs/src/io/ktor/network/sockets/nodejs/node.net.wasmJs.kt b/ktor-network/wasmJs/src/io/ktor/network/sockets/nodejs/node.net.wasmJs.kt new file mode 100644 index 00000000000..0b889f54ed0 --- /dev/null +++ b/ktor-network/wasmJs/src/io/ktor/network/sockets/nodejs/node.net.wasmJs.kt @@ -0,0 +1,65 @@ +/* + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + +package io.ktor.network.sockets.nodejs + +import io.ktor.network.sockets.* +import org.khronos.webgl.* + +internal actual fun nodeNet(): NodeNet? = js("eval('require')('node:net')") + +internal actual fun TcpCreateConnectionOptions( + block: TcpCreateConnectionOptions.() -> Unit +): TcpCreateConnectionOptions = createObject(block) + +internal actual fun IpcCreateConnectionOptions( + block: IpcCreateConnectionOptions.() -> Unit +): IpcCreateConnectionOptions = createObject(block) + +internal actual fun CreateServerOptions( + block: CreateServerOptions.() -> Unit +): CreateServerOptions = createObject(block) + +internal actual fun ServerListenOptions( + block: ServerListenOptions.() -> Unit +): ServerListenOptions = createObject(block) + +internal actual fun JsError.toThrowable(): Throwable = Error(message) +internal actual fun Throwable.toJsError(): JsError? = jsError(message) + +private fun jsError(message: String?): JsError = js("(new Error(message))") + +internal actual fun ByteArray.toJsBuffer(fromIndex: Int, toIndex: Int): JsBuffer { + val array = Int8Array(toIndex - fromIndex) + repeat(array.length) { index -> + array[index] = this[fromIndex + index] + } + return justCast(array) +} + +internal actual fun JsBuffer.toByteArray(): ByteArray { + val array = Int8Array(justCast(this)) + val bytes = ByteArray(array.length) + + repeat(array.length) { index -> + bytes[index] = array[index] + } + return bytes +} + +internal actual fun ServerLocalAddressInfo.toSocketAddress(): SocketAddress { + if (jsTypeOf(justCast(this)) == "string") return UnixSocketAddress(justCast(this).toString()) + val info = justCast(this) + return InetSocketAddress(info.address, info.port) +} + +private fun jsTypeOf(obj: JsAny): String = js("(typeof obj)") + +private fun createJsObject(): JsAny = js("({})") + +private fun createObject(block: T.() -> Unit): T = createJsObject().unsafeCast().apply(block) + +// overcomes the issue that expect declarations are not extending `JsAny` +@Suppress("UNCHECKED_CAST") +private fun justCast(obj: Any): T = obj as T diff --git a/ktor-network/watchos/test/io/ktor/network/sockets/tests/TestUtilsWatchos.kt b/ktor-network/watchos/test/io/ktor/network/sockets/tests/TestUtilsWatchos.kt deleted file mode 100644 index 5964f2a095f..00000000000 --- a/ktor-network/watchos/test/io/ktor/network/sockets/tests/TestUtilsWatchos.kt +++ /dev/null @@ -1,7 +0,0 @@ -/* - * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. - */ - -package io.ktor.network.sockets.tests - -internal actual fun Any.supportsUnixDomainSockets(): Boolean = false diff --git a/ktor-server/ktor-server-cio/api/ktor-server-cio.klib.api b/ktor-server/ktor-server-cio/api/ktor-server-cio.klib.api index acb7cd04729..4a92f30326d 100644 --- a/ktor-server/ktor-server-cio/api/ktor-server-cio.klib.api +++ b/ktor-server/ktor-server-cio/api/ktor-server-cio.klib.api @@ -1,5 +1,5 @@ // Klib ABI Dump -// Targets: [androidNativeArm32, androidNativeArm64, androidNativeX64, androidNativeX86, iosArm64, iosSimulatorArm64, iosX64, linuxArm64, linuxX64, macosArm64, macosX64, mingwX64, tvosArm64, tvosSimulatorArm64, tvosX64, watchosArm32, watchosArm64, watchosDeviceArm64, watchosSimulatorArm64, watchosX64] +// Targets: [androidNativeArm32, androidNativeArm64, androidNativeX64, androidNativeX86, iosArm64, iosSimulatorArm64, iosX64, js, linuxArm64, linuxX64, macosArm64, macosX64, mingwX64, tvosArm64, tvosSimulatorArm64, tvosX64, wasmJs, watchosArm32, watchosArm64, watchosDeviceArm64, watchosSimulatorArm64, watchosX64] // Rendering settings: // - Signature version: 2 // - Show manifest properties: true diff --git a/ktor-server/ktor-server-cio/build.gradle.kts b/ktor-server/ktor-server-cio/build.gradle.kts index 61445613e95..676c56147af 100644 --- a/ktor-server/ktor-server-cio/build.gradle.kts +++ b/ktor-server/ktor-server-cio/build.gradle.kts @@ -1,7 +1,11 @@ +/* + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + description = "" kotlin.sourceSets { - jvmAndPosixMain { + commonMain { dependencies { api(project(":ktor-server:ktor-server-core")) api(project(":ktor-http:ktor-http-cio")) @@ -9,16 +13,15 @@ kotlin.sourceSets { api(project(":ktor-network")) } } - jvmAndPosixTest { + commonTest { dependencies { - api(project(":ktor-server:ktor-server-core")) api(project(":ktor-client:ktor-client-cio")) api(project(":ktor-server:ktor-server-test-suites")) + api(project(":ktor-server:ktor-server-test-base")) } } jvmTest { dependencies { - api(project(":ktor-server:ktor-server-test-base")) api(project(":ktor-server:ktor-server-core", configuration = "testOutput")) api(libs.logback.classic) } diff --git a/ktor-server/ktor-server-cio/jvmAndPosix/src/io/ktor/server/cio/CIO.kt b/ktor-server/ktor-server-cio/common/src/io/ktor/server/cio/CIO.kt similarity index 100% rename from ktor-server/ktor-server-cio/jvmAndPosix/src/io/ktor/server/cio/CIO.kt rename to ktor-server/ktor-server-cio/common/src/io/ktor/server/cio/CIO.kt diff --git a/ktor-server/ktor-server-cio/jvmAndPosix/src/io/ktor/server/cio/CIOApplicationCall.kt b/ktor-server/ktor-server-cio/common/src/io/ktor/server/cio/CIOApplicationCall.kt similarity index 100% rename from ktor-server/ktor-server-cio/jvmAndPosix/src/io/ktor/server/cio/CIOApplicationCall.kt rename to ktor-server/ktor-server-cio/common/src/io/ktor/server/cio/CIOApplicationCall.kt diff --git a/ktor-server/ktor-server-cio/jvmAndPosix/src/io/ktor/server/cio/CIOApplicationEngine.kt b/ktor-server/ktor-server-cio/common/src/io/ktor/server/cio/CIOApplicationEngine.kt similarity index 99% rename from ktor-server/ktor-server-cio/jvmAndPosix/src/io/ktor/server/cio/CIOApplicationEngine.kt rename to ktor-server/ktor-server-cio/common/src/io/ktor/server/cio/CIOApplicationEngine.kt index e963ec29cf9..f7a62155cae 100644 --- a/ktor-server/ktor-server-cio/jvmAndPosix/src/io/ktor/server/cio/CIOApplicationEngine.kt +++ b/ktor-server/ktor-server-cio/common/src/io/ktor/server/cio/CIOApplicationEngine.kt @@ -76,7 +76,7 @@ public class CIOApplicationEngine( return this } - override fun start(wait: Boolean): ApplicationEngine = runBlocking { startSuspend(wait) } + override fun start(wait: Boolean): ApplicationEngine = runBlockingBridge { startSuspend(wait) } override suspend fun stopSuspend(gracePeriodMillis: Long, timeoutMillis: Long) { stopRequest.complete() @@ -96,7 +96,7 @@ public class CIOApplicationEngine( } } - override fun stop(gracePeriodMillis: Long, timeoutMillis: Long): Unit = runBlocking { + override fun stop(gracePeriodMillis: Long, timeoutMillis: Long): Unit = runBlockingBridge { stopSuspend(gracePeriodMillis, timeoutMillis) } diff --git a/ktor-server/ktor-server-cio/jvmAndPosix/src/io/ktor/server/cio/CIOApplicationRequest.kt b/ktor-server/ktor-server-cio/common/src/io/ktor/server/cio/CIOApplicationRequest.kt similarity index 100% rename from ktor-server/ktor-server-cio/jvmAndPosix/src/io/ktor/server/cio/CIOApplicationRequest.kt rename to ktor-server/ktor-server-cio/common/src/io/ktor/server/cio/CIOApplicationRequest.kt diff --git a/ktor-server/ktor-server-cio/jvmAndPosix/src/io/ktor/server/cio/CIOApplicationResponse.kt b/ktor-server/ktor-server-cio/common/src/io/ktor/server/cio/CIOApplicationResponse.kt similarity index 100% rename from ktor-server/ktor-server-cio/jvmAndPosix/src/io/ktor/server/cio/CIOApplicationResponse.kt rename to ktor-server/ktor-server-cio/common/src/io/ktor/server/cio/CIOApplicationResponse.kt diff --git a/ktor-server/ktor-server-cio/jvmAndPosix/src/io/ktor/server/cio/EngineMain.kt b/ktor-server/ktor-server-cio/common/src/io/ktor/server/cio/EngineMain.kt similarity index 100% rename from ktor-server/ktor-server-cio/jvmAndPosix/src/io/ktor/server/cio/EngineMain.kt rename to ktor-server/ktor-server-cio/common/src/io/ktor/server/cio/EngineMain.kt diff --git a/ktor-server/ktor-server-cio/jvmAndPosix/src/io/ktor/server/cio/HttpServer.kt b/ktor-server/ktor-server-cio/common/src/io/ktor/server/cio/HttpServer.kt similarity index 100% rename from ktor-server/ktor-server-cio/jvmAndPosix/src/io/ktor/server/cio/HttpServer.kt rename to ktor-server/ktor-server-cio/common/src/io/ktor/server/cio/HttpServer.kt diff --git a/ktor-server/ktor-server-cio/jvmAndPosix/src/io/ktor/server/cio/Pipeline.kt b/ktor-server/ktor-server-cio/common/src/io/ktor/server/cio/Pipeline.kt similarity index 100% rename from ktor-server/ktor-server-cio/jvmAndPosix/src/io/ktor/server/cio/Pipeline.kt rename to ktor-server/ktor-server-cio/common/src/io/ktor/server/cio/Pipeline.kt diff --git a/ktor-server/ktor-server-cio/jvmAndPosix/src/io/ktor/server/cio/backend/HttpServer.kt b/ktor-server/ktor-server-cio/common/src/io/ktor/server/cio/backend/HttpServer.kt similarity index 87% rename from ktor-server/ktor-server-cio/jvmAndPosix/src/io/ktor/server/cio/backend/HttpServer.kt rename to ktor-server/ktor-server-cio/common/src/io/ktor/server/cio/backend/HttpServer.kt index f24df8a15fd..d83a63d8d24 100644 --- a/ktor-server/ktor-server-cio/jvmAndPosix/src/io/ktor/server/cio/backend/HttpServer.kt +++ b/ktor-server/ktor-server-cio/common/src/io/ktor/server/cio/backend/HttpServer.kt @@ -1,6 +1,6 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.server.cio.backend @@ -11,12 +11,12 @@ import io.ktor.server.engine.* import io.ktor.server.engine.internal.* import io.ktor.util.logging.* import io.ktor.utils.io.* -import io.ktor.utils.io.core.* -import io.ktor.utils.io.errors.* import kotlinx.coroutines.* -import kotlinx.io.IOException +import kotlinx.io.* import kotlin.time.Duration.Companion.seconds +private val LOGGER = KtorSimpleLogger("io.ktor.server.cio.HttpServer") + /** * Start a http server with [settings] invoking [handler] for every request */ @@ -39,10 +39,6 @@ public fun CoroutineScope.httpServer( val selector = SelectorManager(coroutineContext) val timeout = settings.connectionIdleTimeoutSeconds.seconds - val logger = KtorSimpleLogger( - HttpServer::class.simpleName ?: HttpServer::class.qualifiedName ?: HttpServer::class.toString() - ) - val acceptJob = launch(serverJob + CoroutineName("accept-${settings.port}")) { aSocket(selector).tcp().bind(settings.host, settings.port) { reuseAddress = settings.reuseAddress @@ -50,7 +46,7 @@ public fun CoroutineScope.httpServer( socket.complete(server) val exceptionHandler = coroutineContext[CoroutineExceptionHandler] - ?: DefaultUncaughtExceptionHandler(logger) + ?: DefaultUncaughtExceptionHandler(LOGGER) val connectionScope = CoroutineScope( coroutineContext + diff --git a/ktor-server/ktor-server-cio/jvmAndPosix/src/io/ktor/server/cio/backend/ServerIncomingConnection.kt b/ktor-server/ktor-server-cio/common/src/io/ktor/server/cio/backend/ServerIncomingConnection.kt similarity index 100% rename from ktor-server/ktor-server-cio/jvmAndPosix/src/io/ktor/server/cio/backend/ServerIncomingConnection.kt rename to ktor-server/ktor-server-cio/common/src/io/ktor/server/cio/backend/ServerIncomingConnection.kt diff --git a/ktor-server/ktor-server-cio/jvmAndPosix/src/io/ktor/server/cio/backend/ServerPipeline.kt b/ktor-server/ktor-server-cio/common/src/io/ktor/server/cio/backend/ServerPipeline.kt similarity index 100% rename from ktor-server/ktor-server-cio/jvmAndPosix/src/io/ktor/server/cio/backend/ServerPipeline.kt rename to ktor-server/ktor-server-cio/common/src/io/ktor/server/cio/backend/ServerPipeline.kt diff --git a/ktor-server/ktor-server-cio/jvmAndPosix/src/io/ktor/server/cio/backend/ServerRequestScope.kt b/ktor-server/ktor-server-cio/common/src/io/ktor/server/cio/backend/ServerRequestScope.kt similarity index 100% rename from ktor-server/ktor-server-cio/jvmAndPosix/src/io/ktor/server/cio/backend/ServerRequestScope.kt rename to ktor-server/ktor-server-cio/common/src/io/ktor/server/cio/backend/ServerRequestScope.kt diff --git a/ktor-server/ktor-server-cio/jvmAndPosix/src/io/ktor/server/cio/backend/SocketAddressUtils.kt b/ktor-server/ktor-server-cio/common/src/io/ktor/server/cio/backend/SocketAddressUtils.kt similarity index 100% rename from ktor-server/ktor-server-cio/jvmAndPosix/src/io/ktor/server/cio/backend/SocketAddressUtils.kt rename to ktor-server/ktor-server-cio/common/src/io/ktor/server/cio/backend/SocketAddressUtils.kt diff --git a/ktor-server/ktor-server-cio/jvmAndPosix/src/io/ktor/server/cio/internal/CoroutineUtils.kt b/ktor-server/ktor-server-cio/common/src/io/ktor/server/cio/internal/CoroutineUtils.kt similarity index 75% rename from ktor-server/ktor-server-cio/jvmAndPosix/src/io/ktor/server/cio/internal/CoroutineUtils.kt rename to ktor-server/ktor-server-cio/common/src/io/ktor/server/cio/internal/CoroutineUtils.kt index b0443579790..e2c21a59efe 100644 --- a/ktor-server/ktor-server-cio/jvmAndPosix/src/io/ktor/server/cio/internal/CoroutineUtils.kt +++ b/ktor-server/ktor-server-cio/common/src/io/ktor/server/cio/internal/CoroutineUtils.kt @@ -7,3 +7,5 @@ package io.ktor.server.cio.internal import kotlinx.coroutines.* internal expect val Dispatchers.IOBridge: CoroutineDispatcher + +internal expect fun runBlockingBridge(block: suspend CoroutineScope.() -> T): T diff --git a/ktor-server/ktor-server-cio/jvmAndPosix/test/io/ktor/tests/server/cio/CIOConnectionPointTest.kt b/ktor-server/ktor-server-cio/common/test/io/ktor/tests/server/cio/CIOConnectionPointTest.kt similarity index 100% rename from ktor-server/ktor-server-cio/jvmAndPosix/test/io/ktor/tests/server/cio/CIOConnectionPointTest.kt rename to ktor-server/ktor-server-cio/common/test/io/ktor/tests/server/cio/CIOConnectionPointTest.kt diff --git a/ktor-server/ktor-server-cio/jvmAndPosix/test/io/ktor/tests/server/cio/CIOEngineTest.kt b/ktor-server/ktor-server-cio/common/test/io/ktor/tests/server/cio/CIOEngineTest.kt similarity index 98% rename from ktor-server/ktor-server-cio/jvmAndPosix/test/io/ktor/tests/server/cio/CIOEngineTest.kt rename to ktor-server/ktor-server-cio/common/test/io/ktor/tests/server/cio/CIOEngineTest.kt index 32ee17291db..da08b330b05 100644 --- a/ktor-server/ktor-server-cio/jvmAndPosix/test/io/ktor/tests/server/cio/CIOEngineTest.kt +++ b/ktor-server/ktor-server-cio/common/test/io/ktor/tests/server/cio/CIOEngineTest.kt @@ -1,8 +1,8 @@ -// ktlint-disable filename /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ +// ktlint-disable filename package io.ktor.tests.server.cio import io.ktor.client.statement.* @@ -16,7 +16,6 @@ import io.ktor.server.response.* import io.ktor.server.routing.* import io.ktor.server.testing.suites.* import io.ktor.utils.io.* -import io.ktor.utils.io.core.* import kotlin.test.* class CIOHttpServerTest : HttpServerCommonTestSuite(CIO) { diff --git a/ktor-server/ktor-server-cio/jvmAndPosix/test/io/ktor/tests/server/cio/CIOWebSocketTest.kt b/ktor-server/ktor-server-cio/common/test/io/ktor/tests/server/cio/CIOWebSocketTest.kt similarity index 100% rename from ktor-server/ktor-server-cio/jvmAndPosix/test/io/ktor/tests/server/cio/CIOWebSocketTest.kt rename to ktor-server/ktor-server-cio/common/test/io/ktor/tests/server/cio/CIOWebSocketTest.kt diff --git a/ktor-server/ktor-server-cio/jvmAndPosix/test/io/ktor/tests/server/cio/RAWExample.kt b/ktor-server/ktor-server-cio/common/test/io/ktor/tests/server/cio/RAWExample.kt similarity index 96% rename from ktor-server/ktor-server-cio/jvmAndPosix/test/io/ktor/tests/server/cio/RAWExample.kt rename to ktor-server/ktor-server-cio/common/test/io/ktor/tests/server/cio/RAWExample.kt index 08fb3257385..4955c3fc5a9 100644 --- a/ktor-server/ktor-server-cio/jvmAndPosix/test/io/ktor/tests/server/cio/RAWExample.kt +++ b/ktor-server/ktor-server-cio/common/test/io/ktor/tests/server/cio/RAWExample.kt @@ -8,6 +8,7 @@ import io.ktor.http.* import io.ktor.http.cio.* import io.ktor.server.cio.* import io.ktor.server.cio.backend.* +import io.ktor.server.cio.internal.* import io.ktor.util.date.* import io.ktor.utils.io.* import io.ktor.utils.io.core.* @@ -29,7 +30,7 @@ private val notFound404_11 = RequestResponseBuilder().apply { * This is just an example demonstrating how to create CIO low-level http server */ @OptIn(DelicateCoroutinesApi::class) -fun main() { +fun example() { val settings = HttpServerSettings() GlobalScope.launch { @@ -64,7 +65,7 @@ fun main() { } ) - runBlocking { + runBlockingBridge { server.rootServerJob.join() } } diff --git a/ktor-server/ktor-server-cio/jvmAndPosix/test/io/ktor/tests/server/cio/TestConnectorInterfaceUsed.kt b/ktor-server/ktor-server-cio/common/test/io/ktor/tests/server/cio/TestConnectorInterfaceUsed.kt similarity index 100% rename from ktor-server/ktor-server-cio/jvmAndPosix/test/io/ktor/tests/server/cio/TestConnectorInterfaceUsed.kt rename to ktor-server/ktor-server-cio/common/test/io/ktor/tests/server/cio/TestConnectorInterfaceUsed.kt diff --git a/ktor-server/ktor-server-cio/jsAndWasmShared/src/io/ktor/server/cio/internal/CoroutineUtils.jsAndWasmShared.kt b/ktor-server/ktor-server-cio/jsAndWasmShared/src/io/ktor/server/cio/internal/CoroutineUtils.jsAndWasmShared.kt new file mode 100644 index 00000000000..82f9fc6eb2c --- /dev/null +++ b/ktor-server/ktor-server-cio/jsAndWasmShared/src/io/ktor/server/cio/internal/CoroutineUtils.jsAndWasmShared.kt @@ -0,0 +1,13 @@ +/* + * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + +package io.ktor.server.cio.internal + +import kotlinx.coroutines.* + +internal actual val Dispatchers.IOBridge: CoroutineDispatcher + get() = Default + +internal actual fun runBlockingBridge(block: suspend CoroutineScope.() -> T): T = + error("runBlocking is not supported on JS and WASM") diff --git a/ktor-server/ktor-server-cio/jvm/src/io/ktor/server/cio/internal/CoroutineUtilsJvm.kt b/ktor-server/ktor-server-cio/jvm/src/io/ktor/server/cio/internal/CoroutineUtilsJvm.kt index a41e8ddb60f..ecea0cf1447 100644 --- a/ktor-server/ktor-server-cio/jvm/src/io/ktor/server/cio/internal/CoroutineUtilsJvm.kt +++ b/ktor-server/ktor-server-cio/jvm/src/io/ktor/server/cio/internal/CoroutineUtilsJvm.kt @@ -8,3 +8,5 @@ import kotlinx.coroutines.* internal actual val Dispatchers.IOBridge: CoroutineDispatcher get() = IO + +internal actual fun runBlockingBridge(block: suspend CoroutineScope.() -> T): T = runBlocking(block = block) diff --git a/ktor-server/ktor-server-cio/posix/src/io/ktor/server/cio/backend/SocketAddressUtilsNative.kt b/ktor-server/ktor-server-cio/nonJvm/src/io/ktor/server/cio/backend/SocketAddressUtils.nonJvm.kt similarity index 65% rename from ktor-server/ktor-server-cio/posix/src/io/ktor/server/cio/backend/SocketAddressUtilsNative.kt rename to ktor-server/ktor-server-cio/nonJvm/src/io/ktor/server/cio/backend/SocketAddressUtils.nonJvm.kt index 460a9d176e8..0aea2e82efd 100644 --- a/ktor-server/ktor-server-cio/posix/src/io/ktor/server/cio/backend/SocketAddressUtilsNative.kt +++ b/ktor-server/ktor-server-cio/nonJvm/src/io/ktor/server/cio/backend/SocketAddressUtils.nonJvm.kt @@ -8,6 +8,6 @@ import io.ktor.network.sockets.* import io.ktor.util.network.* internal actual fun SocketAddress.toNetworkAddress(): NetworkAddress { - val inetAddress = this as? InetSocketAddress ?: error("Expected inet socket address") - return NetworkAddress(inetAddress.hostname, inetAddress.port) + check(this is InetSocketAddress) { "Expected inet socket address" } + return NetworkAddress(hostname, port) } diff --git a/ktor-server/ktor-server-cio/posix/src/io/ktor/server/cio/internal/CoroutineUtilsNix.kt b/ktor-server/ktor-server-cio/posix/src/io/ktor/server/cio/internal/CoroutineUtilsNix.kt index a41e8ddb60f..ecea0cf1447 100644 --- a/ktor-server/ktor-server-cio/posix/src/io/ktor/server/cio/internal/CoroutineUtilsNix.kt +++ b/ktor-server/ktor-server-cio/posix/src/io/ktor/server/cio/internal/CoroutineUtilsNix.kt @@ -8,3 +8,5 @@ import kotlinx.coroutines.* internal actual val Dispatchers.IOBridge: CoroutineDispatcher get() = IO + +internal actual fun runBlockingBridge(block: suspend CoroutineScope.() -> T): T = runBlocking(block = block) diff --git a/ktor-server/ktor-server-core/api/ktor-server-core.api b/ktor-server/ktor-server-core/api/ktor-server-core.api index 8e3fa2229d4..ff48e5ac0a4 100644 --- a/ktor-server/ktor-server-core/api/ktor-server-core.api +++ b/ktor-server/ktor-server-core/api/ktor-server-core.api @@ -590,9 +590,13 @@ public final class io/ktor/server/engine/EmbeddedServer { public final fun reload ()V public final fun start (Z)Lio/ktor/server/engine/EmbeddedServer; public static synthetic fun start$default (Lio/ktor/server/engine/EmbeddedServer;ZILjava/lang/Object;)Lio/ktor/server/engine/EmbeddedServer; + public final fun startSuspend (ZLkotlin/coroutines/Continuation;)Ljava/lang/Object; + public static synthetic fun startSuspend$default (Lio/ktor/server/engine/EmbeddedServer;ZLkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; public final fun stop (JJ)V public final fun stop (JJLjava/util/concurrent/TimeUnit;)V public static synthetic fun stop$default (Lio/ktor/server/engine/EmbeddedServer;JJILjava/lang/Object;)V + public final fun stopSuspend (JJLkotlin/coroutines/Continuation;)Ljava/lang/Object; + public static synthetic fun stopSuspend$default (Lio/ktor/server/engine/EmbeddedServer;JJLkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; } public final class io/ktor/server/engine/EmbeddedServerKt { @@ -895,7 +899,9 @@ public final class io/ktor/server/http/content/StaticContentResolutionKt { public final class io/ktor/server/http/content/SuppressionAttributeKt { public static final fun getSuppressionAttribute ()Lio/ktor/util/AttributeKey; public static final fun isCompressionSuppressed (Lio/ktor/server/application/ApplicationCall;)Z + public static final fun isDecompressionSuppressed (Lio/ktor/server/application/ApplicationCall;)Z public static final fun suppressCompression (Lio/ktor/server/application/ApplicationCall;)V + public static final fun suppressDecompression (Lio/ktor/server/application/ApplicationCall;)V } public final class io/ktor/server/logging/LoggingKt { diff --git a/ktor-server/ktor-server-core/api/ktor-server-core.klib.api b/ktor-server/ktor-server-core/api/ktor-server-core.klib.api index 464607d4027..015707e5355 100644 --- a/ktor-server/ktor-server-core/api/ktor-server-core.klib.api +++ b/ktor-server/ktor-server-core/api/ktor-server-core.klib.api @@ -416,6 +416,8 @@ final class <#A: io.ktor.server.engine/ApplicationEngine, #B: io.ktor.server.eng final fun start(kotlin/Boolean = ...): io.ktor.server.engine/EmbeddedServer<#A, #B> // io.ktor.server.engine/EmbeddedServer.start|start(kotlin.Boolean){}[0] final fun stop(kotlin/Long = ..., kotlin/Long = ...) // io.ktor.server.engine/EmbeddedServer.stop|stop(kotlin.Long;kotlin.Long){}[0] + final suspend fun startSuspend(kotlin/Boolean = ...): io.ktor.server.engine/EmbeddedServer<#A, #B> // io.ktor.server.engine/EmbeddedServer.startSuspend|startSuspend(kotlin.Boolean){}[0] + final suspend fun stopSuspend(kotlin/Long = ..., kotlin/Long = ...) // io.ktor.server.engine/EmbeddedServer.stopSuspend|stopSuspend(kotlin.Long;kotlin.Long){}[0] } final class <#A: kotlin/Any, #B: io.ktor.events/EventDefinition<#A>> io.ktor.server.application.hooks/MonitoringEvent : io.ktor.server.application/Hook> { // io.ktor.server.application.hooks/MonitoringEvent|null[0] @@ -697,7 +699,7 @@ final class io.ktor.server.plugins/PayloadTooLargeException : io.ktor.server.plu } final class io.ktor.server.plugins/UnsupportedMediaTypeException : io.ktor.server.plugins/ContentTransformationException, kotlinx.coroutines/CopyableThrowable { // io.ktor.server.plugins/UnsupportedMediaTypeException|null[0] - constructor (io.ktor.http/ContentType) // io.ktor.server.plugins/UnsupportedMediaTypeException.|(io.ktor.http.ContentType){}[0] + constructor (io.ktor.http/ContentType?) // io.ktor.server.plugins/UnsupportedMediaTypeException.|(io.ktor.http.ContentType?){}[0] final fun createCopy(): io.ktor.server.plugins/UnsupportedMediaTypeException // io.ktor.server.plugins/UnsupportedMediaTypeException.createCopy|createCopy(){}[0] } @@ -1637,6 +1639,8 @@ final val io.ktor.server.http.content/SuppressionAttribute // io.ktor.server.htt final fun (): io.ktor.util/AttributeKey // io.ktor.server.http.content/SuppressionAttribute.|(){}[0] final val io.ktor.server.http.content/isCompressionSuppressed // io.ktor.server.http.content/isCompressionSuppressed|@io.ktor.server.application.ApplicationCall{}isCompressionSuppressed[0] final fun (io.ktor.server.application/ApplicationCall).(): kotlin/Boolean // io.ktor.server.http.content/isCompressionSuppressed.|@io.ktor.server.application.ApplicationCall(){}[0] +final val io.ktor.server.http.content/isDecompressionSuppressed // io.ktor.server.http.content/isDecompressionSuppressed|@io.ktor.server.application.ApplicationCall{}isDecompressionSuppressed[0] + final fun (io.ktor.server.application/ApplicationCall).(): kotlin/Boolean // io.ktor.server.http.content/isDecompressionSuppressed.|@io.ktor.server.application.ApplicationCall(){}[0] final val io.ktor.server.logging/mdcProvider // io.ktor.server.logging/mdcProvider|@io.ktor.server.application.Application{}mdcProvider[0] final fun (io.ktor.server.application/Application).(): io.ktor.server.logging/MDCProvider // io.ktor.server.logging/mdcProvider.|@io.ktor.server.application.Application(){}[0] final val io.ktor.server.plugins/MutableOriginConnectionPointKey // io.ktor.server.plugins/MutableOriginConnectionPointKey|{}MutableOriginConnectionPointKey[0] @@ -1672,6 +1676,7 @@ final fun (io.ktor.http/HeadersBuilder).io.ktor.server.response/contentRange(kot final fun (io.ktor.http/URLBuilder.Companion).io.ktor.server.util/createFromCall(io.ktor.server.application/ApplicationCall): io.ktor.http/URLBuilder // io.ktor.server.util/createFromCall|createFromCall@io.ktor.http.URLBuilder.Companion(io.ktor.server.application.ApplicationCall){}[0] final fun (io.ktor.server.application/Application).io.ktor.server.routing/routing(kotlin/Function1): io.ktor.server.routing/RoutingRoot // io.ktor.server.routing/routing|routing@io.ktor.server.application.Application(kotlin.Function1){}[0] final fun (io.ktor.server.application/ApplicationCall).io.ktor.server.http.content/suppressCompression() // io.ktor.server.http.content/suppressCompression|suppressCompression@io.ktor.server.application.ApplicationCall(){}[0] +final fun (io.ktor.server.application/ApplicationCall).io.ktor.server.http.content/suppressDecompression() // io.ktor.server.http.content/suppressDecompression|suppressDecompression@io.ktor.server.application.ApplicationCall(){}[0] final fun (io.ktor.server.application/ApplicationCall).io.ktor.server.http/push(kotlin/Function1) // io.ktor.server.http/push|push@io.ktor.server.application.ApplicationCall(kotlin.Function1){}[0] final fun (io.ktor.server.application/ApplicationCall).io.ktor.server.http/push(kotlin/String) // io.ktor.server.http/push|push@io.ktor.server.application.ApplicationCall(kotlin.String){}[0] final fun (io.ktor.server.application/ApplicationCall).io.ktor.server.http/push(kotlin/String, io.ktor.http/Parameters) // io.ktor.server.http/push|push@io.ktor.server.application.ApplicationCall(kotlin.String;io.ktor.http.Parameters){}[0] diff --git a/ktor-server/ktor-server-core/common/src/io/ktor/server/application/ApplicationPlugin.kt b/ktor-server/ktor-server-core/common/src/io/ktor/server/application/ApplicationPlugin.kt index f38ce7ea430..6f8012d4664 100644 --- a/ktor-server/ktor-server-core/common/src/io/ktor/server/application/ApplicationPlugin.kt +++ b/ktor-server/ktor-server-core/common/src/io/ktor/server/application/ApplicationPlugin.kt @@ -1,6 +1,6 @@ /* -* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. -*/ + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ package io.ktor.server.application @@ -8,7 +8,6 @@ import io.ktor.server.routing.* import io.ktor.util.* import io.ktor.util.internal.* import io.ktor.util.pipeline.* -import io.ktor.utils.io.core.* import kotlinx.coroutines.* /** @@ -230,7 +229,7 @@ public fun , B : Any, F : Any> A.uninstall( public fun , F : Any> A.uninstallPlugin(key: AttributeKey) { val registry = attributes.getOrNull(pluginRegistryKey) ?: return val instance = registry.getOrNull(key) ?: return - if (instance is Closeable) { + if (instance is AutoCloseable) { instance.close() } registry.remove(key) diff --git a/ktor-server/ktor-server-core/common/src/io/ktor/server/application/KtorCallContexts.kt b/ktor-server/ktor-server-core/common/src/io/ktor/server/application/KtorCallContexts.kt index 606b1c85d63..75dbd7241cd 100644 --- a/ktor-server/ktor-server-core/common/src/io/ktor/server/application/KtorCallContexts.kt +++ b/ktor-server/ktor-server-core/common/src/io/ktor/server/application/KtorCallContexts.kt @@ -58,7 +58,6 @@ public class OnCallReceiveContext internal constructor( public suspend fun transformBody(transform: suspend TransformBodyContext.(body: ByteReadChannel) -> Any) { val receiveBody = context.subject as? ByteReadChannel ?: return val typeInfo = context.call.receiveType - if (typeInfo == typeInfo()) return val transformContext = TransformBodyContext(typeInfo) context.subject = transformContext.transform(receiveBody) diff --git a/ktor-server/ktor-server-core/common/src/io/ktor/server/engine/EmbeddedServer.kt b/ktor-server/ktor-server-core/common/src/io/ktor/server/engine/EmbeddedServer.kt index 36138c1f71c..ff05ff5ddcf 100644 --- a/ktor-server/ktor-server-core/common/src/io/ktor/server/engine/EmbeddedServer.kt +++ b/ktor-server/ktor-server-core/common/src/io/ktor/server/engine/EmbeddedServer.kt @@ -6,6 +6,7 @@ package io.ktor.server.engine import io.ktor.events.* import io.ktor.server.application.* +import io.ktor.server.engine.internal.* import io.ktor.util.logging.* import kotlinx.coroutines.* import kotlin.coroutines.* @@ -34,10 +35,17 @@ public expect class EmbeddedServer + public suspend fun startSuspend(wait: Boolean = false): EmbeddedServer + public fun stop( gracePeriodMillis: Long = engineConfig.shutdownGracePeriod, timeoutMillis: Long = engineConfig.shutdownGracePeriod ) + + public suspend fun stopSuspend( + gracePeriodMillis: Long = engineConfig.shutdownGracePeriod, + timeoutMillis: Long = engineConfig.shutdownGracePeriod + ) } /** diff --git a/ktor-server/ktor-server-core/common/src/io/ktor/server/http/content/SuppressionAttribute.kt b/ktor-server/ktor-server-core/common/src/io/ktor/server/http/content/SuppressionAttribute.kt index dc93bd309a1..53712f45b8a 100644 --- a/ktor-server/ktor-server-core/common/src/io/ktor/server/http/content/SuppressionAttribute.kt +++ b/ktor-server/ktor-server-core/common/src/io/ktor/server/http/content/SuppressionAttribute.kt @@ -15,6 +15,7 @@ import io.ktor.util.* level = DeprecationLevel.ERROR ) public val SuppressionAttribute: AttributeKey = AttributeKey("preventCompression") +internal val DecompressionSuppressionAttribute: AttributeKey = AttributeKey("preventDecompression") /** * Suppress response body compression plugin for this [ApplicationCall]. @@ -24,8 +25,23 @@ public fun ApplicationCall.suppressCompression() { attributes.put(SuppressionAttribute, true) } +/** + * Suppresses the decompression for the current application call. + */ +public fun ApplicationCall.suppressDecompression() { + attributes.put(DecompressionSuppressionAttribute, true) +} + /** * Checks if response body compression is suppressed for this [ApplicationCall]. */ @Suppress("DEPRECATION_ERROR") public val ApplicationCall.isCompressionSuppressed: Boolean get() = SuppressionAttribute in attributes + +/** + * Indicates whether decompression is suppressed for the current application call. + * If decompression is suppressed, the plugin will not decompress the request body. + * + * To suppress decompression, use [suppressDecompression]. + */ +public val ApplicationCall.isDecompressionSuppressed: Boolean get() = DecompressionSuppressionAttribute in attributes diff --git a/ktor-server/ktor-server-core/common/src/io/ktor/server/plugins/Errors.kt b/ktor-server/ktor-server-core/common/src/io/ktor/server/plugins/Errors.kt index 8c672d512f0..8b1393be592 100644 --- a/ktor-server/ktor-server-core/common/src/io/ktor/server/plugins/Errors.kt +++ b/ktor-server/ktor-server-core/common/src/io/ktor/server/plugins/Errors.kt @@ -85,8 +85,11 @@ public class CannotTransformContentToTypeException( */ @OptIn(ExperimentalCoroutinesApi::class) public class UnsupportedMediaTypeException( - private val contentType: ContentType -) : ContentTransformationException("Content type $contentType is not supported"), + private val contentType: ContentType? +) : ContentTransformationException( + contentType?.let { "Content type $it is not supported" } + ?: "Content-Type header is required" +), CopyableThrowable { override fun createCopy(): UnsupportedMediaTypeException = UnsupportedMediaTypeException(contentType).also { diff --git a/ktor-server/ktor-server-core/jsAndWasmShared/src/io/ktor/server/engine/EmbeddedServer.jsAndWasmShared.kt b/ktor-server/ktor-server-core/jsAndWasmShared/src/io/ktor/server/engine/EmbeddedServer.jsAndWasmShared.kt index b24fc43895b..b7a8466fbb9 100644 --- a/ktor-server/ktor-server-core/jsAndWasmShared/src/io/ktor/server/engine/EmbeddedServer.jsAndWasmShared.kt +++ b/ktor-server/ktor-server-core/jsAndWasmShared/src/io/ktor/server/engine/EmbeddedServer.jsAndWasmShared.kt @@ -44,9 +44,7 @@ actual constructor( private val modules = rootConfig.modules - public actual fun start(wait: Boolean): EmbeddedServer { - addShutdownHook { stop() } - + private fun prepareToStart() { safeRaiseEvent(ApplicationStarting, application) try { modules.forEach { application.it() } @@ -65,9 +63,20 @@ actual constructor( ) } } + } + public actual fun start(wait: Boolean): EmbeddedServer { + addShutdownHook { stop() } + prepareToStart() engine.start(wait) + return this + } + @OptIn(DelicateCoroutinesApi::class) + public actual suspend fun startSuspend(wait: Boolean): EmbeddedServer { + addShutdownHook { GlobalScope.launch { stopSuspend() } } + prepareToStart() + engine.startSuspend(wait) return this } @@ -76,6 +85,11 @@ actual constructor( destroy(application) } + public actual suspend fun stopSuspend(gracePeriodMillis: Long, timeoutMillis: Long) { + engine.stopSuspend(gracePeriodMillis, timeoutMillis) + destroy(application) + } + private fun destroy(application: Application) { safeRaiseEvent(ApplicationStopping, application) try { diff --git a/ktor-server/ktor-server-core/jvm/src/io/ktor/server/engine/DefaultTransformJvm.kt b/ktor-server/ktor-server-core/jvm/src/io/ktor/server/engine/DefaultTransformJvm.kt index dd3c7d43079..a5379f8e5e7 100644 --- a/ktor-server/ktor-server-core/jvm/src/io/ktor/server/engine/DefaultTransformJvm.kt +++ b/ktor-server/ktor-server-core/jvm/src/io/ktor/server/engine/DefaultTransformJvm.kt @@ -6,8 +6,10 @@ package io.ktor.server.engine import io.ktor.http.* import io.ktor.http.cio.* +import io.ktor.http.cio.internals.* import io.ktor.http.content.* import io.ktor.server.application.* +import io.ktor.server.plugins.UnsupportedMediaTypeException import io.ktor.server.request.* import io.ktor.util.pipeline.* import io.ktor.utils.io.* @@ -33,16 +35,21 @@ internal actual suspend fun PipelineContext.defaultPlatformTr @OptIn(InternalAPI::class) internal actual fun PipelineContext<*, PipelineCall>.multiPartData(rc: ByteReadChannel): MultiPartData { val contentType = call.request.header(HttpHeaders.ContentType) - ?: throw IllegalStateException("Content-Type header is required for multipart processing") + ?: throw UnsupportedMediaTypeException(null) val contentLength = call.request.header(HttpHeaders.ContentLength)?.toLong() - return CIOMultipartDataBase( - coroutineContext + Dispatchers.Unconfined, - rc, - contentType, - contentLength, - call.formFieldLimit - ) + + try { + return CIOMultipartDataBase( + coroutineContext + Dispatchers.Unconfined, + rc, + contentType, + contentLength, + call.formFieldLimit + ) + } catch (_: UnsupportedMediaTypeExceptionCIO) { + throw UnsupportedMediaTypeException(ContentType.parse(contentType)) + } } internal actual fun Source.readTextWithCustomCharset(charset: Charset): String = diff --git a/ktor-server/ktor-server-core/jvm/src/io/ktor/server/engine/EmbeddedServerJvm.kt b/ktor-server/ktor-server-core/jvm/src/io/ktor/server/engine/EmbeddedServerJvm.kt index 0e8b31c045d..cad8966568c 100644 --- a/ktor-server/ktor-server-core/jvm/src/io/ktor/server/engine/EmbeddedServerJvm.kt +++ b/ktor-server/ktor-server-core/jvm/src/io/ktor/server/engine/EmbeddedServerJvm.kt @@ -294,6 +294,10 @@ actual constructor( return this } + public actual suspend fun startSuspend(wait: Boolean): EmbeddedServer { + return withContext(Dispatchers.IOBridge) { start(wait) } + } + public fun stop(shutdownGracePeriod: Long, shutdownTimeout: Long, timeUnit: TimeUnit) { try { engine.stop(timeUnit.toMillis(shutdownGracePeriod), timeUnit.toMillis(shutdownTimeout)) @@ -312,6 +316,10 @@ actual constructor( stop(gracePeriodMillis, timeoutMillis, TimeUnit.MILLISECONDS) } + public actual suspend fun stopSuspend(gracePeriodMillis: Long, timeoutMillis: Long) { + withContext(Dispatchers.IOBridge) { stop(gracePeriodMillis, timeoutMillis) } + } + private fun instantiateAndConfigureApplication(currentClassLoader: ClassLoader): Application { val newInstance = if (recreateInstance || _applicationInstance == null) { Application( diff --git a/ktor-server/ktor-server-core/jvm/test/io/ktor/tests/server/engine/MultiPartDataTest.kt b/ktor-server/ktor-server-core/jvm/test/io/ktor/tests/server/engine/MultiPartDataTest.kt new file mode 100644 index 00000000000..5f3934ed78b --- /dev/null +++ b/ktor-server/ktor-server-core/jvm/test/io/ktor/tests/server/engine/MultiPartDataTest.kt @@ -0,0 +1,78 @@ +/* + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + +package io.ktor.tests.server.engine + +import io.ktor.client.request.* +import io.ktor.http.* +import io.ktor.server.application.* +import io.ktor.server.engine.* +import io.ktor.server.plugins.* +import io.ktor.server.request.* +import io.ktor.server.response.* +import io.ktor.server.routing.* +import io.ktor.server.testing.* +import io.ktor.util.pipeline.* +import io.ktor.utils.io.* +import io.mockk.* +import kotlinx.coroutines.* +import kotlinx.coroutines.test.* +import kotlin.test.* + +class MultiPartDataTest { + private val mockContext = mockk>(relaxed = true) + private val mockRequest = mockk(relaxed = true) + private val testScope = TestScope() + + @Test + fun givenRequest_whenNoContentTypeHeaderPresent_thenUnsupportedMediaTypeException() { + // Given + every { mockContext.call.request } returns mockRequest + every { mockRequest.header(HttpHeaders.ContentType) } returns null + + // When & Then + assertFailsWith { + runBlocking { mockContext.multiPartData(ByteReadChannel("sample data")) } + } + } + + @Test + fun givenWrongContentType_whenProcessMultiPart_thenUnsupportedMediaTypeException() { + // Given + val rc = ByteReadChannel("sample data") + val contentType = "test/plain; boundary=test" + val contentLength = "123" + every { mockContext.call.request } returns mockRequest + every { mockContext.call.attributes.getOrNull(any()) } returns 0L + every { mockRequest.header(HttpHeaders.ContentType) } returns contentType + every { mockRequest.header(HttpHeaders.ContentLength) } returns contentLength + + // When & Then + testScope.runTest { + assertFailsWith { + mockContext.multiPartData(rc) + } + } + } + + @Test + fun testUnsupportedMediaTypeStatusCode() = testApplication { + routing { + post { + call.receiveMultipart() + call.respond(HttpStatusCode.OK) + } + } + + client.post { + accept(ContentType.Text.Plain) + }.apply { + assertEquals(HttpStatusCode.UnsupportedMediaType, status) + } + + client.post {}.apply { + assertEquals(HttpStatusCode.UnsupportedMediaType, status) + } + } +} diff --git a/ktor-server/ktor-server-core/posix/src/io/ktor/server/engine/EmbeddedServerNix.kt b/ktor-server/ktor-server-core/posix/src/io/ktor/server/engine/EmbeddedServerNix.kt index 9720830df6f..f9c1bdedec3 100644 --- a/ktor-server/ktor-server-core/posix/src/io/ktor/server/engine/EmbeddedServerNix.kt +++ b/ktor-server/ktor-server-core/posix/src/io/ktor/server/engine/EmbeddedServerNix.kt @@ -71,11 +71,19 @@ actual constructor( return this } + public actual suspend fun startSuspend(wait: Boolean): EmbeddedServer { + return withContext(Dispatchers.IOBridge) { start(wait) } + } + public actual fun stop(gracePeriodMillis: Long, timeoutMillis: Long) { engine.stop(gracePeriodMillis, timeoutMillis) destroy(application) } + public actual suspend fun stopSuspend(gracePeriodMillis: Long, timeoutMillis: Long) { + withContext(Dispatchers.IOBridge) { stop(gracePeriodMillis, timeoutMillis) } + } + private fun destroy(application: Application) { safeRaiseEvent(ApplicationStopping, application) try { diff --git a/ktor-server/ktor-server-plugins/ktor-server-auth/common/test/io/ktor/tests/auth/SessionAuthTest.kt b/ktor-server/ktor-server-plugins/ktor-server-auth/common/test/io/ktor/tests/auth/SessionAuthTest.kt index 0fcdefca394..c565add44a4 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-auth/common/test/io/ktor/tests/auth/SessionAuthTest.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-auth/common/test/io/ktor/tests/auth/SessionAuthTest.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.tests.auth @@ -14,7 +14,6 @@ import io.ktor.server.response.* import io.ktor.server.routing.* import io.ktor.server.sessions.* import io.ktor.server.testing.* -import io.ktor.utils.io.core.* import kotlinx.serialization.* import kotlin.test.* diff --git a/ktor-server/ktor-server-plugins/ktor-server-compression/jvm/src/io/ktor/server/plugins/compression/Compression.kt b/ktor-server/ktor-server-plugins/ktor-server-compression/jvm/src/io/ktor/server/plugins/compression/Compression.kt index ed1c18cd526..434d83fb7d8 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-compression/jvm/src/io/ktor/server/plugins/compression/Compression.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-compression/jvm/src/io/ktor/server/plugins/compression/Compression.kt @@ -5,7 +5,6 @@ package io.ktor.server.plugins.compression import io.ktor.http.* -import io.ktor.http.cio.* import io.ktor.http.content.* import io.ktor.server.application.* import io.ktor.server.http.content.* @@ -13,9 +12,15 @@ import io.ktor.server.request.* import io.ktor.server.response.* import io.ktor.util.* import io.ktor.util.logging.* -import io.ktor.util.pipeline.* import io.ktor.utils.io.* -import kotlinx.coroutines.* + +/** + * List of [ContentEncoder] names that were used to decode request body. + */ +public val ApplicationRequest.appliedDecoders: List + get() = call.attributes.getOrNull(DecompressionListAttribute) ?: emptyList() + +internal val DecompressionListAttribute: AttributeKey> = AttributeKey("DecompressionListAttribute") internal val LOGGER = KtorSimpleLogger("io.ktor.server.plugins.compression.Compression") @@ -24,27 +29,6 @@ internal val LOGGER = KtorSimpleLogger("io.ktor.server.plugins.compression.Compr */ internal const val DEFAULT_MINIMAL_COMPRESSION_SIZE: Long = 200L -private object ContentEncoding : Hook Unit> { - - class Context(private val pipelineContext: PipelineContext) { - fun transformBody(block: (OutgoingContent) -> OutgoingContent?) { - val transformedContent = block(pipelineContext.subject as OutgoingContent) - if (transformedContent != null) { - pipelineContext.subject = transformedContent - } - } - } - - override fun install( - pipeline: ApplicationCallPipeline, - handler: suspend Context.(PipelineCall) -> Unit - ) { - pipeline.sendPipeline.intercept(ApplicationSendPipeline.ContentEncoding) { - handler(Context(this), call) - } - } -} - /** * A plugin that provides the capability to compress a response and decompress request bodies. * You can use different compression algorithms, including `gzip` and `deflate`, @@ -82,15 +66,21 @@ public val Compression: RouteScopedPlugin = createRouteScoped if (!mode.response) return@on encode(call, options) } - onCall { call -> - if (!mode.request) return@onCall + + onCallReceive { call -> + if (!mode.request) return@onCallReceive decode(call, options) } + } @OptIn(InternalAPI::class) -private fun decode(call: PipelineCall, options: CompressionOptions) { +private suspend fun OnCallReceiveContext.decode(call: PipelineCall, options: CompressionOptions) { val encodingRaw = call.request.headers[HttpHeaders.ContentEncoding] + if (call.isDecompressionSuppressed) { + LOGGER.trace("Skip decompression for ${call.request.uri} because it is suppressed.") + return + } if (encodingRaw == null) { LOGGER.trace("Skip decompression for ${call.request.uri} because no content encoding provided.") return @@ -112,10 +102,12 @@ private fun decode(call: PipelineCall, options: CompressionOptions) { } else { call.request.setHeader(HttpHeaders.ContentEncoding, null) } - val originalChannel = call.request.receiveChannel() - val decoded = encoders.fold(originalChannel) { content, encoder -> encoder.encoder.decode(content) } - call.request.setReceiveChannel(decoded) + call.attributes.put(DecompressionListAttribute, encoderNames) + + transformBody { body -> + encoders.fold(body) { content, encoder -> encoder.encoder.decode(content) } + } } private fun ContentEncoding.Context.encode(call: PipelineCall, options: CompressionOptions) { @@ -180,14 +172,6 @@ private fun ContentEncoding.Context.encode(call: PipelineCall, options: Compress } } -internal val DecompressionListAttribute: AttributeKey> = AttributeKey("DecompressionListAttribute") - -/** - * List of [ContentEncoder] names that were used to decode request body. - */ -public val ApplicationRequest.appliedDecoders: List - get() = call.attributes.getOrNull(DecompressionListAttribute) ?: emptyList() - private fun PipelineResponse.isSSEResponse(): Boolean { val contentType = headers[HttpHeaders.ContentType]?.let { ContentType.parse(it) } return contentType?.withoutParameters() == ContentType.Text.EventStream diff --git a/ktor-server/ktor-server-plugins/ktor-server-compression/jvm/src/io/ktor/server/plugins/compression/ContentEncoding.kt b/ktor-server/ktor-server-plugins/ktor-server-compression/jvm/src/io/ktor/server/plugins/compression/ContentEncoding.kt new file mode 100644 index 00000000000..5a67799e188 --- /dev/null +++ b/ktor-server/ktor-server-plugins/ktor-server-compression/jvm/src/io/ktor/server/plugins/compression/ContentEncoding.kt @@ -0,0 +1,31 @@ +/* + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + */ + +package io.ktor.server.plugins.compression + +import io.ktor.http.content.* +import io.ktor.server.application.* +import io.ktor.server.response.* +import io.ktor.util.pipeline.* + +internal object ContentEncoding : Hook Unit> { + + class Context(private val pipelineContext: PipelineContext) { + fun transformBody(block: (OutgoingContent) -> OutgoingContent?) { + val transformedContent = block(pipelineContext.subject as OutgoingContent) + if (transformedContent != null) { + pipelineContext.subject = transformedContent + } + } + } + + override fun install( + pipeline: ApplicationCallPipeline, + handler: suspend Context.(PipelineCall) -> Unit + ) { + pipeline.sendPipeline.intercept(ApplicationSendPipeline.ContentEncoding) { + handler(Context(this), call) + } + } +} diff --git a/ktor-server/ktor-server-plugins/ktor-server-sse/api/ktor-server-sse.api b/ktor-server/ktor-server-plugins/ktor-server-sse/api/ktor-server-sse.api index 1cc44ada840..ccc9395d0d5 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-sse/api/ktor-server-sse.api +++ b/ktor-server/ktor-server-plugins/ktor-server-sse/api/ktor-server-sse.api @@ -1,6 +1,8 @@ public final class io/ktor/server/sse/RoutingKt { public static final fun sse (Lio/ktor/server/routing/Route;Ljava/lang/String;Lkotlin/jvm/functions/Function2;)V + public static final fun sse (Lio/ktor/server/routing/Route;Ljava/lang/String;Lkotlin/jvm/functions/Function2;Lkotlin/jvm/functions/Function2;)V public static final fun sse (Lio/ktor/server/routing/Route;Lkotlin/jvm/functions/Function2;)V + public static final fun sse (Lio/ktor/server/routing/Route;Lkotlin/jvm/functions/Function2;Lkotlin/jvm/functions/Function2;)V } public final class io/ktor/server/sse/SSEKt { @@ -9,9 +11,12 @@ public final class io/ktor/server/sse/SSEKt { public final class io/ktor/server/sse/SSEServerContent : io/ktor/http/content/OutgoingContent$WriteChannelContent { public fun (Lio/ktor/server/application/ApplicationCall;Lkotlin/jvm/functions/Function2;)V + public fun (Lio/ktor/server/application/ApplicationCall;Lkotlin/jvm/functions/Function2;Lkotlin/jvm/functions/Function2;)V + public synthetic fun (Lio/ktor/server/application/ApplicationCall;Lkotlin/jvm/functions/Function2;Lkotlin/jvm/functions/Function2;ILkotlin/jvm/internal/DefaultConstructorMarker;)V public final fun getCall ()Lio/ktor/server/application/ApplicationCall; public fun getContentType ()Lio/ktor/http/ContentType; public final fun getHandle ()Lkotlin/jvm/functions/Function2; + public final fun getSerialize ()Lkotlin/jvm/functions/Function2; public fun toString ()Ljava/lang/String; public fun writeTo (Lio/ktor/utils/io/ByteWriteChannel;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; } @@ -28,3 +33,11 @@ public final class io/ktor/server/sse/ServerSSESession$DefaultImpls { public static synthetic fun send$default (Lio/ktor/server/sse/ServerSSESession;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;Ljava/lang/String;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; } +public abstract interface class io/ktor/server/sse/ServerSSESessionWithSerialization : io/ktor/server/sse/ServerSSESession { + public abstract fun getSerializer ()Lkotlin/jvm/functions/Function2; +} + +public final class io/ktor/server/sse/ServerSSESessionWithSerialization$DefaultImpls { + public static fun send (Lio/ktor/server/sse/ServerSSESessionWithSerialization;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;Ljava/lang/String;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; +} + diff --git a/ktor-server/ktor-server-plugins/ktor-server-sse/api/ktor-server-sse.klib.api b/ktor-server/ktor-server-plugins/ktor-server-sse/api/ktor-server-sse.klib.api index e49e67192ea..93d8bbf2b19 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-sse/api/ktor-server-sse.klib.api +++ b/ktor-server/ktor-server-plugins/ktor-server-sse/api/ktor-server-sse.klib.api @@ -15,8 +15,14 @@ abstract interface io.ktor.server.sse/ServerSSESession : kotlinx.coroutines/Coro open suspend fun send(kotlin/String? = ..., kotlin/String? = ..., kotlin/String? = ..., kotlin/Long? = ..., kotlin/String? = ...) // io.ktor.server.sse/ServerSSESession.send|send(kotlin.String?;kotlin.String?;kotlin.String?;kotlin.Long?;kotlin.String?){}[0] } +abstract interface io.ktor.server.sse/ServerSSESessionWithSerialization : io.ktor.server.sse/ServerSSESession { // io.ktor.server.sse/ServerSSESessionWithSerialization|null[0] + abstract val serializer // io.ktor.server.sse/ServerSSESessionWithSerialization.serializer|{}serializer[0] + abstract fun (): kotlin/Function2 // io.ktor.server.sse/ServerSSESessionWithSerialization.serializer.|(){}[0] +} + final class io.ktor.server.sse/SSEServerContent : io.ktor.http.content/OutgoingContent.WriteChannelContent { // io.ktor.server.sse/SSEServerContent|null[0] constructor (io.ktor.server.application/ApplicationCall, kotlin.coroutines/SuspendFunction1) // io.ktor.server.sse/SSEServerContent.|(io.ktor.server.application.ApplicationCall;kotlin.coroutines.SuspendFunction1){}[0] + constructor (io.ktor.server.application/ApplicationCall, kotlin.coroutines/SuspendFunction1, kotlin/Function2? = ...) // io.ktor.server.sse/SSEServerContent.|(io.ktor.server.application.ApplicationCall;kotlin.coroutines.SuspendFunction1;kotlin.Function2?){}[0] final val call // io.ktor.server.sse/SSEServerContent.call|{}call[0] final fun (): io.ktor.server.application/ApplicationCall // io.ktor.server.sse/SSEServerContent.call.|(){}[0] @@ -24,6 +30,8 @@ final class io.ktor.server.sse/SSEServerContent : io.ktor.http.content/OutgoingC final fun (): io.ktor.http/ContentType // io.ktor.server.sse/SSEServerContent.contentType.|(){}[0] final val handle // io.ktor.server.sse/SSEServerContent.handle|{}handle[0] final fun (): kotlin.coroutines/SuspendFunction1 // io.ktor.server.sse/SSEServerContent.handle.|(){}[0] + final val serialize // io.ktor.server.sse/SSEServerContent.serialize|{}serialize[0] + final fun (): kotlin/Function2? // io.ktor.server.sse/SSEServerContent.serialize.|(){}[0] final fun toString(): kotlin/String // io.ktor.server.sse/SSEServerContent.toString|toString(){}[0] final suspend fun writeTo(io.ktor.utils.io/ByteWriteChannel) // io.ktor.server.sse/SSEServerContent.writeTo|writeTo(io.ktor.utils.io.ByteWriteChannel){}[0] @@ -33,4 +41,9 @@ final val io.ktor.server.sse/SSE // io.ktor.server.sse/SSE|{}SSE[0] final fun (): io.ktor.server.application/ApplicationPlugin // io.ktor.server.sse/SSE.|(){}[0] final fun (io.ktor.server.routing/Route).io.ktor.server.sse/sse(kotlin.coroutines/SuspendFunction1) // io.ktor.server.sse/sse|sse@io.ktor.server.routing.Route(kotlin.coroutines.SuspendFunction1){}[0] +final fun (io.ktor.server.routing/Route).io.ktor.server.sse/sse(kotlin/Function2, kotlin.coroutines/SuspendFunction1) // io.ktor.server.sse/sse|sse@io.ktor.server.routing.Route(kotlin.Function2;kotlin.coroutines.SuspendFunction1){}[0] final fun (io.ktor.server.routing/Route).io.ktor.server.sse/sse(kotlin/String, kotlin.coroutines/SuspendFunction1) // io.ktor.server.sse/sse|sse@io.ktor.server.routing.Route(kotlin.String;kotlin.coroutines.SuspendFunction1){}[0] +final fun (io.ktor.server.routing/Route).io.ktor.server.sse/sse(kotlin/String, kotlin/Function2, kotlin.coroutines/SuspendFunction1) // io.ktor.server.sse/sse|sse@io.ktor.server.routing.Route(kotlin.String;kotlin.Function2;kotlin.coroutines.SuspendFunction1){}[0] +final suspend inline fun <#A: reified kotlin/Any> (io.ktor.server.sse/ServerSSESessionWithSerialization).io.ktor.server.sse/send(#A) // io.ktor.server.sse/send|send@io.ktor.server.sse.ServerSSESessionWithSerialization(0:0){0§}[0] +final suspend inline fun <#A: reified kotlin/Any> (io.ktor.server.sse/ServerSSESessionWithSerialization).io.ktor.server.sse/send(#A? = ..., kotlin/String? = ..., kotlin/String? = ..., kotlin/Long? = ..., kotlin/String? = ...) // io.ktor.server.sse/send|send@io.ktor.server.sse.ServerSSESessionWithSerialization(0:0?;kotlin.String?;kotlin.String?;kotlin.Long?;kotlin.String?){0§}[0] +final suspend inline fun <#A: reified kotlin/Any> (io.ktor.server.sse/ServerSSESessionWithSerialization).io.ktor.server.sse/send(io.ktor.sse/TypedServerSentEvent<#A>) // io.ktor.server.sse/send|send@io.ktor.server.sse.ServerSSESessionWithSerialization(io.ktor.sse.TypedServerSentEvent<0:0>){0§}[0] diff --git a/ktor-server/ktor-server-plugins/ktor-server-sse/build.gradle.kts b/ktor-server/ktor-server-plugins/ktor-server-sse/build.gradle.kts index 5148437ca11..f1ad9f6b9fc 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-sse/build.gradle.kts +++ b/ktor-server/ktor-server-plugins/ktor-server-sse/build.gradle.kts @@ -1,9 +1,19 @@ description = "Server-sent events (SSE) support" +plugins { + id("kotlinx-serialization") +} + kotlin.sourceSets { commonMain { dependencies { api(project(":ktor-shared:ktor-sse")) } } + commonTest { + dependencies { + api(project(":ktor-shared:ktor-serialization:ktor-serialization-kotlinx")) + api(project(":ktor-shared:ktor-serialization:ktor-serialization-kotlinx:ktor-serialization-kotlinx-json")) + } + } } diff --git a/ktor-server/ktor-server-plugins/ktor-server-sse/common/src/io/ktor/server/sse/Routing.kt b/ktor-server/ktor-server-plugins/ktor-server-sse/common/src/io/ktor/server/sse/Routing.kt index 4ed05d3988a..8665c97bb2e 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-sse/common/src/io/ktor/server/sse/Routing.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-sse/common/src/io/ktor/server/sse/Routing.kt @@ -7,21 +7,35 @@ package io.ktor.server.sse import io.ktor.http.* import io.ktor.server.response.* import io.ktor.server.routing.* +import io.ktor.util.reflect.* /** * Adds a route to handle Server-Sent Events (SSE) at the specified [path] using the provided [handler]. * Requires [SSE] plugin to be installed. * - * @param path URL path at which to handle SSE requests. - * @param handler function that defines the behavior of the SSE session. It is invoked when a client connects to the SSE - * endpoint. Inside the handler, you can use the functions provided by [ServerSSESession] + * @param path A URL path at which to handle Server-Sent Events (SSE) requests. + * @param handler A function that defines the behavior of the SSE session. It is invoked when a client connects to the SSE + * endpoint. Inside the handler, you can use the functions provided by [ServerSSESessionWithSerialization] * to send events to the connected clients. * + * Example of usage: + * ```kotlin + * install(SSE) + * routing { + * sse("/events") { + * repeat(100) { + * send(ServerSentEvent("event $it")) + * } + * } + * } + * ``` + * + * To learn more, see [the SSE](https://en.wikipedia.org/wiki/Server-sent_events) + * and [the SSE specification](https://html.spec.whatwg.org/multipage/server-sent-events.html). + * * @see ServerSSESession */ public fun Route.sse(path: String, handler: suspend ServerSSESession.() -> Unit) { - plugin(SSE) - route(path, HttpMethod.Get) { sse(handler) } @@ -31,13 +45,122 @@ public fun Route.sse(path: String, handler: suspend ServerSSESession.() -> Unit) * Adds a route to handle Server-Sent Events (SSE) using the provided [handler]. * Requires [SSE] plugin to be installed. * - * @param handler function that defines the behavior of the SSE session. It is invoked when a client connects to the SSE - * endpoint. Inside the handler, you can use the functions provided by [ServerSSESession] + * @param handler A function that defines the behavior of the SSE session. It is invoked when a client connects to the SSE + * endpoint. Inside the handler, you can use the functions provided by [ServerSSESessionWithSerialization] * to send events to the connected clients. * + * Example of usage: + * ```kotlin + * install(SSE) + * routing { + * sse { + * repeat(100) { + * send(ServerSentEvent("event $it")) + * } + * } + * } + * ``` + * + * To learn more, see [the SSE](https://en.wikipedia.org/wiki/Server-sent_events) + * and [the SSE specification](https://html.spec.whatwg.org/multipage/server-sent-events.html). + * * @see ServerSSESession */ -public fun Route.sse(handler: suspend ServerSSESession.() -> Unit) { +public fun Route.sse(handler: suspend ServerSSESession.() -> Unit): Unit = processSSEWithoutSerialization(handler) + +/** + * Adds a route to handle Server-Sent Events (SSE) at the specified [path] using the provided [handler]. + * Requires [SSE] plugin to be installed. + * + * @param path A URL path at which to handle Server-Sent Events (SSE) requests. + * @param serialize A function to serialize data objects into the `data` field of a `ServerSentEvent`. + * @param handler A function that defines the behavior of the SSE session. It is invoked when a client connects to the SSE + * endpoint. Inside the handler, you can use the functions provided by [ServerSSESessionWithSerialization] + * to send events to the connected clients. + * + * Example of usage: + * ```kotlin + * install(SSE) + * routing { + * sse("/json", serialize = { typeInfo, it -> + * val serializer = Json.serializersModule.serializer(typeInfo.kotlinType!!) + * Json.encodeToString(serializer, it) + * }) { + * send(Customer(0, "Jet", "Brains")) + * send(Product(0, listOf(100, 200))) + * } + * } + * ``` + * + * To learn more, see [the SSE](https://en.wikipedia.org/wiki/Server-sent_events) + * and [the SSE specification](https://html.spec.whatwg.org/multipage/server-sent-events.html). + * + * @see ServerSSESessionWithSerialization + */ +public fun Route.sse( + path: String, + serialize: (TypeInfo, Any) -> String, + handler: suspend ServerSSESessionWithSerialization.() -> Unit +) { + route(path, HttpMethod.Get) { + sse(serialize, handler) + } +} + +/** + * Adds a route to handle Server-Sent Events (SSE) using the provided [handler]. + * Requires [SSE] plugin to be installed. + * + * @param serialize A function to serialize data objects into the `data` field of a `ServerSentEvent`. + * @param handler A function that defines the behavior of the SSE session. It is invoked when a client connects to the SSE + * endpoint. Inside the handler, you can use the functions provided by [ServerSSESessionWithSerialization] + * to send events to the connected clients. + * + * Example of usage: + * ```kotlin + * install(SSE) + * routing { + * sse(serialize = { typeInfo, it -> + * val serializer = Json.serializersModule.serializer(typeInfo.kotlinType!!) + * Json.encodeToString(serializer, it) + * }) { + * send(Customer(0, "Jet", "Brains")) + * send(Product(0, listOf(100, 200))) + * } + * } + * ``` + * + * To learn more, see [the SSE](https://en.wikipedia.org/wiki/Server-sent_events) + * and [the SSE specification](https://html.spec.whatwg.org/multipage/server-sent-events.html). + * + * @see ServerSSESessionWithSerialization + */ +public fun Route.sse( + serialize: (TypeInfo, Any) -> String, + handler: suspend ServerSSESessionWithSerialization.() -> Unit +): Unit = processSSEWithSerialization(serialize, handler) + +private fun Route.processSSEWithoutSerialization( + handler: suspend ServerSSESession.() -> Unit +) = processSSE(null, handler) + +private fun Route.processSSEWithSerialization( + serialize: ((TypeInfo, Any) -> String), + handler: suspend ServerSSESessionWithSerialization.() -> Unit +) { + val sessionHandler: suspend ServerSSESession.() -> Unit = { + check(this is ServerSSESessionWithSerialization) { + "Impossible state. Please report this bug: https://youtrack.jetbrains.com/newIssue?project=KTOR" + } + handler() + } + processSSE(serialize, sessionHandler) +} + +private fun Route.processSSE( + serialize: ((TypeInfo, Any) -> String)?, + handler: suspend ServerSSESession.() -> Unit +) { plugin(SSE) handle { @@ -45,6 +168,6 @@ public fun Route.sse(handler: suspend ServerSSESession.() -> Unit) { call.response.header(HttpHeaders.CacheControl, "no-store") call.response.header(HttpHeaders.Connection, "keep-alive") call.response.header("X-Accel-Buffering", "no") - call.respond(SSEServerContent(call, handler)) + call.respond(SSEServerContent(call, handler, serialize)) } } diff --git a/ktor-server/ktor-server-plugins/ktor-server-sse/common/src/io/ktor/server/sse/SSE.kt b/ktor-server/ktor-server-plugins/ktor-server-sse/common/src/io/ktor/server/sse/SSE.kt index efbc9129de6..bf8b558f8fd 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-sse/common/src/io/ktor/server/sse/SSE.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-sse/common/src/io/ktor/server/sse/SSE.kt @@ -12,17 +12,27 @@ internal val LOGGER = KtorSimpleLogger("io.ktor.server.plugins.sse.SSE") /** * Server-Sent Events (SSE) support plugin. It is required to be installed first before binding any sse endpoints. * - * To learn more, see [specification](https://html.spec.whatwg.org/multipage/server-sent-events.html). - * - * Example: + * Example of usage: * ```kotlin * install(SSE) + * routing { + * sse("/default") { + * repeat(100) { + * send(ServerSentEvent("event $it")) + * } + * } * - * install(Routing) { - * sse { - * send(ServerSentEvent("Hello")) + * sse("/serialization", serialize = { typeInfo, it -> + * val serializer = Json.serializersModule.serializer(typeInfo.kotlinType!!) + * Json.encodeToString(serializer, it) + * }) { + * send(Customer(0, "Jet", "Brains")) + * send(Product(0, listOf(100, 200))) * } * } * ``` + * + * To learn more, see [the SSE](https://en.wikipedia.org/wiki/Server-sent_events) + * and [the SSE specification](https://html.spec.whatwg.org/multipage/server-sent-events.html). */ public val SSE: ApplicationPlugin = createApplicationPlugin("SSE") {} diff --git a/ktor-server/ktor-server-plugins/ktor-server-sse/common/src/io/ktor/server/sse/SSEServerContent.kt b/ktor-server/ktor-server-plugins/ktor-server-sse/common/src/io/ktor/server/sse/SSEServerContent.kt index 8dd94e6ddf4..45b260c7411 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-sse/common/src/io/ktor/server/sse/SSEServerContent.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-sse/common/src/io/ktor/server/sse/SSEServerContent.kt @@ -8,6 +8,7 @@ import io.ktor.http.* import io.ktor.http.content.* import io.ktor.server.application.* import io.ktor.server.request.* +import io.ktor.util.reflect.* import io.ktor.utils.io.* import kotlinx.coroutines.* @@ -25,8 +26,14 @@ import kotlinx.coroutines.* */ public class SSEServerContent( public val call: ApplicationCall, - public val handle: suspend ServerSSESession.() -> Unit + public val handle: suspend ServerSSESession.() -> Unit, + public val serialize: ((TypeInfo, Any) -> String)? = null ) : OutgoingContent.WriteChannelContent() { + public constructor( + call: ApplicationCall, + handle: suspend ServerSSESession.() -> Unit, + ) : this(call, handle, null) + override val contentType: ContentType = ContentType.Text.EventStream override suspend fun writeTo(channel: ByteWriteChannel) { @@ -36,6 +43,13 @@ public class SSEServerContent( try { coroutineScope { session = DefaultServerSSESession(channel, call, coroutineContext) + if (serialize != null) { + session = object : + ServerSSESessionWithSerialization, + ServerSSESession by session as DefaultServerSSESession { + override val serializer: (TypeInfo, Any) -> String = serialize + } + } session?.handle() } } finally { diff --git a/ktor-server/ktor-server-plugins/ktor-server-sse/common/src/io/ktor/server/sse/ServerSSESession.kt b/ktor-server/ktor-server-plugins/ktor-server-sse/common/src/io/ktor/server/sse/ServerSSESession.kt index 2d281ee243d..46627989635 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-sse/common/src/io/ktor/server/sse/ServerSSESession.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-sse/common/src/io/ktor/server/sse/ServerSSESession.kt @@ -6,17 +6,34 @@ package io.ktor.server.sse import io.ktor.server.application.* import io.ktor.sse.* +import io.ktor.util.reflect.* +import io.ktor.websocket.* import kotlinx.coroutines.* /** - * Represents a server-side server-sent events session. + * Represents a server-side Server-Sent Events (SSE) session. * An [ServerSSESession] allows the server to send [ServerSentEvent] to the client over a single HTTP connection. * - * @see [SSE] + * Example of usage: + * ```kotlin + * install(SSE) + * routing { + * sse("/default") { + * repeat(100) { + * send(ServerSentEvent("event $it")) + * } + * } + * } + * ``` + * + * To learn more, see [the SSE](https://en.wikipedia.org/wiki/Server-sent_events) + * and [the SSE specification](https://html.spec.whatwg.org/multipage/server-sent-events.html). + * + * @see SSE */ public interface ServerSSESession : CoroutineScope { /** - * Associated received [call] that originating this session. + * The received [call] that originated this session. */ public val call: ApplicationCall @@ -55,3 +72,61 @@ public interface ServerSSESession : CoroutineScope { */ public suspend fun close() } + +/** + * Represents a server-side Server-Sent Events (SSE) session with serialization support. + * An [ServerSSESessionWithSerialization] allows the server to send [ServerSentEvent] to the client over a single HTTP connection. + * + * Example of usage: + * ```kotlin + * install(SSE) + * routing { + * sse("/serialization", serialize = { typeInfo, it -> + * val serializer = Json.serializersModule.serializer(typeInfo.kotlinType!!) + * Json.encodeToString(serializer, it) + * }) { + * send(Customer(0, "Jet", "Brains")) + * send(Product(0, listOf(100, 200))) + * } + * } + * ``` + * + * To learn more, see [the SSE](https://en.wikipedia.org/wiki/Server-sent_events) + * and [the SSE specification](https://html.spec.whatwg.org/multipage/server-sent-events.html). + * + * @see SSE + */ +public interface ServerSSESessionWithSerialization : ServerSSESession { + /** + * Serializer for transforming data object into field `data` of `ServerSentEvent`. + */ + public val serializer: (TypeInfo, Any) -> String +} + +public suspend inline fun ServerSSESessionWithSerialization.send(event: TypedServerSentEvent) { + send( + ServerSentEvent( + event.data?.let { + serializer(typeInfo(), it) + }, + event.event, + event.id, + event.retry, + event.comments + ) + ) +} + +public suspend inline fun ServerSSESessionWithSerialization.send( + data: T? = null, + event: String? = null, + id: String? = null, + retry: Long? = null, + comments: String? = null +) { + send(TypedServerSentEvent(data, event, id, retry, comments)) +} + +public suspend inline fun ServerSSESessionWithSerialization.send(data: T) { + send(ServerSentEvent(serializer(typeInfo(), data))) +} diff --git a/ktor-server/ktor-server-plugins/ktor-server-sse/common/test/io/ktor/server/sse/ServerSentEventsTest.kt b/ktor-server/ktor-server-plugins/ktor-server-sse/common/test/io/ktor/server/sse/ServerSentEventsTest.kt index 3f82c477c78..f9200fd40ca 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-sse/common/test/io/ktor/server/sse/ServerSentEventsTest.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-sse/common/test/io/ktor/server/sse/ServerSentEventsTest.kt @@ -13,6 +13,8 @@ import io.ktor.server.testing.* import io.ktor.sse.* import kotlinx.coroutines.* import kotlinx.coroutines.flow.* +import kotlinx.serialization.* +import kotlinx.serialization.json.* import kotlin.test.* class ServerSentEventsTest { @@ -192,6 +194,103 @@ class ServerSentEventsTest { assertEquals(expectedOneEventData.lines(), actualOneEventData.toString().lines()) } + class Person1(val age: Int) + class Person2(val number: Int) + + @Test + fun testSerializerInRoute() = testApplication { + install(SSE) + routing { + sse("/person", serialize = { typeInfo, data -> + when (typeInfo.type) { + Person1::class -> { + "Age ${(data as Person1).age}" + } + + else -> { + data.toString() + } + } + }) { + repeat(10) { + send(Person1(it)) + } + } + } + + val client = createSseClient() + + client.sse("/person") { + incoming.collectIndexed { i, person -> + assertEquals("Age $i", person.data) + } + } + } + + @Test + fun testDifferentSerializers() = testApplication { + install(SSE) + routing { + sse(serialize = { typeInfo, data -> + when (typeInfo.type) { + Person1::class -> { + "Age ${(data as Person1).age}" + } + + Person2::class -> { + "Number ${(data as Person2).number}" + } + + else -> { + data.toString() + } + } + }) { + send(Person1(22)) + send(Person2(123456)) + } + } + + val client = createSseClient() + client.sse { + var first = true + incoming.collect { + if (first) { + assertEquals("Age 22", it.data) + first = false + } else { + assertEquals("Number 123456", it.data) + } + } + } + } + + @Serializable + data class Customer(val id: Int, val firstName: String, val lastName: String) + + @Serializable + data class Product(val id: Int, val prices: List) + + @Test + fun testJsonSerializer() = testApplication { + install(SSE) + routing { + sse("/json", serialize = { typeInfo, it -> + val serializer = Json.serializersModule.serializer(typeInfo.kotlinType!!) + Json.encodeToString(serializer, it) + }) { + send(Customer(0, "Jet", "Brains")) + send(Product(0, listOf(100, 200))) + } + } + + assertEquals( + "data: {\"id\":0,\"firstName\":\"Jet\",\"lastName\":\"Brains\"}\r\n\r\n" + + "data: {\"id\":0,\"prices\":[100,200]}", + client.get("/json").bodyAsText().trim() + ) + } + private fun ApplicationTestBuilder.createSseClient(): HttpClient { val client = createClient { install(io.ktor.client.plugins.sse.SSE) diff --git a/ktor-server/ktor-server-test-base/jsAndWasmShared/src/io/ktor/server/test/base/EngineTestBase.jsAndWasmShared.kt b/ktor-server/ktor-server-test-base/jsAndWasmShared/src/io/ktor/server/test/base/EngineTestBase.jsAndWasmShared.kt index fe9b632b017..6564b519697 100644 --- a/ktor-server/ktor-server-test-base/jsAndWasmShared/src/io/ktor/server/test/base/EngineTestBase.jsAndWasmShared.kt +++ b/ktor-server/ktor-server-test-base/jsAndWasmShared/src/io/ktor/server/test/base/EngineTestBase.jsAndWasmShared.kt @@ -5,6 +5,7 @@ package io.ktor.server.test.base import io.ktor.client.* +import io.ktor.client.engine.cio.* import io.ktor.client.plugins.* import io.ktor.client.request.* import io.ktor.client.statement.* @@ -14,11 +15,14 @@ import io.ktor.server.engine.* import io.ktor.server.routing.* import io.ktor.server.testing.* import io.ktor.util.logging.* -import io.ktor.utils.io.core.* import kotlinx.coroutines.* import kotlin.coroutines.* +import kotlin.test.* import kotlin.time.Duration.Companion.seconds +private const val UNINITIALIZED_PORT = -1 +private const val DEFAULT_PORT = 0 + actual abstract class EngineTestBase< TEngine : ApplicationEngine, TConfiguration : ApplicationEngine.Configuration @@ -33,7 +37,22 @@ actual constructor( @Retention protected actual annotation class Http2Only actual constructor() - protected actual var port: Int = 0 + /** + * It's not possible to find a free port during test setup, + * as on JS (Node.js) all APIs are non-blocking (suspend). + * That's why we assign port after the server is started in [startServer] + * Note: this means, that [port] can be used only after calling [createAndStartServer] or [startServer]. + */ + private var _port: Int = UNINITIALIZED_PORT + protected actual var port: Int + get() { + check(_port != UNINITIALIZED_PORT) { "Port is not initialized" } + return _port + } + set(_) { + error("Can't reassign port.") + } + protected actual var sslPort: Int = 0 protected actual var server: EmbeddedServer? = null @@ -41,6 +60,12 @@ actual constructor( protected actual var enableSsl: Boolean = false protected actual var enableCertVerify: Boolean = false + @OptIn(DelicateCoroutinesApi::class) + @AfterTest + fun tearDownBase() { + GlobalScope.launch { server?.stopSuspend(gracePeriodMillis = 0, timeoutMillis = 500) } + } + protected actual suspend fun createAndStartServer( log: Logger?, parent: CoroutineContext, @@ -57,7 +82,7 @@ actual constructor( return server } - server.stop(1L, 1L) + server.stopSuspend(1L, 1L) } error(lastFailures) @@ -68,7 +93,6 @@ actual constructor( parent: CoroutineContext = EmptyCoroutineContext, module: Application.() -> Unit ): EmbeddedServer { - val _port = this.port val environment = applicationEnvironment { val delegate = KtorSimpleLogger("io.ktor.test") this.log = log ?: object : Logger by delegate { @@ -89,7 +113,10 @@ actual constructor( } return embeddedServer(applicationEngineFactory, properties) { - connector { port = _port } + connector { + // the default port is zero, so that it will be automatically assigned when the server is started. + port = DEFAULT_PORT + } shutdownGracePeriod = 1000 shutdownTimeout = 1000 } @@ -102,8 +129,8 @@ actual constructor( // we start it on the global scope because we don't want it to fail the whole test // as far as we have retry loop on call side val starting = GlobalScope.async { - server.start(wait = false) - delay(500) + server.startSuspend(wait = false) + _port = server.engine.resolvedConnectors().first().port } return try { @@ -132,7 +159,7 @@ actual constructor( builder: suspend HttpRequestBuilder.() -> Unit, block: suspend HttpResponse.(Int) -> Unit ) { - HttpClient { + HttpClient(CIO) { followRedirects = false expectSuccess = false diff --git a/ktor-server/ktor-server-test-base/posix/src/io/ktor/server/test/base/EngineTestBaseNix.kt b/ktor-server/ktor-server-test-base/posix/src/io/ktor/server/test/base/EngineTestBaseNix.kt index b575aa151b8..95664b8c320 100644 --- a/ktor-server/ktor-server-test-base/posix/src/io/ktor/server/test/base/EngineTestBaseNix.kt +++ b/ktor-server/ktor-server-test-base/posix/src/io/ktor/server/test/base/EngineTestBaseNix.kt @@ -17,7 +17,6 @@ import io.ktor.server.engine.* import io.ktor.server.routing.* import io.ktor.server.testing.* import io.ktor.util.logging.* -import io.ktor.utils.io.core.* import kotlinx.coroutines.* import kotlin.coroutines.* import kotlin.time.Duration.Companion.seconds @@ -114,7 +113,8 @@ actual constructor( // as far as we have retry loop on call side val starting = GlobalScope.async { server.start(wait = false) - delay(500) + // await for a server to be started + server.engine.resolvedConnectors() } return try { diff --git a/ktor-server/ktor-server-test-host/build.gradle.kts b/ktor-server/ktor-server-test-host/build.gradle.kts index 0602940f9cb..b1cdc615b55 100644 --- a/ktor-server/ktor-server-test-host/build.gradle.kts +++ b/ktor-server/ktor-server-test-host/build.gradle.kts @@ -9,18 +9,13 @@ val jetty_alpn_boot_version: String? by extra kotlin.sourceSets { commonMain { dependencies { + api(project(":ktor-client:ktor-client-cio")) api(project(":ktor-server:ktor-server-core")) api(project(":ktor-client:ktor-client-core")) api(project(":ktor-test-dispatcher")) } } - jvmAndPosixMain { - dependencies { - api(project(":ktor-client:ktor-client-cio")) - } - } - jvmMain { dependencies { api(project(":ktor-network:ktor-network-tls")) diff --git a/ktor-server/ktor-server-test-host/common/src/io/ktor/server/testing/Utils.kt b/ktor-server/ktor-server-test-host/common/src/io/ktor/server/testing/Utils.kt index ba0c2e5a8a6..d96814f3302 100644 --- a/ktor-server/ktor-server-test-host/common/src/io/ktor/server/testing/Utils.kt +++ b/ktor-server/ktor-server-test-host/common/src/io/ktor/server/testing/Utils.kt @@ -9,7 +9,7 @@ import io.ktor.client.request.* import io.ktor.util.* import io.ktor.utils.io.* import kotlinx.coroutines.* -import kotlinx.io.* +import io.ktor.network.sockets.SocketTimeoutException as NetworkSocketTimeoutException /** * [on] function receiver object @@ -67,10 +67,3 @@ internal fun Throwable.mapToKtor(data: HttpRequestData): Throwable = when { cause?.rootCause is NetworkSocketTimeoutException -> SocketTimeoutException(data, cause?.rootCause) else -> this } - -// There are two SocketTimeoutException in ktor: -// * io.ktor.network.sockets.SocketTimeoutException -// * io.ktor.client.network.sockets.SocketTimeoutException -// on JVM they both are java.net.SocketTimeoutException, but on other targets it's not true -// additionally `network.sockets` exception is in `ktor-network` modules which don't have support for js/wasm target -internal expect class NetworkSocketTimeoutException(message: String) : IOException diff --git a/ktor-server/ktor-server-test-host/jsAndWasmShared/src/io/ktor/server/testing/Utils.jsAndWasmShared.kt b/ktor-server/ktor-server-test-host/jsAndWasmShared/src/io/ktor/server/testing/Utils.jsAndWasmShared.kt deleted file mode 100644 index 899cfecf918..00000000000 --- a/ktor-server/ktor-server-test-host/jsAndWasmShared/src/io/ktor/server/testing/Utils.jsAndWasmShared.kt +++ /dev/null @@ -1,9 +0,0 @@ -/* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. - */ - -package io.ktor.server.testing - -import kotlinx.io.* - -internal actual class NetworkSocketTimeoutException actual constructor(message: String) : IOException(message) diff --git a/ktor-server/ktor-server-test-host/jvm/src/io/ktor/server/testing/Utils.jvm.kt b/ktor-server/ktor-server-test-host/jvm/src/io/ktor/server/testing/Utils.jvm.kt deleted file mode 100644 index 0c95aad026c..00000000000 --- a/ktor-server/ktor-server-test-host/jvm/src/io/ktor/server/testing/Utils.jvm.kt +++ /dev/null @@ -1,8 +0,0 @@ -/* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. - */ - -package io.ktor.server.testing - -@Suppress("ACTUAL_WITHOUT_EXPECT") -internal actual typealias NetworkSocketTimeoutException = java.net.SocketTimeoutException diff --git a/ktor-server/ktor-server-test-host/posix/src/io/ktor/server/testing/Utils.posix.kt b/ktor-server/ktor-server-test-host/posix/src/io/ktor/server/testing/Utils.posix.kt deleted file mode 100644 index c33b6a98f29..00000000000 --- a/ktor-server/ktor-server-test-host/posix/src/io/ktor/server/testing/Utils.posix.kt +++ /dev/null @@ -1,8 +0,0 @@ -/* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. - */ - -package io.ktor.server.testing - -@Suppress("ACTUAL_WITHOUT_EXPECT") -internal actual typealias NetworkSocketTimeoutException = io.ktor.network.sockets.SocketTimeoutException diff --git a/ktor-server/ktor-server-test-suites/build.gradle.kts b/ktor-server/ktor-server-test-suites/build.gradle.kts index 84ed5f55904..90d1cc9ec15 100644 --- a/ktor-server/ktor-server-test-suites/build.gradle.kts +++ b/ktor-server/ktor-server-test-suites/build.gradle.kts @@ -12,7 +12,7 @@ kotlin.sourceSets { implementation(project(":ktor-server:ktor-server-plugins:ktor-server-status-pages")) implementation(project(":ktor-server:ktor-server-plugins:ktor-server-hsts")) implementation(project(":ktor-server:ktor-server-plugins:ktor-server-websockets")) - implementation(project(":ktor-server:ktor-server-test-base")) + api(project(":ktor-server:ktor-server-test-base")) } } diff --git a/ktor-server/ktor-server-test-suites/common/src/io/ktor/server/testing/suites/HttpServerCommonTestSuite.kt b/ktor-server/ktor-server-test-suites/common/src/io/ktor/server/testing/suites/HttpServerCommonTestSuite.kt index f29594ce514..73f459159a7 100644 --- a/ktor-server/ktor-server-test-suites/common/src/io/ktor/server/testing/suites/HttpServerCommonTestSuite.kt +++ b/ktor-server/ktor-server-test-suites/common/src/io/ktor/server/testing/suites/HttpServerCommonTestSuite.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.testing.suites @@ -32,6 +32,7 @@ import kotlinx.io.* import kotlin.coroutines.* import kotlin.test.* import kotlin.time.Duration.Companion.minutes +import kotlin.use abstract class HttpServerCommonTestSuite( hostFactory: ApplicationEngineFactory diff --git a/ktor-server/ktor-server-test-suites/jvmAndPosix/src/io/ktor/server/testing/suites/WebSocketEngineSuite.kt b/ktor-server/ktor-server-test-suites/common/src/io/ktor/server/testing/suites/WebSocketEngineSuite.kt similarity index 99% rename from ktor-server/ktor-server-test-suites/jvmAndPosix/src/io/ktor/server/testing/suites/WebSocketEngineSuite.kt rename to ktor-server/ktor-server-test-suites/common/src/io/ktor/server/testing/suites/WebSocketEngineSuite.kt index 920a0f382a7..f4e86cb77b3 100644 --- a/ktor-server/ktor-server-test-suites/jvmAndPosix/src/io/ktor/server/testing/suites/WebSocketEngineSuite.kt +++ b/ktor-server/ktor-server-test-suites/common/src/io/ktor/server/testing/suites/WebSocketEngineSuite.kt @@ -26,6 +26,7 @@ import kotlin.test.* import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.seconds +import kotlin.use @OptIn(InternalAPI::class) abstract class WebSocketEngineSuite( diff --git a/ktor-server/ktor-server-test-suites/jvm/src/io/ktor/server/testing/suites/HttpServerJvmTestSuite.kt b/ktor-server/ktor-server-test-suites/jvm/src/io/ktor/server/testing/suites/HttpServerJvmTestSuite.kt index d7e1469c61d..5c78a07a6d8 100644 --- a/ktor-server/ktor-server-test-suites/jvm/src/io/ktor/server/testing/suites/HttpServerJvmTestSuite.kt +++ b/ktor-server/ktor-server-test-suites/jvm/src/io/ktor/server/testing/suites/HttpServerJvmTestSuite.kt @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.testing.suites @@ -25,6 +25,7 @@ import kotlin.coroutines.* import kotlin.test.* import kotlin.text.toByteArray import kotlin.time.Duration.Companion.seconds +import kotlin.use abstract class HttpServerJvmTestSuite( hostFactory: ApplicationEngineFactory diff --git a/ktor-server/ktor-server-test-suites/jvm/src/io/ktor/server/testing/suites/SustainabilityTestSuite.kt b/ktor-server/ktor-server-test-suites/jvm/src/io/ktor/server/testing/suites/SustainabilityTestSuite.kt index fafa55381d4..443c3501590 100644 --- a/ktor-server/ktor-server-test-suites/jvm/src/io/ktor/server/testing/suites/SustainabilityTestSuite.kt +++ b/ktor-server/ktor-server-test-suites/jvm/src/io/ktor/server/testing/suites/SustainabilityTestSuite.kt @@ -35,6 +35,7 @@ import java.util.* import java.util.concurrent.* import java.util.concurrent.atomic.* import kotlin.test.* +import kotlin.use abstract class SustainabilityTestSuite( hostFactory: ApplicationEngineFactory diff --git a/ktor-server/ktor-server-tests/jvm/test/io/ktor/server/plugins/CompressionTest.kt b/ktor-server/ktor-server-tests/jvm/test/io/ktor/server/plugins/CompressionTest.kt index 9c979b8e31f..2d0d0c07834 100644 --- a/ktor-server/ktor-server-tests/jvm/test/io/ktor/server/plugins/CompressionTest.kt +++ b/ktor-server/ktor-server-tests/jvm/test/io/ktor/server/plugins/CompressionTest.kt @@ -642,24 +642,31 @@ class CompressionTest { install(Compression) routing { post("/identity") { + val message = call.receiveText() assertNull(call.request.headers[HttpHeaders.ContentEncoding]) assertEquals(listOf("identity"), call.request.appliedDecoders) - call.respond(call.receiveText()) + + call.respond(message) } post("/gzip") { + val message = call.receiveText() + assertNull(call.request.headers[HttpHeaders.ContentEncoding]) assertEquals(listOf("gzip"), call.request.appliedDecoders) - call.respond(call.receiveText()) + + call.respond(message) } post("/deflate") { + val message = call.receiveText() assertNull(call.request.headers[HttpHeaders.ContentEncoding]) assertEquals(listOf("deflate"), call.request.appliedDecoders) - call.respond(call.receiveText()) + call.respond(message) } post("/multiple") { + val message = call.receiveText() assertNull(call.request.headers[HttpHeaders.ContentEncoding]) assertEquals(listOf("identity", "deflate", "gzip"), call.request.appliedDecoders) - call.respond(call.receiveText()) + call.respond(message) } post("/unknown") { assertEquals("unknown", call.request.headers[HttpHeaders.ContentEncoding]) @@ -754,9 +761,38 @@ class CompressionTest { } routing { post("/gzip") { + val body = call.receive() + assertNull(call.request.headers[HttpHeaders.ContentEncoding]) + assertContentEquals(compressed, body) + + call.respond(textToCompressAsBytes) + } + } + + val response = client.post("/gzip") { + setBody(compressed) + header(HttpHeaders.ContentEncoding, "gzip") + header(HttpHeaders.AcceptEncoding, "gzip") + } + assertContentEquals(textToCompressAsBytes, response.body()) + } + + @Test + fun testDisableCallEncoding() = testApplication { + val compressed = GZip.encode(ByteReadChannel(textToCompressAsBytes)).readRemaining().readByteArray() + install(Compression) + + routing { + post("/gzip") { + call.suppressCompression() + val body = call.receive() - assertContentEquals(textToCompressAsBytes, body) + + assertEquals("gzip", call.request.appliedDecoders.first()) + assertNull(call.request.headers[HttpHeaders.ContentEncoding]) + assertContentEquals(compressed, body) + call.respond(textToCompressAsBytes) } } @@ -769,6 +805,29 @@ class CompressionTest { assertContentEquals(textToCompressAsBytes, response.body()) } + @Test + fun testDisableCallDecoding() = testApplication { + val compressed = GZip.encode(ByteReadChannel(textToCompressAsBytes)).readRemaining().readByteArray() + + install(Compression) + routing { + post("/gzip") { + call.suppressDecompression() + assertEquals("gzip", call.request.headers[HttpHeaders.ContentEncoding]) + val body = call.receive() + assertContentEquals(compressed, body) + call.respond(textToCompress) + } + } + + val response = client.post("/gzip") { + setBody(compressed) + header(HttpHeaders.ContentEncoding, "gzip") + header(HttpHeaders.AcceptEncoding, "gzip") + } + assertContentEquals(compressed, response.body()) + } + private suspend fun ApplicationTestBuilder.handleAndAssert( url: String, acceptHeader: String?, diff --git a/ktor-server/ktor-server-tests/jvmAndNix/test/io/ktor/tests/server/plugins/CORSTest.kt b/ktor-server/ktor-server-tests/jvmAndNix/test/io/ktor/tests/server/plugins/CORSTest.kt deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/ktor-shared/ktor-junit/jvm/src/io/ktor/junit/Assertions.kt b/ktor-shared/ktor-junit/jvm/src/io/ktor/junit/Assertions.kt index f5e0d07b1e8..9e1545f0fb4 100644 --- a/ktor-shared/ktor-junit/jvm/src/io/ktor/junit/Assertions.kt +++ b/ktor-shared/ktor-junit/jvm/src/io/ktor/junit/Assertions.kt @@ -4,6 +4,9 @@ package io.ktor.junit +import java.io.* +import kotlin.test.* + /** * Convenience function for asserting on all elements of a collection. */ @@ -29,3 +32,14 @@ fun assertAll(collection: Iterable, assertion: (T) -> Unit) { } ) } + +inline fun assertSerializable(obj: T, checkEquality: Boolean = true): T { + val encoded = ByteArrayOutputStream().also { + ObjectOutputStream(it).writeObject(obj) + }.toByteArray() + val decoded = ObjectInputStream(encoded.inputStream()).readObject() as T + if (checkEquality) { + assertEquals(obj, decoded, "deserialized object must be equal to original object") + } + return decoded +} diff --git a/ktor-shared/ktor-sse/api/ktor-sse.api b/ktor-shared/ktor-sse/api/ktor-sse.api index 4d9751075f9..7c6231a033e 100644 --- a/ktor-shared/ktor-sse/api/ktor-sse.api +++ b/ktor-shared/ktor-sse/api/ktor-sse.api @@ -1,12 +1,22 @@ -public final class io/ktor/sse/ServerSentEvent { +public final class io/ktor/sse/ServerSentEvent : io/ktor/sse/ServerSentEventMetadata { public fun ()V public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;Ljava/lang/String;)V public synthetic fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun getComments ()Ljava/lang/String; - public final fun getData ()Ljava/lang/String; - public final fun getEvent ()Ljava/lang/String; - public final fun getId ()Ljava/lang/String; - public final fun getRetry ()Ljava/lang/Long; + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Ljava/lang/String; + public final fun component3 ()Ljava/lang/String; + public final fun component4 ()Ljava/lang/Long; + public final fun component5 ()Ljava/lang/String; + public final fun copy (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;Ljava/lang/String;)Lio/ktor/sse/ServerSentEvent; + public static synthetic fun copy$default (Lio/ktor/sse/ServerSentEvent;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;Ljava/lang/String;ILjava/lang/Object;)Lio/ktor/sse/ServerSentEvent; + public fun equals (Ljava/lang/Object;)Z + public fun getComments ()Ljava/lang/String; + public synthetic fun getData ()Ljava/lang/Object; + public fun getData ()Ljava/lang/String; + public fun getEvent ()Ljava/lang/String; + public fun getId ()Ljava/lang/String; + public fun getRetry ()Ljava/lang/Long; + public fun hashCode ()I public fun toString ()Ljava/lang/String; } @@ -17,3 +27,33 @@ public final class io/ktor/sse/ServerSentEventKt { public static final fun getEND_OF_LINE_VARIANTS ()Lkotlin/text/Regex; } +public abstract interface class io/ktor/sse/ServerSentEventMetadata { + public abstract fun getComments ()Ljava/lang/String; + public abstract fun getData ()Ljava/lang/Object; + public abstract fun getEvent ()Ljava/lang/String; + public abstract fun getId ()Ljava/lang/String; + public abstract fun getRetry ()Ljava/lang/Long; +} + +public final class io/ktor/sse/TypedServerSentEvent : io/ktor/sse/ServerSentEventMetadata { + public fun ()V + public fun (Ljava/lang/Object;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;Ljava/lang/String;)V + public synthetic fun (Ljava/lang/Object;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/Object; + public final fun component2 ()Ljava/lang/String; + public final fun component3 ()Ljava/lang/String; + public final fun component4 ()Ljava/lang/Long; + public final fun component5 ()Ljava/lang/String; + public final fun copy (Ljava/lang/Object;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;Ljava/lang/String;)Lio/ktor/sse/TypedServerSentEvent; + public static synthetic fun copy$default (Lio/ktor/sse/TypedServerSentEvent;Ljava/lang/Object;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;Ljava/lang/String;ILjava/lang/Object;)Lio/ktor/sse/TypedServerSentEvent; + public fun equals (Ljava/lang/Object;)Z + public fun getComments ()Ljava/lang/String; + public fun getData ()Ljava/lang/Object; + public fun getEvent ()Ljava/lang/String; + public fun getId ()Ljava/lang/String; + public fun getRetry ()Ljava/lang/Long; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; + public final fun toString (Lkotlin/jvm/functions/Function1;)Ljava/lang/String; +} + diff --git a/ktor-shared/ktor-sse/api/ktor-sse.klib.api b/ktor-shared/ktor-sse/api/ktor-sse.klib.api index 9aa81adf36b..b53022fb7bd 100644 --- a/ktor-shared/ktor-sse/api/ktor-sse.klib.api +++ b/ktor-shared/ktor-sse/api/ktor-sse.klib.api @@ -6,7 +6,46 @@ // - Show declarations: true // Library unique name: -final class io.ktor.sse/ServerSentEvent { // io.ktor.sse/ServerSentEvent|null[0] +sealed interface <#A: kotlin/Any?> io.ktor.sse/ServerSentEventMetadata { // io.ktor.sse/ServerSentEventMetadata|null[0] + abstract val comments // io.ktor.sse/ServerSentEventMetadata.comments|{}comments[0] + abstract fun (): kotlin/String? // io.ktor.sse/ServerSentEventMetadata.comments.|(){}[0] + abstract val data // io.ktor.sse/ServerSentEventMetadata.data|{}data[0] + abstract fun (): #A? // io.ktor.sse/ServerSentEventMetadata.data.|(){}[0] + abstract val event // io.ktor.sse/ServerSentEventMetadata.event|{}event[0] + abstract fun (): kotlin/String? // io.ktor.sse/ServerSentEventMetadata.event.|(){}[0] + abstract val id // io.ktor.sse/ServerSentEventMetadata.id|{}id[0] + abstract fun (): kotlin/String? // io.ktor.sse/ServerSentEventMetadata.id.|(){}[0] + abstract val retry // io.ktor.sse/ServerSentEventMetadata.retry|{}retry[0] + abstract fun (): kotlin/Long? // io.ktor.sse/ServerSentEventMetadata.retry.|(){}[0] +} + +final class <#A: kotlin/Any?> io.ktor.sse/TypedServerSentEvent : io.ktor.sse/ServerSentEventMetadata<#A> { // io.ktor.sse/TypedServerSentEvent|null[0] + constructor (#A? = ..., kotlin/String? = ..., kotlin/String? = ..., kotlin/Long? = ..., kotlin/String? = ...) // io.ktor.sse/TypedServerSentEvent.|(1:0?;kotlin.String?;kotlin.String?;kotlin.Long?;kotlin.String?){}[0] + + final val comments // io.ktor.sse/TypedServerSentEvent.comments|{}comments[0] + final fun (): kotlin/String? // io.ktor.sse/TypedServerSentEvent.comments.|(){}[0] + final val data // io.ktor.sse/TypedServerSentEvent.data|{}data[0] + final fun (): #A? // io.ktor.sse/TypedServerSentEvent.data.|(){}[0] + final val event // io.ktor.sse/TypedServerSentEvent.event|{}event[0] + final fun (): kotlin/String? // io.ktor.sse/TypedServerSentEvent.event.|(){}[0] + final val id // io.ktor.sse/TypedServerSentEvent.id|{}id[0] + final fun (): kotlin/String? // io.ktor.sse/TypedServerSentEvent.id.|(){}[0] + final val retry // io.ktor.sse/TypedServerSentEvent.retry|{}retry[0] + final fun (): kotlin/Long? // io.ktor.sse/TypedServerSentEvent.retry.|(){}[0] + + final fun component1(): #A? // io.ktor.sse/TypedServerSentEvent.component1|component1(){}[0] + final fun component2(): kotlin/String? // io.ktor.sse/TypedServerSentEvent.component2|component2(){}[0] + final fun component3(): kotlin/String? // io.ktor.sse/TypedServerSentEvent.component3|component3(){}[0] + final fun component4(): kotlin/Long? // io.ktor.sse/TypedServerSentEvent.component4|component4(){}[0] + final fun component5(): kotlin/String? // io.ktor.sse/TypedServerSentEvent.component5|component5(){}[0] + final fun copy(#A? = ..., kotlin/String? = ..., kotlin/String? = ..., kotlin/Long? = ..., kotlin/String? = ...): io.ktor.sse/TypedServerSentEvent<#A> // io.ktor.sse/TypedServerSentEvent.copy|copy(1:0?;kotlin.String?;kotlin.String?;kotlin.Long?;kotlin.String?){}[0] + final fun equals(kotlin/Any?): kotlin/Boolean // io.ktor.sse/TypedServerSentEvent.equals|equals(kotlin.Any?){}[0] + final fun hashCode(): kotlin/Int // io.ktor.sse/TypedServerSentEvent.hashCode|hashCode(){}[0] + final fun toString(): kotlin/String // io.ktor.sse/TypedServerSentEvent.toString|toString(){}[0] + final fun toString(kotlin/Function1<#A, kotlin/String>): kotlin/String // io.ktor.sse/TypedServerSentEvent.toString|toString(kotlin.Function1<1:0,kotlin.String>){}[0] +} + +final class io.ktor.sse/ServerSentEvent : io.ktor.sse/ServerSentEventMetadata { // io.ktor.sse/ServerSentEvent|null[0] constructor (kotlin/String? = ..., kotlin/String? = ..., kotlin/String? = ..., kotlin/Long? = ..., kotlin/String? = ...) // io.ktor.sse/ServerSentEvent.|(kotlin.String?;kotlin.String?;kotlin.String?;kotlin.Long?;kotlin.String?){}[0] final val comments // io.ktor.sse/ServerSentEvent.comments|{}comments[0] @@ -20,6 +59,14 @@ final class io.ktor.sse/ServerSentEvent { // io.ktor.sse/ServerSentEvent|null[0] final val retry // io.ktor.sse/ServerSentEvent.retry|{}retry[0] final fun (): kotlin/Long? // io.ktor.sse/ServerSentEvent.retry.|(){}[0] + final fun component1(): kotlin/String? // io.ktor.sse/ServerSentEvent.component1|component1(){}[0] + final fun component2(): kotlin/String? // io.ktor.sse/ServerSentEvent.component2|component2(){}[0] + final fun component3(): kotlin/String? // io.ktor.sse/ServerSentEvent.component3|component3(){}[0] + final fun component4(): kotlin/Long? // io.ktor.sse/ServerSentEvent.component4|component4(){}[0] + final fun component5(): kotlin/String? // io.ktor.sse/ServerSentEvent.component5|component5(){}[0] + final fun copy(kotlin/String? = ..., kotlin/String? = ..., kotlin/String? = ..., kotlin/Long? = ..., kotlin/String? = ...): io.ktor.sse/ServerSentEvent // io.ktor.sse/ServerSentEvent.copy|copy(kotlin.String?;kotlin.String?;kotlin.String?;kotlin.Long?;kotlin.String?){}[0] + final fun equals(kotlin/Any?): kotlin/Boolean // io.ktor.sse/ServerSentEvent.equals|equals(kotlin.Any?){}[0] + final fun hashCode(): kotlin/Int // io.ktor.sse/ServerSentEvent.hashCode|hashCode(){}[0] final fun toString(): kotlin/String // io.ktor.sse/ServerSentEvent.toString|toString(){}[0] } diff --git a/ktor-shared/ktor-sse/common/src/io/ktor/sse/ServerSentEvent.kt b/ktor-shared/ktor-sse/common/src/io/ktor/sse/ServerSentEvent.kt index ad1cf960b56..fe064d38ced 100644 --- a/ktor-shared/ktor-sse/common/src/io/ktor/sse/ServerSentEvent.kt +++ b/ktor-shared/ktor-sse/common/src/io/ktor/sse/ServerSentEvent.kt @@ -6,6 +6,26 @@ package io.ktor.sse import io.ktor.utils.io.* +/** + * Server-sent event interface. + * + * @property data data field of the event. + * @property event string identifying the type of event. + * @property id event ID. + * @property retry reconnection time, in milliseconds to wait before reconnecting. + * @property comments comment lines starting with a ':' character. + * + * @see ServerSentEvent with default String parameter `data` + * @see TypedServerSentEvent with parameterized parameter `data` + */ +public sealed interface ServerSentEventMetadata { + public val data: T? + public val event: String? + public val id: String? + public val retry: Long? + public val comments: String? +} + /** * Server-sent event. * @@ -14,22 +34,49 @@ import io.ktor.utils.io.* * @property id event ID. * @property retry reconnection time, in milliseconds to wait before reconnecting. * @property comments comment lines starting with a ':' character. + * + * @see TypedServerSentEvent with parameterized parameter `data` */ -public class ServerSentEvent( - public val data: String? = null, - public val event: String? = null, - public val id: String? = null, - public val retry: Long? = null, - public val comments: String? = null -) { - override fun toString(): String { - return buildString { - appendField("data", data) - appendField("event", event) - appendField("id", id) - appendField("retry", retry) - appendField("", comments) - } +public data class ServerSentEvent( + override val data: String? = null, + override val event: String? = null, + override val id: String? = null, + override val retry: Long? = null, + override val comments: String? = null +) : ServerSentEventMetadata { + override fun toString(): String = eventToString(data, event, id, retry, comments) +} + +/** + * Server-sent event with generic parameter [data]. + * + * @property data data field of the event. + * @property event string identifying the type of event. + * @property id event ID. + * @property retry reconnection time, in milliseconds to wait before reconnecting. + * @property comments comment lines starting with a ':' character. + * + * @see ServerSentEvent with default String parameter `data` + */ +public data class TypedServerSentEvent( + override val data: T? = null, + override val event: String? = null, + override val id: String? = null, + override val retry: Long? = null, + override val comments: String? = null +) : ServerSentEventMetadata { + @InternalAPI + public fun toString(serializer: (T) -> String): String = + eventToString(data?.let { serializer(it) }, event, id, retry, comments) +} + +private fun eventToString(data: String?, event: String?, id: String?, retry: Long?, comments: String?): String { + return buildString { + appendField("data", data) + appendField("event", event) + appendField("id", id) + appendField("retry", retry) + appendField("", comments) } } diff --git a/ktor-utils/jvm/src/io/ktor/util/cio/FileChannels.kt b/ktor-utils/jvm/src/io/ktor/util/cio/FileChannels.kt index e673f52f114..c6b72d89991 100644 --- a/ktor-utils/jvm/src/io/ktor/util/cio/FileChannels.kt +++ b/ktor-utils/jvm/src/io/ktor/util/cio/FileChannels.kt @@ -1,12 +1,10 @@ /* - * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. + * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.util.cio -import io.ktor.util.* import io.ktor.utils.io.* -import io.ktor.utils.io.core.* import io.ktor.utils.io.jvm.nio.* import kotlinx.coroutines.* import java.io.* diff --git a/ktor-utils/jvm/test/io/ktor/tests/utils/FileChannelTest.kt b/ktor-utils/jvm/test/io/ktor/tests/utils/FileChannelTest.kt index 3a32b8dc2d9..e6af6335ae6 100644 --- a/ktor-utils/jvm/test/io/ktor/tests/utils/FileChannelTest.kt +++ b/ktor-utils/jvm/test/io/ktor/tests/utils/FileChannelTest.kt @@ -9,9 +9,11 @@ import io.ktor.util.cio.* import io.ktor.utils.io.* import io.ktor.utils.io.jvm.javaio.* import kotlinx.coroutines.* +import kotlinx.coroutines.test.runTest import org.junit.jupiter.api.* import org.junit.jupiter.api.extension.* import java.io.* +import java.nio.file.Files import kotlin.test.* import kotlin.test.Test @@ -117,4 +119,23 @@ class FileChannelTest { // Assert (we cannot delete if there is a file handle open on it) assertTrue(temp.delete()) } + + @Test + fun `writeChannel finishes on close`() = runTest { + val file = Files.createTempFile("file", "txt").toFile() + val ch = file.writeChannel() + ch.writeStringUtf8("Hello") + ch.flushAndClose() + assertEquals(5, file.length()) + assertEquals("Hello", file.readText()) + } + + @Test + fun `writeChannel writes to file on flush`() = runTest { + val file = Files.createTempFile("file", "txt").toFile() + val ch = file.writeChannel() + ch.writeStringUtf8("Hello") + ch.flush() + assertEquals("Hello", file.readText()) + } }