diff --git a/README.md b/README.md index 7caa13127..6cb0e2416 100644 --- a/README.md +++ b/README.md @@ -71,9 +71,10 @@ Maven to add the [protobuf-java](https://mvnrepository.com/artifact/com.google.protobuf/protobuf-java) dependency. * Note: To eliminate any errors or warnings, you should try and match the same version JavaSteam uses.

-* Content Downloading: - * Add the following dependencies to your project: [XZ For Java](https://mvnrepository.com/artifact/org.tukaani/xz) and [ZSTD JNI](https://mvnrepository.com/artifact/com.github.luben/zstd-jni). - * ZSTD for android uses `aar` for the libray type. +* Content Downloading (required if you download depots, otherwise optional): + * Add [XZ For Java](https://mvnrepository.com/artifact/org.tukaani/xz) and [ZSTD JNI](https://mvnrepository.com/artifact/com.github.luben/zstd-jni) to your project. + Without them, downloads fail with a `NoClassDefFoundError`. + * On Android, ZSTD must be the `aar` artifact: `implementation("com.github.luben:zstd-jni:@aar")` You can find the latest version of these dependencies JavaSteam supports [here](https://github.com/Longi94/JavaSteam/blob/master/gradle/libs.versions.toml). diff --git a/build.gradle.kts b/build.gradle.kts index 14a553a9f..67dabcb6d 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -21,7 +21,7 @@ plugins { allprojects { group = "in.dragonbra" - version = "1.8.1-SNAPSHOT" + version = "1.9.0-SNAPSHOT" } repositories { diff --git a/buildSrc/src/main/kotlin/in/dragonbra/generators/rpc/RpcGenTask.kt b/buildSrc/src/main/kotlin/in/dragonbra/generators/rpc/RpcGenTask.kt index 266115a88..28e48f0c1 100644 --- a/buildSrc/src/main/kotlin/in/dragonbra/generators/rpc/RpcGenTask.kt +++ b/buildSrc/src/main/kotlin/in/dragonbra/generators/rpc/RpcGenTask.kt @@ -52,7 +52,7 @@ abstract class RpcGenTask : DefaultTask { outputDir.deleteRecursively() outputDir.mkdirs() - val protoParser = ProtoParser(outputDir) + val protoParser = ProtoParser(outputDir, protoDirectory) protoDirectory.walkTopDown() .filter { it.isFile && it.extension == "proto" } diff --git a/buildSrc/src/main/kotlin/in/dragonbra/generators/rpc/parser/ProtoParser.kt b/buildSrc/src/main/kotlin/in/dragonbra/generators/rpc/parser/ProtoParser.kt index d3dc4c9c0..c37748c83 100644 --- a/buildSrc/src/main/kotlin/in/dragonbra/generators/rpc/parser/ProtoParser.kt +++ b/buildSrc/src/main/kotlin/in/dragonbra/generators/rpc/parser/ProtoParser.kt @@ -5,7 +5,7 @@ import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import java.io.File import java.util.* -class ProtoParser(private val outputDir: File) { +class ProtoParser(private val outputDir: File, private val protoRoot: File) { private companion object { private const val RPC_PACKAGE = "in.dragonbra.javasteam.rpc" @@ -19,6 +19,60 @@ class ProtoParser(private val outputDir: File) { .addMember("%S", "RedundantVisibilityModifier") // KotlinPoet is an explicit API generator .addMember("%S", "unused") // All methods could be used. .build() + + private val topLevelMessageRegex = Regex("""(?m)^message\s+(\w+)""") + private val importRegex = Regex("""(?m)^import\s+(?:public\s+)?"([^"]+)"\s*;""") + } + + // Top-level message names declared by each .proto file. + private val messagesByFile = mutableMapOf>() + + // Files imported by each .proto file, limited to the ones that live under [protoRoot]. + private val importsByFile = mutableMapOf>() + + private fun messagesOf(file: File): Set = messagesByFile.getOrPut(file) { + topLevelMessageRegex.findAll(file.readText()).map { it.groupValues[1] }.toSet() + } + + private fun importsOf(file: File): List = importsByFile.getOrPut(file) { + importRegex.findAll(file.readText()) + .map { File(protoRoot, it.groupValues[1]).canonicalFile } + .filter { it.isFile } + .toList() + } + + /** + * Find the .proto file that declares [type], starting at [file] and then walking its imports breadth first. + * A service can use messages declared in an imported file (e.g. webui services and common.proto), + * and the generated Java class is nested in the outer class of the declaring file. + * Falls back to [file] if no declaration is found. + */ + private fun findDeclaringFile(file: File, type: String): File { + val start = file.canonicalFile + val visited = mutableSetOf(start) + val queue = ArrayDeque().apply { add(start) } + + while (queue.isNotEmpty()) { + val current = queue.removeFirst() + if (type in messagesOf(current)) { + return current + } + importsOf(current).filter(visited::add).forEach(queue::add) + } + + return start + } + + /** + * The generated protobuf class of [type], as referenced from [file]. + */ + private fun messageClassName(file: File, type: String): ClassName { + val declaringFile = findDeclaringFile(file, type) + return ClassName( + packageName = "in.dragonbra.javasteam.protobufs." + + "${declaringFile.parentFile.name}.${transformProtoFileName(declaringFile.name)}", + type + ) } /** @@ -85,8 +139,6 @@ class ProtoParser(private val outputDir: File) { * Build the [Service] to a class with all known RPC methods. */ private fun buildClass(file: File, service: Service) { - val protoFileName = transformProtoFileName(file.name) - val parentPathName = file.parentFile.name // Class Builder @@ -132,10 +184,7 @@ class ProtoParser(private val outputDir: File) { if (method.responseType != "NoResponse") { // HAS Response numResponse++ - val className = ClassName( - packageName = "in.dragonbra.javasteam.protobufs.$parentPathName.$protoFileName", - method.responseType - ) + val className = messageClassName(file, method.responseType) responseBlock.addStatement( "\"${method.methodName}\" -> postResponseMsg<%T.Builder>(\n%T::class.java,\npacketMsg\n)", className, @@ -144,10 +193,7 @@ class ProtoParser(private val outputDir: File) { } else { // NO Response numNotification++ - val className = ClassName( - packageName = "in.dragonbra.javasteam.protobufs.$parentPathName.$protoFileName", - method.requestType - ) + val className = messageClassName(file, method.requestType) notificationBlock.addStatement( "\"${method.methodName}\" -> postNotificationMsg<%T.Builder>(\n%T::class.java,\npacketMsg\n)", className, @@ -201,10 +247,7 @@ class ProtoParser(private val outputDir: File) { .addModifiers(KModifier.PUBLIC) .addParameter( "request", - ClassName( - packageName = "in.dragonbra.javasteam.protobufs.$parentPathName.$protoFileName", - method.requestType - ) + messageClassName(file, method.requestType) ) if (method.responseType != "NoResponse") { @@ -217,16 +260,13 @@ class ProtoParser(private val outputDir: File) { funcBuilder.returns( asyncJobSingleClass.parameterizedBy( serviceMethodResponseClass.parameterizedBy( - ClassName.bestGuess("in.dragonbra.javasteam.protobufs.$parentPathName.$protoFileName.${method.responseType}.Builder") + messageClassName(file, method.responseType).nestedClass("Builder") ) ) ) funcBuilder.addStatement( format = "return unifiedMessages!!.sendMessage(\n%T.Builder::class.java,\n%S,\nrequest\n)", - ClassName( - packageName = "in.dragonbra.javasteam.protobufs.$parentPathName.$protoFileName", - method.responseType - ), + messageClassName(file, method.responseType), "${service.name}.${method.methodName}#1" ) } else { @@ -238,10 +278,7 @@ class ProtoParser(private val outputDir: File) { ) funcBuilder.addStatement( format = "unifiedMessages!!.sendNotification<%T.Builder>(\n%S,\nrequest\n)", - ClassName( - packageName = "in.dragonbra.javasteam.protobufs.$parentPathName.$protoFileName", - method.requestType - ), + messageClassName(file, method.requestType), "${service.name}.${method.methodName}#1" ) } diff --git a/gradle.properties b/gradle.properties index 11202a53f..4515566de 100644 --- a/gradle.properties +++ b/gradle.properties @@ -18,3 +18,6 @@ org.gradle.jvmargs=-Xmx4g -Didea.max.content.load.filesize=65536 kotlin.daemon.jvmargs=-Xmx2048m -Didea.max.content.load.filesize=65536 org.jetbrains.dokka.experimental.gradle.pluginMode.noWarn=true + +# Enabled parallel sync for Gradle 9.4+ +org.gradle.tooling.parallel=true diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index eda83f5ea..3132e2438 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -13,7 +13,6 @@ jacoco = "0.8.16" # https://www.eclemma.org/jacoco # Standard Library versions commons-lang3 = "3.21.0" # https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 kotlin-coroutines = "1.11.0" # https://mvnrepository.com/artifact/org.jetbrains.kotlinx/kotlinx-coroutines-core -ktor = "3.6.1" # https://mvnrepository.com/artifact/io.ktor/ktor-client-cio okHttp = "5.5.1" # https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp protobuf = "4.36.2" # https://mvnrepository.com/artifact/com.google.protobuf/protobuf-java protobuf-gradle = "0.10.1" # https://mvnrepository.com/artifact/com.google.protobuf/protobuf-gradle-plugin @@ -42,9 +41,6 @@ qrCode = "1.0.1" # https://mvnrepository.com/artifact/pro.leaco.qrcode/console-q commons-lang3 = { module = "org.apache.commons:commons-lang3", version.ref = "commons-lang3" } kotlin-coroutines = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "kotlin-coroutines" } kotlin-stdib = { module = "org.jetbrains.kotlin:kotlin-stdlib-jdk8", version.ref = "kotlin" } -ktor-client-cio = { module = "io.ktor:ktor-client-cio", version.ref = "ktor" } -ktor-client-core = { module = "io.ktor:ktor-client-core", version.ref = "ktor" } -ktor-client-websocket = { module = "io.ktor:ktor-client-websockets", version.ref = "ktor" } okHttp = { module = "com.squareup.okhttp3:okhttp", version.ref = "okHttp" } okHttp-coroutines = { module = "com.squareup.okhttp3:okhttp-coroutines", version.ref = "okHttp" } protobuf-java = { module = "com.google.protobuf:protobuf-java", version.ref = "protobuf" } @@ -96,12 +92,6 @@ testing = [ "zstd", ] -ktor = [ - "ktor-client-core", - "ktor-client-cio", - "ktor-client-websocket", -] - okHttp = [ "okHttp", "okHttp-coroutines", diff --git a/javasteam-cs/src/main/proto/in/dragonbra/javasteam/protobufs/cs/netmessages.proto b/javasteam-cs/src/main/proto/in/dragonbra/javasteam/protobufs/cs/netmessages.proto index b1c3ba2c9..3a6692556 100644 --- a/javasteam-cs/src/main/proto/in/dragonbra/javasteam/protobufs/cs/netmessages.proto +++ b/javasteam-cs/src/main/proto/in/dragonbra/javasteam/protobufs/cs/netmessages.proto @@ -322,6 +322,8 @@ message CSVCMsg_Menu { } message CSVCMsg_UserMessage { + option (maximum_size_bytes) = 0; + optional int32 msg_type = 1; optional bytes msg_data = 2; optional int32 passthrough = 3; @@ -419,9 +421,10 @@ message CSVCMsg_CreateStringTable { optional int32 user_data_size_bits = 5; optional int32 flags = 6; optional bytes string_data = 7; - optional int32 uncompressed_size = 8; optional bool data_compressed = 9; optional bool using_varint_bitcounts = 10; + + reserved 8; } message CSVCMsg_UpdateStringTable { diff --git a/javasteam-cs/src/main/proto/in/dragonbra/javasteam/protobufs/cs/source2_steam_stats.proto b/javasteam-cs/src/main/proto/in/dragonbra/javasteam/protobufs/cs/source2_steam_stats.proto index c75d0ab9f..686e2cc88 100644 --- a/javasteam-cs/src/main/proto/in/dragonbra/javasteam/protobufs/cs/source2_steam_stats.proto +++ b/javasteam-cs/src/main/proto/in/dragonbra/javasteam/protobufs/cs/source2_steam_stats.proto @@ -29,6 +29,9 @@ message CMsgSource2SystemSpecs { optional string cpu_brand = 2; optional uint32 cpu_model = 3; optional uint32 cpu_num_physical = 4; + optional uint32 cpu_num_logical = 5; + optional uint32 cpu_num_performance = 6; + optional uint32 cpu_num_efficiency = 7; optional uint32 ram_physical_total_mb = 21; optional string gpu_rendersystem_dll_name = 41; optional uint32 gpu_vendor_id = 42; @@ -39,6 +42,7 @@ message CMsgSource2SystemSpecs { optional uint32 gpu_texture_memory_size_mb = 47; optional uint32 backbuffer_width = 51; optional uint32 backbuffer_height = 52; + optional uint32 thread_pool_workers = 61; } message CMsgSource2VProfLiteReportItem { diff --git a/javasteam-deadlock/src/main/proto/in/dragonbra/javasteam/protobufs/deadlock/citadel_gcmessages_client.proto b/javasteam-deadlock/src/main/proto/in/dragonbra/javasteam/protobufs/deadlock/citadel_gcmessages_client.proto index aaeca0076..9ffa394fc 100644 --- a/javasteam-deadlock/src/main/proto/in/dragonbra/javasteam/protobufs/deadlock/citadel_gcmessages_client.proto +++ b/javasteam-deadlock/src/main/proto/in/dragonbra/javasteam/protobufs/deadlock/citadel_gcmessages_client.proto @@ -402,6 +402,8 @@ message CSOAccountHeroInfo { optional uint32 wins = 4; optional uint32 hero_xp = 6; optional uint32 brawl_wins = 7; + optional uint32 losses = 8; + optional uint32 brawl_losses = 9; } message CSOAccountChallenge { diff --git a/javasteam-deadlock/src/main/proto/in/dragonbra/javasteam/protobufs/deadlock/citadel_gcmessages_common.proto b/javasteam-deadlock/src/main/proto/in/dragonbra/javasteam/protobufs/deadlock/citadel_gcmessages_common.proto index 4131a1f7e..a1b7c2ae6 100644 --- a/javasteam-deadlock/src/main/proto/in/dragonbra/javasteam/protobufs/deadlock/citadel_gcmessages_common.proto +++ b/javasteam-deadlock/src/main/proto/in/dragonbra/javasteam/protobufs/deadlock/citadel_gcmessages_common.proto @@ -157,6 +157,7 @@ enum ECitadelGameMode { k_ECitadelGameMode_StreetBrawl = 4; k_ECitadelGameMode_ExploreNYC = 5; k_ECitadelGameMode_Internal = 6; + k_ECitadelGameMode_Internal02 = 7; } enum ELobbyServerState { @@ -263,6 +264,7 @@ message CSOCitadelHideoutLobby { optional uint32 account_id = 1; optional bool hideout_holiday_award_2024 = 30; optional bool hideout_holiday_award_2025 = 32; + optional uint32 ranked_season_1_season_rank = 33; } enum EServerStatus { @@ -380,6 +382,7 @@ message CSOCitadelParty { optional uint32 rank_display_badge = 3; repeated uint32 unlocked_heroes = 5; optional bool in_calibration = 6; + optional uint32 max_rank_display_badge = 7; } message Member { diff --git a/javasteam-deadlock/src/main/proto/in/dragonbra/javasteam/protobufs/deadlock/citadel_gcmessages_server.proto b/javasteam-deadlock/src/main/proto/in/dragonbra/javasteam/protobufs/deadlock/citadel_gcmessages_server.proto index be750a2a2..3721f6195 100644 --- a/javasteam-deadlock/src/main/proto/in/dragonbra/javasteam/protobufs/deadlock/citadel_gcmessages_server.proto +++ b/javasteam-deadlock/src/main/proto/in/dragonbra/javasteam/protobufs/deadlock/citadel_gcmessages_server.proto @@ -688,6 +688,7 @@ message CMsgMatchData { optional uint32 flags = 5; optional uint32 imbued_ability_id = 6; optional uint32 upgrade_info = 7; + optional uint32 purchase_source = 8; } message AuxStat { diff --git a/javasteam-depotdownloader/build.gradle.kts b/javasteam-depotdownloader/build.gradle.kts index 5e01a53d0..af39122f8 100644 --- a/javasteam-depotdownloader/build.gradle.kts +++ b/javasteam-depotdownloader/build.gradle.kts @@ -66,13 +66,23 @@ tasks.withType { dependencies { implementation(rootProject) - implementation(libs.bundles.ktor) + implementation(libs.bundles.okHttp) implementation(libs.commons.lang3) implementation(libs.kotlin.coroutines) implementation(libs.kotlin.serialization.json) implementation(libs.kotlin.stdib) implementation(libs.okio) implementation(libs.protobuf.java) + + testImplementation(platform(libs.tests.junit.bom)) + testImplementation(libs.tests.junit.jupiter) + testImplementation(libs.test.mock.webserver3) + testRuntimeOnly(libs.tests.junit.platform) +} + +/* Testing */ +tasks.test { + useJUnitPlatform() } /* Artifact publishing */ diff --git a/javasteam-depotdownloader/src/main/kotlin/in/dragonbra/javasteam/depotdownloader/CDNClientPool.kt b/javasteam-depotdownloader/src/main/kotlin/in/dragonbra/javasteam/depotdownloader/CDNClientPool.kt index e90a98414..76df8e3b2 100644 --- a/javasteam-depotdownloader/src/main/kotlin/in/dragonbra/javasteam/depotdownloader/CDNClientPool.kt +++ b/javasteam-depotdownloader/src/main/kotlin/in/dragonbra/javasteam/depotdownloader/CDNClientPool.kt @@ -7,6 +7,7 @@ import `in`.dragonbra.javasteam.util.log.Logger import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock +import okhttp3.OkHttpClient import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicReference @@ -20,6 +21,7 @@ import java.util.concurrent.atomic.AtomicReference * @param appId The application ID to download - used to filter compatible CDN servers * @param scope The coroutine scope for async operations * @param debug If true, enables debug logging + * @param httpClient The HTTP client to download with. Defaults to the one of the SteamClient configuration. * * @author Oxters * @author Lossy @@ -30,9 +32,13 @@ class CDNClientPool( private val appId: Int, private val scope: CoroutineScope, debug: Boolean = false, + httpClient: OkHttpClient? = null, ) : AutoCloseable { - private var logger: Logger? = null + // Errors are always logged. + private val log: Logger = LogManager.getLogger(CDNClientPool::class.java) + + private val logger: Logger? = if (debug) log else null private val servers = AtomicReference>(emptyList()) @@ -47,11 +53,7 @@ class CDNClientPool( private set init { - cdnClient = Client(steamSession.steamClient) - - if (debug) { - logger = LogManager.getLogger(CDNClientPool::class.java) - } + cdnClient = Client(steamSession.steamClient, httpClient ?: steamSession.steamClient.configuration.httpClient) } /** @@ -65,8 +67,6 @@ class CDNClientPool( cdnClient = null proxyServer = null - - logger = null } /** @@ -133,7 +133,7 @@ class CDNClientPool( */ fun returnConnection(server: Server?) { if (server == null) { - logger?.error("null server returned to cdn pool.") + log.error("null server returned to cdn pool.") return } @@ -160,7 +160,7 @@ class CDNClientPool( */ fun returnBrokenConnection(server: Server?) { if (server == null) { - logger?.error("null broken server returned to pool") + log.error("null broken server returned to pool") return } @@ -168,7 +168,7 @@ class CDNClientPool( val updated = servers.updateAndGet { it.filter { s -> s != server } } if (updated.isEmpty()) { - logger?.error("No CDN servers remaining after removing broken connection: $server") + log.error("No CDN servers remaining after removing broken connection: $server") } // TODO: (SK) Add server to ContentServerPenalty diff --git a/javasteam-depotdownloader/src/main/kotlin/in/dragonbra/javasteam/depotdownloader/ChunkBufferPool.kt b/javasteam-depotdownloader/src/main/kotlin/in/dragonbra/javasteam/depotdownloader/ChunkBufferPool.kt new file mode 100644 index 000000000..a339a9bda --- /dev/null +++ b/javasteam-depotdownloader/src/main/kotlin/in/dragonbra/javasteam/depotdownloader/ChunkBufferPool.kt @@ -0,0 +1,63 @@ +package `in`.dragonbra.javasteam.depotdownloader + +/** + * Reuses the byte arrays a chunk passes through (downloaded, then decompressed), so a download + * does not allocate two fresh arrays for every chunk. + * + * Every pooled array has the same size, [BUFFER_SIZE], so any of them fits either use. A rented + * array is usually longer than the data in it: callers must carry the length of the data + * themselves and never use the array's size. + * + * A rented array that is never given back is harmless, it is simply garbage collected. An array + * must not be given back twice, or while anything still reads or writes it. + * + * @param maxIdle The most arrays kept while not in use. Arrays given back beyond that are dropped. + */ +internal class ChunkBufferPool(maxIdle: Int) { + + companion object { + /** + * Depot chunks are at most 1 MiB uncompressed. The slack is for a chunk that does not + * compress: its downloaded form is slightly longer than its content (container header and + * footer, the IV and the cipher padding). + */ + const val BUFFER_SIZE: Int = (1024 + 64) * 1024 + } + + private val maxIdle: Int = maxIdle.coerceAtLeast(0) + + private val idle = ArrayDeque() + + /** Number of arrays currently kept for reuse. */ + val idleCount: Int get() = synchronized(idle) { idle.size } + + /** + * Returns an array of at least [minSize] bytes. Its contents are whatever its last user left in it. + * A request above [BUFFER_SIZE] gets an array of its own, which is not kept when given back. + */ + fun rent(minSize: Int): ByteArray { + if (minSize > BUFFER_SIZE) { + return ByteArray(minSize) + } + + return synchronized(idle) { idle.removeLastOrNull() } ?: ByteArray(BUFFER_SIZE) + } + + /** Hands [array] back for reuse. The caller must not touch it afterwards. */ + fun giveBack(array: ByteArray) { + if (array.size != BUFFER_SIZE) { + return + } + + synchronized(idle) { + if (idle.size < maxIdle) { + idle.addLast(array) + } + } + } + + /** Drops every idle array. */ + fun clear() { + synchronized(idle) { idle.clear() } + } +} diff --git a/javasteam-depotdownloader/src/main/kotlin/in/dragonbra/javasteam/depotdownloader/DepotDownloader.kt b/javasteam-depotdownloader/src/main/kotlin/in/dragonbra/javasteam/depotdownloader/DepotDownloader.kt index 5cb7f2409..589b8f87b 100644 --- a/javasteam-depotdownloader/src/main/kotlin/in/dragonbra/javasteam/depotdownloader/DepotDownloader.kt +++ b/javasteam-depotdownloader/src/main/kotlin/in/dragonbra/javasteam/depotdownloader/DepotDownloader.kt @@ -18,19 +18,16 @@ import `in`.dragonbra.javasteam.util.SteamKitWebRequestException import `in`.dragonbra.javasteam.util.Strings import `in`.dragonbra.javasteam.util.log.LogManager import `in`.dragonbra.javasteam.util.log.Logger -import io.ktor.client.request.get -import io.ktor.client.statement.bodyAsChannel -import io.ktor.http.HttpHeaders -import io.ktor.utils.io.readAvailable import kotlinx.coroutines.* import kotlinx.coroutines.CancellationException import kotlinx.coroutines.channels.* import kotlinx.coroutines.flow.* +import kotlinx.coroutines.selects.select import kotlinx.coroutines.sync.* +import okhttp3.OkHttpClient import okio.FileSystem import okio.Path import okio.Path.Companion.toPath -import okio.buffer import org.apache.commons.lang3.SystemUtils import java.io.Closeable import java.io.IOException @@ -62,8 +59,14 @@ import java.util.concurrent.atomic.* * @param licenses User's license list from [LicenseListCallback]. Required to determine which depots the account has access to. * @param debug Enables detailed logging of all operations via [LogManager] * @param useLanCache Attempts to detect and use local Steam cache servers (e.g., LANCache) for faster downloads on local networks - * @param maxDownloads Number of concurrent chunk downloads. Automatically increased to 25 when a LAN cache is detected. Default: 8. Higher is better + * @param maxDownloads Number of concurrent chunk downloads. Automatically increased to 25 when a LAN cache is detected. Default: 8. + * Higher is faster on a good connection, lower is easier on memory, the network and the CDN servers. All of them may go to + * one server, which is what a LAN cache needs. * @param maxFileWrites Number of concurrent files being written. Default: 1 + * @param maxDecompress Number of chunks decrypted and decompressed at the same time, each on a thread of its own. + * Default: half of the available processors, which leaves the rest to the OS and the app. Kept between 1 and the + * number of available processors. Higher is faster where the CPU, not the network, limits the download. + * This is the last constructor parameter, after [parentJob]. * @param androidEmulation Forces "Windows" as the default OS filter. Used when running Android games in PC emulators that expect Windows builds. * @param parentJob Parent job for the downloader. If provided, the downloader will be cancelled when the parent job is cancelled. * @@ -82,6 +85,7 @@ class DepotDownloader @JvmOverloads constructor( private var maxFileWrites: Int = 1, private val androidEmulation: Boolean = false, private val parentJob: Job? = null, + maxDecompress: Int = (Runtime.getRuntime().availableProcessors() / 2).coerceAtLeast(1), ) : Closeable { companion object { @@ -95,7 +99,15 @@ class DepotDownloader @JvmOverloads constructor( val STAGING_DIR: Path = CONFIG_DIR.toPath() / "staging" + private const val MAX_DOWNLOAD_ATTEMPTS: Int = 10 + + private fun retryDelayMillis(failures: Int): Long = (500L * failures).coerceAtMost(5_000L) + + private fun fraction(done: Long, total: Long): Float = if (total <= 0L) 1f else done.toFloat() / total + private val SupportedWorkshopFileTypes: Set = setOf( + // First and Community share the value 0, and EWorkshopFileType.from(0) returns First. + EWorkshopFileType.First, EWorkshopFileType.Community, EWorkshopFileType.Art, EWorkshopFileType.Screenshot, @@ -109,34 +121,57 @@ class DepotDownloader @JvmOverloads constructor( private val filesystem: FileSystem by lazy { FileSystem.SYSTEM } - private val httpClient: HttpClient by lazy { HttpClient(maxConnections = maxDownloads) } - private val listeners = CopyOnWriteArrayList() private val progressUpdateInterval = 500L // ms - private val scope: CoroutineScope = CoroutineScope(Dispatchers.IO + SupervisorJob(parentJob)) + // Errors are always logged. Everything else goes through [logger], which is only set with [debug]. + private val log: Logger = LogManager.getLogger(DepotDownloader::class.java) + + private val logger: Logger? = if (debug) log else null + + // Last line of defence: a failure inside the downloader must never take the host process down. + private val scope: CoroutineScope = CoroutineScope( + Dispatchers.IO + + SupervisorJob(parentJob) + + CoroutineExceptionHandler { _, e -> log.error("Uncaught error in DepotDownloader: ${e.message}", e) } + ) private var cdnClientPool: CDNClientPool? = null - private var config: Config = Config(androidEmulation = androidEmulation) + // Derived from the SteamClient's HTTP client on first use, see [HttpClient]. Built late on + // purpose: a detected LAN cache raises maxDownloads before the first item is processed. + private var ownHttpClient: OkHttpClient? = null - private var logger: Logger? = null + private val httpClientLock = Any() + + private fun httpClient(): OkHttpClient = synchronized(httpClientLock) { + ownHttpClient ?: HttpClient.create( + base = steamClient.configuration.httpClient, + maxDownloads = maxDownloads, + ).also { ownHttpClient = it } + } + + private var config: Config = Config(androidEmulation = androidEmulation) private var processingChannel = Channel(Channel.UNLIMITED) // Bounded channel — send() suspends producers when full, creating backpressure through the pipeline. private val networkChunkChannel = Channel(64) - // Half of available processors, clamped to at least 1. Leaves remaining cores for the OS and app. - private val maxDecompress: Int = (Runtime.getRuntime().availableProcessors() / 2).coerceAtLeast(1) - - private val pendingChunks = AtomicInteger(0) - - // Completed by processFileWrites when all pending chunks drain, or by the sentinel release in - // downloadSteam3DepotFiles. Replaces the 100ms polling loop. - @Volatile - private var downloadCompletion: CompletableDeferred? = null + // The decompress stage runs on Dispatchers.Default, which has no more threads than there are processors. + private val maxDecompress: Int = maxDecompress.coerceIn(1, Runtime.getRuntime().availableProcessors().coerceAtLeast(1)) + + // The downloaded and the decompressed bytes of every chunk live in arrays rented from here. + // Lazy because a detected LAN cache raises maxDownloads before the first chunk is downloaded. + // + // The idle cap is one array per array a stage can hold at once: one per download, two per + // decompress (input and output), one per file write. The chunks buffered between the stages + // are left out on purpose: while a download runs they are in use, not idle, and reuse works + // without slots for them. Counting them would only let ~150 MB sit idle after a burst. + private val bufferPool: ChunkBufferPool by lazy { + ChunkBufferPool(maxIdle = maxDownloads + 2 * this.maxDecompress + maxFileWrites) + } private var chunkProcessingJob: Job? = null @@ -149,7 +184,59 @@ class DepotDownloader @JvmOverloads constructor( // region [REGION] Private data classes. + /** + * Failure state of one queued item. The chunk pipeline outlives items, so every chunk carries + * the session it belongs to: once a session has failed its remaining chunks are dropped instead + * of downloaded, and whoever waits on the item is woken with the error. + */ + private class DownloadSession { + private val error = AtomicReference(null) + private val failure = CompletableDeferred() + + val isFailed: Boolean get() = error.get() != null + + fun fail(cause: Throwable) { + if (error.compareAndSet(null, cause)) { + failure.completeExceptionally(cause) + } + } + + fun throwIfFailed() { + error.get()?.let { throw it } + } + + /** Suspends until every chunk of [tracker] went through the pipeline, or throws once the session fails. */ + suspend fun awaitDrained(tracker: DepotChunkTracker) { + select { + tracker.drained.onAwait { } + failure.onAwait { } + } + throwIfFailed() + } + } + + /** Counts the chunks of one depot that are still somewhere in the pipeline. */ + private class DepotChunkTracker(val session: DownloadSession) { + // Starts at 1: a sentinel held while files are still being enumerated, so the count + // cannot reach zero before every chunk has been queued. + private val pending = AtomicInteger(1) + + val drained = CompletableDeferred() + + fun chunkQueued() { + pending.incrementAndGet() + } + + /** Must be called exactly once per queued chunk (done, failed or dropped), and once for the sentinel. */ + fun chunkDone() { + if (pending.decrementAndGet() == 0) { + drained.complete(Unit) + } + } + } + private data class NetworkChunkItem( + val tracker: DepotChunkTracker, val downloadCounter: GlobalDownloadCounter, val depotFilesData: DepotFilesData, val fileStreamData: FileStreamData, @@ -160,23 +247,28 @@ class DepotDownloader @JvmOverloads constructor( @Suppress("ArrayInDataClass") private data class DecompressItem( + val tracker: DepotChunkTracker, val depot: DepotDownloadInfo, val depotDownloadCounter: DepotDownloadCounter, val downloadCounter: GlobalDownloadCounter, val file: FileData, val fileStreamData: FileStreamData, val chunk: ChunkData, + // Rented from bufferPool: longer than the chunk. Only the first [downloaded] bytes are valid. + val downloaded: Int, val chunkBuffer: ByteArray, ) @Suppress("ArrayInDataClass") private data class FileWriteItem( + val tracker: DepotChunkTracker, val depot: DepotDownloadInfo, val depotDownloadCounter: DepotDownloadCounter, val downloadCounter: GlobalDownloadCounter, val file: FileData, val fileStreamData: FileStreamData, val chunk: ChunkData, + // Rented from bufferPool: longer than the chunk. Only the first [decompressed] bytes are valid. val decompressed: Int, val decompressedBuffer: ByteArray, ) @@ -203,10 +295,6 @@ class DepotDownloader @JvmOverloads constructor( // endregion init { - if (debug) { - logger = LogManager.getLogger(DepotDownloader::class.java) - } - steam3 = Steam3Session(steamClient, debug) logger?.debug("DepotDownloader launched with ${licenses.size} for account") @@ -225,52 +313,60 @@ class DepotDownloader @JvmOverloads constructor( private fun createChunkProcessingFlow() = networkChunkChannel.receiveAsFlow() .flatMapMerge(concurrency = maxDownloads) { item -> flow { - try { - emit( - downloadSteam3DepotFileChunk( - downloadCounter = item.downloadCounter, - depotFilesData = item.depotFilesData, - file = item.fileData, - fileStreamData = item.fileStreamData, - chunk = item.chunk - ) + val downloaded = runChunkStage(item.tracker, "downloading") { + downloadSteam3DepotFileChunk( + tracker = item.tracker, + downloadCounter = item.downloadCounter, + depotFilesData = item.depotFilesData, + file = item.fileData, + fileStreamData = item.fileStreamData, + chunk = item.chunk ) - } catch (e: CancellationException) { - throw e - } catch (e: Exception) { - logger?.error("Error downloading chunk: ${e.message}", e) } + if (downloaded != null) emit(downloaded) }.flowOn(Dispatchers.IO) } .flatMapMerge(concurrency = maxDecompress) { item -> flow { - try { - emit(processFileDecompress(item)) - } catch (e: CancellationException) { - throw e - } catch (e: Exception) { - logger?.error("Error decompressing chunk: ${e.message}", e) - } + val decompressed = runChunkStage(item.tracker, "decompressing") { processFileDecompress(item) } + if (decompressed != null) emit(decompressed) }.flowOn(Dispatchers.Default) } .flatMapMerge(concurrency = maxFileWrites) { item -> flow { - var rethrow: CancellationException? = null - try { - processFileWrites(item) - } catch (e: CancellationException) { - rethrow = e - } catch (e: Exception) { - logger?.error("Error writing file: ${e.message}", e) - } - if (pendingChunks.decrementAndGet() == 0) { - downloadCompletion?.complete(Unit) - } - rethrow?.let { throw it } + val written = runChunkStage(item.tracker, "writing") { processFileWrites(item) } + if (written != null) item.tracker.chunkDone() emit(Unit) }.flowOn(Dispatchers.IO) } + /** + * Runs one pipeline stage for a chunk. Returns null when the chunk left the pipeline here: either + * its item had already failed (the chunk is dropped), or [block] threw, which fails the item. + * Catches [Throwable] on purpose: a missing optional dependency surfaces as [NoClassDefFoundError] + * and must fail one download, not the pipeline or the process. + */ + private suspend inline fun runChunkStage(tracker: DepotChunkTracker, stage: String, block: () -> T): T? { + if (tracker.session.isFailed) { + tracker.chunkDone() + return null + } + + try { + return block() + } catch (e: Throwable) { + // Only a cancellation of the downloader itself may stop the pipeline. + if (e is CancellationException) currentCoroutineContext().ensureActive() + + log.error("Error $stage chunk: ${e.message}", e) + + val cause = if (e is CancellationException) DepotDownloaderException("Timed out $stage chunk", e) else e + tracker.session.fail(cause) + tracker.chunkDone() + return null + } + } + // region [REGION] Downloading Operations private suspend fun processPublishedFile( @@ -278,13 +374,21 @@ class DepotDownloader @JvmOverloads constructor( publishedFileId: Long, fileUrls: MutableList>, contentFileIds: MutableList, + skipReasons: MutableList, ) { val details = steam3!!.getPublishedFileDetails(appId, PublishedFileID(publishedFileId)) - val fileType = EWorkshopFileType.from(details!!.fileType) + if (details == null) { + val reason = "Unable to get the details of published file $publishedFileId" + log.error(reason) + skipReasons.add(reason) + return + } + + val fileType = EWorkshopFileType.from(details.fileType) if (fileType == EWorkshopFileType.Collection) { details.childrenList.forEach { child -> - processPublishedFile(appId, child.publishedfileid, fileUrls, contentFileIds) + processPublishedFile(appId, child.publishedfileid, fileUrls, contentFileIds, skipReasons) } } else if (SupportedWorkshopFileTypes.contains(fileType)) { if (details.fileUrl.isNotEmpty()) { @@ -292,10 +396,14 @@ class DepotDownloader @JvmOverloads constructor( } else if (details.hcontentFile > 0) { contentFileIds.add(details.hcontentFile) } else { - logger?.error("Unable to locate manifest ID for published file $publishedFileId") + val reason = "Unable to locate manifest ID for published file $publishedFileId" + log.error(reason) + skipReasons.add(reason) } } else { - logger?.error("Published file $publishedFileId has unsupported file type $fileType. Skipping file") + val reason = "Published file $publishedFileId has unsupported file type $fileType" + log.error("$reason. Skipping file") + skipReasons.add(reason) } } @@ -303,14 +411,25 @@ class DepotDownloader @JvmOverloads constructor( private suspend fun downloadPubFile(appId: Int, publishedFileId: Long) { val fileUrls = mutableListOf>() val contentFileIds = mutableListOf() + val skipReasons = mutableListOf() + + processPublishedFile(appId, publishedFileId, fileUrls, contentFileIds, skipReasons) - processPublishedFile(appId, publishedFileId, fileUrls, contentFileIds) + // Without this an item with nothing to download would end without any callback. + if (fileUrls.isEmpty() && contentFileIds.isEmpty()) { + throw DepotDownloaderException( + "Nothing to download for published file $publishedFileId: ${skipReasons.joinToString("; ")}" + ) + } fileUrls.forEach { item -> downloadWebFile(appId, item.first, item.second) } - if (contentFileIds.isNotEmpty()) { + if (contentFileIds.isEmpty()) { + // Only web files: downloadApp, which reports the completion otherwise, is not reached. + finishDepotDownload(appId) + } else { val depotManifestIds = contentFileIds.map { id -> appId to id } downloadApp( appId = appId, @@ -338,11 +457,13 @@ class DepotDownloader @JvmOverloads constructor( val ugcHandle = UGCHandle(ugcId) details = steam3!!.getUGCDetails(ugcHandle) } else { - logger?.error("Unable to query UGC details for $ugcId from an anonymous account") + log.error("Unable to query UGC details for $ugcId from an anonymous account") } if (!details?.url.isNullOrBlank()) { downloadWebFile(appId = appId, fileName = details.fileName, url = details.url) + // downloadApp, which reports the completion otherwise, is not reached. + finishDepotDownload(appId) } else { downloadApp( appId = appId, @@ -361,9 +482,9 @@ class DepotDownloader @JvmOverloads constructor( private suspend fun downloadWebFile(appId: Int, fileName: String, url: String) { val (success, installDir) = createDirectories(appId, 0, appId) + // Failures are thrown so the item ends in onDownloadFailed instead of ending silently. if (!success) { - logger?.error("Error: Unable to create install directories!") - return + throw DepotDownloaderException("Unable to create install directories for $fileName") } val stagingDir = installDir!! / "staging" @@ -373,29 +494,17 @@ class DepotDownloader @JvmOverloads constructor( filesystem.createDirectories(fileFinalPath.parent!!) filesystem.createDirectories(fileStagingPath.parent!!) - httpClient.getClient().use { client -> - logger?.debug("Starting download of $fileName...") - - val response = client.get(url) - val channel = response.bodyAsChannel() - - val totalBytes = response.headers[HttpHeaders.ContentLength]?.toLongOrNull() - - logger?.debug("File size: ${totalBytes?.let { Util.formatBytes(it) } ?: "Unknown"}") + logger?.debug("Starting download of $fileName...") - filesystem.sink(fileStagingPath).buffer().use { sink -> - val tempArray = ByteArray(DEFAULT_BUFFER_SIZE) - - while (!channel.isClosedForRead) { - val bytesRead = channel.readAvailable(tempArray, 0, tempArray.size) - if (bytesRead > 0) { - sink.write(tempArray, 0, bytesRead) - } - } - } + // The same HTTP client chunks and manifests use. + val bytesWritten = HttpClient.downloadFile( + httpClient = httpClient(), + url = url, + destination = fileStagingPath, + filesystem = filesystem, + ) - logger?.debug("Download completed.") - } + logger?.debug("Download completed, ${Util.formatBytes(bytesWritten)}.") if (filesystem.exists(fileFinalPath)) { logger?.debug("Deleting $fileFinalPath") @@ -406,7 +515,7 @@ class DepotDownloader @JvmOverloads constructor( filesystem.atomicMove(fileStagingPath, fileFinalPath) logger?.debug("File '$fileStagingPath' moved to final location: $fileFinalPath") } catch (e: IOException) { - logger?.error("Failed to move files", e) + log.error("Failed to move files", e) throw e } } @@ -426,7 +535,7 @@ class DepotDownloader @JvmOverloads constructor( var depotManifestIds = depotManifestIds.toMutableList() val steamUser = requireNotNull(steam3!!.steamUser) - cdnClientPool = CDNClientPool(steam3!!, appId, scope, debug) + cdnClientPool = CDNClientPool(steam3!!, appId, scope, debug, httpClient()) // Load our configuration data containing the depots currently installed var configPath = config.installPath @@ -538,14 +647,22 @@ class DepotDownloader @JvmOverloads constructor( } val infos = mutableListOf() + val skipReasons = mutableListOf() depotManifestIds.forEach { (depotId, manifestId) -> - val info = getDepotInfo(depotId, appId, manifestId, branch) + val info = getDepotInfo(depotId, appId, manifestId, branch, skipReasons) if (info != null) { infos.add(info) } } + // Without this an item whose depots were all skipped would be reported as completed. + if (infos.isEmpty()) { + throw DepotDownloaderException( + "None of the depots of app $appId could be downloaded: ${skipReasons.joinToString("; ")}" + ) + } + downloadSteam3(appId, infos) } @@ -555,48 +672,49 @@ class DepotDownloader @JvmOverloads constructor( appId: Int, manifestId: Long, branch: String, + skipReasons: MutableList, ): DepotDownloadInfo? { var manifestId = manifestId var branch = branch + fun skip(reason: String): DepotDownloadInfo? { + skipReasons.add(reason) + skipDepot(depotId, reason) + return null + } + if (appId != INVALID_APP_ID) { steam3!!.requestAppInfo(appId) } if (!accountHasAccess(appId, depotId)) { - logger?.error("Depot $depotId is not available from this account.") - return null + return skip("Depot $depotId is not available from this account.") } if (manifestId == INVALID_MANIFEST_ID) { manifestId = getSteam3DepotManifest(depotId, appId, branch) if (manifestId == INVALID_MANIFEST_ID && !branch.equals(DEFAULT_BRANCH, true)) { - logger?.error("Warning: Depot $depotId does not have branch named \"$branch\". Trying $DEFAULT_BRANCH branch.") + log.error("Warning: Depot $depotId does not have branch named \"$branch\". Trying $DEFAULT_BRANCH branch.") branch = DEFAULT_BRANCH manifestId = getSteam3DepotManifest(depotId, appId, branch) } if (manifestId == INVALID_MANIFEST_ID) { - logger?.error("Depot $depotId missing public subsection or manifest section.") - return null + return skip("Depot $depotId missing public subsection or manifest section.") } } steam3!!.requestDepotKey(depotId, appId) val depotKey = steam3!!.depotKeys[depotId] - if (depotKey == null) { - logger?.error("No valid depot key for $depotId, unable to download.") - return null - } + ?: return skip("No valid depot key for $depotId, unable to download.") val uVersion = getSteam3AppBuildNumber(appId, branch) val (success, installDir) = createDirectories(depotId, uVersion, appId) if (!success) { - logger?.error("Error: Unable to create install directories!") - return null + return skip("Unable to create install directories for depot $depotId.") } // For depots that are proxied through depotfromapp, we still need to resolve the proxy app id, unless the app is freetodownload @@ -619,6 +737,12 @@ class DepotDownloader @JvmOverloads constructor( ) } + /** A depot is left out of the download. Always logged, and reported to listeners. */ + private fun skipDepot(depotId: Int, reason: String) { + log.error(reason) + notifyListeners { it.onDepotSkipped(depotId, reason) } + } + private suspend fun getSteam3DepotManifest( depotId: Int, appId: Int, @@ -638,7 +762,7 @@ class DepotDownloader @JvmOverloads constructor( val otherAppId = depotChild["depotfromapp"].asInteger() if (otherAppId == appId) { // This shouldn't ever happen, but ya never know with Valve. Don't infinite loop. - logger?.error("App $appId, Depot $depotId has depotfromapp of $otherAppId!") + log.error("App $appId, Depot $depotId has depotfromapp of $otherAppId!") return INVALID_MANIFEST_ID } @@ -667,7 +791,7 @@ class DepotDownloader @JvmOverloads constructor( // Either the branch just doesn't exist, or it has a password if (config.betaPassword.isNullOrBlank()) { - logger?.error("Branch $branch for depot $depotId was not found, either it does not exist or it has a password.") + log.error("Branch $branch for depot $depotId was not found, either it does not exist or it has a password.") return INVALID_MANIFEST_ID } @@ -676,7 +800,7 @@ class DepotDownloader @JvmOverloads constructor( steam3!!.checkAppBetaPassword(appId, config.betaPassword!!) if (!steam3!!.appBetaPasswords.containsKey(branch)) { - logger?.error("Error: Password was invalid for branch $branch (or the branch does not exist)") + log.error("Error: Password was invalid for branch $branch (or the branch does not exist)") return INVALID_MANIFEST_ID } } @@ -800,7 +924,7 @@ class DepotDownloader @JvmOverloads constructor( filesystem.createDirectories(installDir / STAGING_DIR) } } catch (e: IOException) { - logger?.error("Failed to create directory for depot $depotId, app $appId", e) + log.error("Failed to create directory for depot $depotId, app $appId", e) return DirectoryResult(false, null) } @@ -886,6 +1010,12 @@ class DepotDownloader @JvmOverloads constructor( allFileNamesAllDepots.addAll(depotFileData.allFileNames) } + // Depots can still be skipped while fetching manifests. Without this an item whose depots + // were all skipped there would be reported as completed. + if (depotsToDownload.isEmpty() && depots.isNotEmpty() && !config.downloadManifestOnly) { + throw DepotDownloaderException("None of the depots of app $mainAppId could be downloaded.") + } + // If we're about to write all the files to the same directory, we will need to first de-duplicate any files by path // This is in last-depot-wins order, from Steam or the list of depots supplied by the user if (config.installPath != null && depotsToDownload.isNotEmpty()) { @@ -897,28 +1027,23 @@ class DepotDownloader @JvmOverloads constructor( } } - if (depotsToDownload.isEmpty()) { - finishDepotDownload(mainAppId) - } else { - // Sentinel: keeps pendingChunks ≥ 1 while files are still being enumerated, - // preventing a premature zero signal before all chunks have been submitted. - pendingChunks.set(1) - downloadCompletion = CompletableDeferred() - depotsToDownload.forEachIndexed { index, depotFileData -> - downloadSteam3DepotFiles( - mainAppId, - downloadCounter, - depotFileData, - allFileNamesAllDepots, - index == depotsToDownload.size - 1 - ) + val session = DownloadSession() + try { + depotsToDownload.forEach { depotFileData -> + downloadSteam3DepotFiles(session, downloadCounter, depotFileData, allFileNamesAllDepots) } + } catch (e: Throwable) { + // Drops the chunks of this item that are still in the pipeline. + session.fail(e) + throw e } logger?.debug( "Total downloaded: ${downloadCounter.totalBytesCompressed.get()} bytes " + "(${downloadCounter.totalBytesUncompressed.get()} bytes uncompressed) from ${depots.size} depots" ) + + finishDepotDownload(mainAppId) } private suspend fun processDepotManifestAndFiles( @@ -965,9 +1090,15 @@ class DepotDownloader @JvmOverloads constructor( var manifestRequestCode: ULong = 0U var manifestRequestCodeExpiration = Instant.MIN + var failures = 0 + var lastError: Throwable? = null + do { ensureActive() + if (failures >= MAX_DOWNLOAD_ATTEMPTS) break + if (failures > 0) delay(retryDelayMillis(failures)) + var connection: Server? = null try { @@ -981,7 +1112,8 @@ class DepotDownloader @JvmOverloads constructor( val result = authTokenCallbackPromise.await() cdnToken = result.token } catch (e: Exception) { - logger?.error("Failed to get CDN auth token: ${e.message}") + ensureActive() + log.error("Failed to get CDN auth token: ${e.message}") } } @@ -1002,10 +1134,8 @@ class DepotDownloader @JvmOverloads constructor( // If we could not get the manifest code, this is a fatal error if (manifestRequestCode == 0UL) { - // TODO this should be a fatal error and bail out. But I guess we can continue. - logger?.error("Manifest request code is 0. Skipping depot ${depot.depotId}") + skipDepot(depot.depotId, "No manifest request code for depot ${depot.depotId}, manifest ${depot.manifestId}.") return@withContext null - // cancel("manifestRequestCode is 0UL") } } @@ -1022,10 +1152,6 @@ class DepotDownloader @JvmOverloads constructor( ) cdnClientPool!!.returnConnection(connection) - } catch (e: CancellationException) { - // logger?.error("Connection timeout downloading depot manifest ${depot.depotId} ${depot.manifestId}. Retrying.") - logger?.error("Cancellation Exception thrown in process manifest", e) - break } catch (e: SteamKitWebRequestException) { // If the CDN returned 403, attempt to get a cdn auth if we didn't yet if (e.statusCode == 403 && !steam3!!.cdnAuthTokens.containsKey(depot.depotId to connection!!.host)) { @@ -1038,39 +1164,48 @@ class DepotDownloader @JvmOverloads constructor( cdnClientPool!!.skipConnection(connection) + failures++ + lastError = e + // Unauthorized || Forbidden if (e.statusCode == 401 || e.statusCode == 403) { - logger?.error("Encountered ${depot.depotId} for depot manifest ${depot.manifestId} ${e.statusCode}. Aborting.") + log.error("Encountered ${depot.depotId} for depot manifest ${depot.manifestId} ${e.statusCode}. Aborting.") break } // NotFound if (e.statusCode == 404) { - logger?.error("Encountered 404 for depot manifest ${depot.depotId} ${depot.manifestId}. Aborting.") + log.error("Encountered 404 for depot manifest ${depot.depotId} ${depot.manifestId}. Aborting.") break } - logger?.error("Encountered error downloading depot manifest ${depot.depotId} ${depot.manifestId}: ${e.statusCode}") + log.error("Encountered error downloading depot manifest ${depot.depotId} ${depot.manifestId}: ${e.statusCode}") } catch (e: Exception) { + // A real cancellation stops here; a timeout reported as one is retried like any error. + if (e is CancellationException) ensureActive() + if (e is java.net.UnknownHostException || e.cause is java.net.UnknownHostException) { cdnClientPool!!.returnBrokenConnection(connection) } else { cdnClientPool!!.skipConnection(connection) } - logger?.error("Encountered error downloading manifest for depot ${depot.depotId} ${depot.manifestId}: ${e.message}") + + failures++ + lastError = e + + log.error("Encountered error downloading manifest for depot ${depot.depotId} ${depot.manifestId}: ${e.message}") if (!cdnClientPool!!.hasServers()) break } } while (newManifest == null) if (newManifest == null) { - logger?.error("\nUnable to download manifest ${depot.manifestId} for depot ${depot.depotId}") - cancel() + throw DepotDownloaderException( + "Unable to download manifest ${depot.manifestId} for depot ${depot.depotId}", + lastError + ) } - // Throw the cancellation exception if requested so that this task is marked failed - ensureActive() - - Util.saveManifestToFile(configDir, newManifest!!) + Util.saveManifestToFile(configDir, newManifest) } } @@ -1122,13 +1257,11 @@ class DepotDownloader @JvmOverloads constructor( ) } - @OptIn(DelicateCoroutinesApi::class) private suspend fun downloadSteam3DepotFiles( - mainAppId: Int, + session: DownloadSession, downloadCounter: GlobalDownloadCounter, depotFilesData: DepotFilesData, allFileNamesAllDepots: HashSet, - isLastDepot: Boolean, ) = withContext(Dispatchers.IO) { val depot = depotFilesData.depotDownloadInfo val depotCounter = depotFilesData.depotCounter @@ -1137,34 +1270,29 @@ class DepotDownloader @JvmOverloads constructor( val files = depotFilesData.filteredFiles.filter { !it.flags.contains(EDepotFileFlag.Directory) } - try { - coroutineScope { - files.map { file -> - async { - downloadSteam3DepotFile( - downloadCounter = downloadCounter, - depotFilesData = depotFilesData, - file = file, - ) - } - }.awaitAll() - } - } finally { - if (isLastDepot) { - logger?.debug("Waiting for ${pendingChunks.get()} pending chunks to complete for depot ${depot.depotId}") + val tracker = DepotChunkTracker(session) - // Release the sentinel. If no chunks are still in flight, signal immediately; - // otherwise suspend until the last processFileWrites call signals us. - if (pendingChunks.decrementAndGet() == 0) { - downloadCompletion?.complete(Unit) + coroutineScope { + files.map { file -> + async { + downloadSteam3DepotFile( + tracker = tracker, + downloadCounter = downloadCounter, + depotFilesData = depotFilesData, + file = file, + ) } - downloadCompletion?.await() - downloadCompletion = null - - logger?.debug("All chunks completed for depot ${depot.depotId}") - } + }.awaitAll() } + // Every chunk is queued: release the sentinel and wait until the last one is on disk. + // The depot must not be recorded as installed (below) before that, or an interrupted + // download would be trusted on the next run without its missing chunks being noticed. + tracker.chunkDone() + session.awaitDrained(tracker) + + logger?.debug("All chunks completed for depot ${depot.depotId}") + // Check for deleted files if updating the depot. if (depotFilesData.previousManifest != null) { val previousFilteredFiles = depotFilesData.previousManifest.files @@ -1206,18 +1334,16 @@ class DepotDownloader @JvmOverloads constructor( } logger?.debug("Depot ${depot.depotId} - Downloaded ${depotCounter.depotBytesCompressed} bytes (${depotCounter.depotBytesUncompressed} bytes uncompressed)") - - if (isLastDepot) { - finishDepotDownload(mainAppId) - } } private suspend fun downloadSteam3DepotFile( + tracker: DepotChunkTracker, downloadCounter: GlobalDownloadCounter, depotFilesData: DepotFilesData, file: FileData, ) = withContext(Dispatchers.IO) { ensureActive() + tracker.session.throwIfFailed() val depot = depotFilesData.depotDownloadInfo val stagingDir = depotFilesData.stagingDir @@ -1396,9 +1522,13 @@ class DepotDownloader @JvmOverloads constructor( ) neededChunks!!.forEach { chunk -> - pendingChunks.incrementAndGet() + // Stop feeding the pipeline once the download has failed. + tracker.session.throwIfFailed() + + tracker.chunkQueued() networkChunkChannel.send( NetworkChunkItem( + tracker = tracker, downloadCounter = downloadCounter, depotFilesData = depotFilesData, fileStreamData = fileStreamData, @@ -1411,6 +1541,7 @@ class DepotDownloader @JvmOverloads constructor( } private suspend fun downloadSteam3DepotFileChunk( + tracker: DepotChunkTracker, downloadCounter: GlobalDownloadCounter, depotFilesData: DepotFilesData, file: FileData, @@ -1426,11 +1557,22 @@ class DepotDownloader @JvmOverloads constructor( val chunkID = Strings.toHex(chunkIdBytes) var downloaded = 0 - val chunkBuffer = ByteArray(chunk.compressedLength) + // Given back by processFileDecompress. If this chunk fails or is dropped before that, + // the array is simply left to the garbage collector. + val chunkBuffer = bufferPool.rent(chunk.compressedLength) + + var failures = 0 + var lastError: Throwable? = null do { ensureActive() + // Another chunk already failed this download; no point in fetching this one. + tracker.session.throwIfFailed() + + if (failures >= MAX_DOWNLOAD_ATTEMPTS) break + if (failures > 0) delay(retryDelayMillis(failures)) + var connection: Server? = null try { @@ -1445,7 +1587,8 @@ class DepotDownloader @JvmOverloads constructor( val result = authTokenCallbackPromise.await() cdnToken = result.token } catch (e: Exception) { - logger?.error("Failed to get CDN auth token: ${e.message}") + ensureActive() + log.error("Failed to get CDN auth token: ${e.message}") } } @@ -1464,8 +1607,6 @@ class DepotDownloader @JvmOverloads constructor( cdnClientPool!!.returnConnection(connection) break - } catch (e: CancellationException) { - throw e } catch (e: SteamKitWebRequestException) { // If the CDN returned 403, attempt to get a cdn auth if we didn't yet, // if auth task already exists, make sure it didn't complete yet, so that it gets awaited above @@ -1484,40 +1625,53 @@ class DepotDownloader @JvmOverloads constructor( cdnClientPool!!.skipConnection(connection) + failures++ + lastError = e + // Unauthorized || Forbidden if (e.statusCode == 401 || e.statusCode == 403) { - logger?.error("Encountered ${e.statusCode} for chunk $chunkID. Aborting.") + log.error("Encountered ${e.statusCode} for chunk $chunkID. Aborting.") break } - logger?.error("Encountered error downloading chunk $chunkID: ${e.statusCode}") + log.error("Encountered error downloading chunk $chunkID from $connection: ${e.statusCode} (${e.message})") } catch (e: Exception) { + // A real cancellation stops here; a timeout reported as one is retried like any error. + if (e is CancellationException) ensureActive() + if (e is java.net.UnknownHostException || e.cause is java.net.UnknownHostException) { cdnClientPool!!.returnBrokenConnection(connection) } else { cdnClientPool!!.skipConnection(connection) } - logger?.error("Encountered unexpected error downloading chunk $chunkID", e) + + failures++ + lastError = e + + log.error("Encountered unexpected error downloading chunk $chunkID", e) if (!cdnClientPool!!.hasServers()) break } } while (downloaded == 0) + // Giving up on one chunk fails the whole item: the pipeline reports it through the session, + // which wakes downloadSteam3DepotFiles and ends in onDownloadFailed. if (downloaded == 0) { - logger?.error("Failed to find any server with chunk ${chunk.chunkID} for depot ${depot.depotId}. Aborting.") - cancel() + throw DepotDownloaderException( + "Failed to download chunk $chunkID for depot ${depot.depotId} after $failures failed attempts", + lastError + ) } - // Throw the cancellation exception if requested so that this task is marked failed - ensureActive() - // Return the decompress item for the next stage in the pipeline return@withContext DecompressItem( + tracker = tracker, depot = depot, depotDownloadCounter = depotDownloadCounter, downloadCounter = downloadCounter, file = file, fileStreamData = fileStreamData, chunk = chunk, + downloaded = downloaded, chunkBuffer = chunkBuffer, ) } @@ -1573,14 +1727,13 @@ class DepotDownloader @JvmOverloads constructor( * Add a singular item of either [AppItem], [PubFileItem], or [UgcItem] */ fun add(item: DownloadItem) { - runBlocking { - try { - processingChannel.send(item) - notifyListeners { it.onItemAdded(item) } - } catch (e: Exception) { - logger?.error("Could not add item ${item.appId}", e) - throw e - } + try { + // The queue is unlimited, so this only fails once it has been closed. + processingChannel.trySend(item).getOrThrow() + notifyListeners { it.onItemAdded(item) } + } catch (e: Exception) { + log.error("Could not add item ${item.appId}", e) + throw e } } @@ -1588,17 +1741,7 @@ class DepotDownloader @JvmOverloads constructor( * Add a list items of either [AppItem], [PubFileItem], or [UgcItem] */ fun addAll(items: List) { - runBlocking { - try { - items.forEach { item -> - processingChannel.send(item) - notifyListeners { it.onItemAdded(item) } - } - } catch (e: Exception) { - logger?.error("Could not add all files", e) - throw e - } - } + items.forEach { add(it) } } /** @@ -1663,33 +1806,30 @@ class DepotDownloader @JvmOverloads constructor( val branch = item.branch ?: DEFAULT_BRANCH config = config.copy(betaPassword = item.branchPassword) + // Invalid arguments are thrown so they reach onDownloadFailed below. if (!config.betaPassword.isNullOrBlank() && branch.isBlank()) { - logger?.error("Error: Cannot specify 'branchpassword' when 'branch' is not specified.") - continue + throw IllegalArgumentException("Cannot specify 'branchPassword' when 'branch' is not specified.") } config = config.copy(downloadAllPlatforms = item.downloadAllPlatforms) val os = item.os if (config.downloadAllPlatforms && !os.isNullOrBlank()) { - logger?.error("Error: Cannot specify `os` when `all-platforms` is specified.") - continue + throw IllegalArgumentException("Cannot specify 'os' when 'downloadAllPlatforms' is set.") } config = config.copy(downloadAllArchs = item.downloadAllArchs) val arch = item.osArch if (config.downloadAllArchs && !arch.isNullOrBlank()) { - logger?.error("Error: Cannot specify `osarch` when `all-archs` is specified.") - continue + throw IllegalArgumentException("Cannot specify 'osArch' when 'downloadAllArchs' is set.") } config = config.copy(downloadAllLanguages = item.downloadAllLanguages) val language = item.language if (config.downloadAllLanguages && !language.isNullOrBlank()) { - logger?.error("Error: Cannot specify `language` when `all-languages` is specified.") - continue + throw IllegalArgumentException("Cannot specify 'language' when 'downloadAllLanguages' is set.") } val depotManifestIds = mutableListOf>() @@ -1698,8 +1838,7 @@ class DepotDownloader @JvmOverloads constructor( if (manifestIdList.isNotEmpty()) { if (depotIdList.size != manifestIdList.size) { - logger?.error("Error: `manifest` requires one id for every `depot` specified") - continue + throw IllegalArgumentException("'manifest' requires one id for every 'depot' specified.") } depotManifestIds.addAll(depotIdList.zip(manifestIdList)) } else { @@ -1720,8 +1859,9 @@ class DepotDownloader @JvmOverloads constructor( ) } } - } catch (e: Exception) { - logger?.error("Error downloading item ${item.appId}: ${e.message}", e) + } catch (e: Throwable) { + // Throwable, not Exception: e.g. a missing zstd/xz dependency is a NoClassDefFoundError. + log.error("Error downloading item ${item.appId}: ${e.message}", e) notifyListeners { it.onDownloadFailed(item, e) } } } @@ -1738,10 +1878,18 @@ class DepotDownloader @JvmOverloads constructor( val chunk = item.chunk val chunkBuffer = item.chunkBuffer - val decompressedBuffer = ByteArray(chunk.uncompressedLength) - val written = DepotChunk.process(chunk, chunkBuffer, decompressedBuffer, depot.depotKey) + // Given back by processFileWrites; left to the garbage collector if the chunk fails before that. + val decompressedBuffer = bufferPool.rent(chunk.uncompressedLength) + + val written = try { + DepotChunk.process(chunk, chunkBuffer, item.downloaded, decompressedBuffer, depot.depotKey) + } finally { + // Nothing reads the downloaded bytes after this point. + bufferPool.giveBack(chunkBuffer) + } return@withContext FileWriteItem( + tracker = item.tracker, depot = depot, depotDownloadCounter = item.depotDownloadCounter, downloadCounter = item.downloadCounter, @@ -1767,35 +1915,58 @@ class DepotDownloader @JvmOverloads constructor( val decompressedBuffer = item.decompressedBuffer try { - fileStreamData.fileLock.lock() + try { + fileStreamData.fileLock.lock() - if (fileStreamData.fileHandle == null) { - val fileFinalPath = depot.installDir / file.fileName - fileStreamData.fileHandle = filesystem.openReadWrite(fileFinalPath) - } + if (fileStreamData.fileHandle == null) { + val fileFinalPath = depot.installDir / file.fileName + fileStreamData.fileHandle = filesystem.openReadWrite(fileFinalPath) + } - fileStreamData.fileHandle!!.write(chunk.offset, decompressedBuffer, 0, written) + fileStreamData.fileHandle!!.write(chunk.offset, decompressedBuffer, 0, written) + } finally { + fileStreamData.fileLock.unlock() + } } finally { - fileStreamData.fileLock.unlock() + // The write was the last reader of the array; everything below uses lengths only. + bufferPool.giveBack(decompressedBuffer) } val remainingChunks = fileStreamData.chunksToDownload.decrementAndGet() if (remainingChunks == 0) { fileStreamData.fileHandle?.close() + } - // File completed - notify with percentage - val sizeDownloaded = synchronized(depotDownloadCounter) { - depotDownloadCounter.sizeDownloaded += written.toLong() - depotDownloadCounter.depotBytesCompressed += chunk.compressedLength - depotDownloadCounter.depotBytesUncompressed += chunk.uncompressedLength - depotDownloadCounter.sizeDownloaded - } + // Update counters and notify on chunk completion. Every chunk is reported, the last one of a + // file included, so the byte counts also move for depots made of single-chunk files. + val depotPercentage: Float + val compressedBytes: Long + val uncompressedBytes: Long - downloadCounter.totalBytesCompressed.addAndGet(chunk.compressedLength.toLong()) - downloadCounter.totalBytesUncompressed.addAndGet(chunk.uncompressedLength.toLong()) + synchronized(depotDownloadCounter) { + depotDownloadCounter.sizeDownloaded += written.toLong() + depotDownloadCounter.depotBytesCompressed += chunk.compressedLength + depotDownloadCounter.depotBytesUncompressed += chunk.uncompressedLength + + compressedBytes = depotDownloadCounter.depotBytesCompressed + uncompressedBytes = depotDownloadCounter.depotBytesUncompressed + depotPercentage = fraction(depotDownloadCounter.sizeDownloaded, depotDownloadCounter.completeDownloadSize) + } + downloadCounter.totalBytesCompressed.addAndGet(chunk.compressedLength.toLong()) + downloadCounter.totalBytesUncompressed.addAndGet(chunk.uncompressedLength.toLong()) + + notifyListeners { listener -> + listener.onChunkCompleted( + depotId = depot.depotId, + depotPercentComplete = depotPercentage, + compressedBytes = compressedBytes, + uncompressedBytes = uncompressedBytes + ) + } + + if (remainingChunks == 0) { val fileFinalPath = depot.installDir / file.fileName - val depotPercentage = (sizeDownloaded.toFloat() / depotDownloadCounter.completeDownloadSize) notifyListeners { listener -> listener.onFileCompleted( @@ -1806,35 +1977,6 @@ class DepotDownloader @JvmOverloads constructor( } logger?.debug("%.2f%% %s".format(depotPercentage, fileFinalPath)) - } else { - // Update counters and notify on chunk completion - val sizeDownloaded: Long - val depotPercentage: Float - val compressedBytes: Long - val uncompressedBytes: Long - - synchronized(depotDownloadCounter) { - depotDownloadCounter.sizeDownloaded += written.toLong() - depotDownloadCounter.depotBytesCompressed += chunk.compressedLength - depotDownloadCounter.depotBytesUncompressed += chunk.uncompressedLength - - sizeDownloaded = depotDownloadCounter.sizeDownloaded - compressedBytes = depotDownloadCounter.depotBytesCompressed - uncompressedBytes = depotDownloadCounter.depotBytesUncompressed - depotPercentage = (sizeDownloaded.toFloat() / depotDownloadCounter.completeDownloadSize) - } - - downloadCounter.totalBytesCompressed.addAndGet(chunk.compressedLength.toLong()) - downloadCounter.totalBytesUncompressed.addAndGet(chunk.uncompressedLength.toLong()) - - notifyListeners { listener -> - listener.onChunkCompleted( - depotId = depot.depotId, - depotPercentComplete = depotPercentage, - compressedBytes = compressedBytes, - uncompressedBytes = uncompressedBytes - ) - } } } @@ -1859,8 +2001,6 @@ class DepotDownloader @JvmOverloads constructor( scope.cancel("DepotDownloader Closing") - httpClient.close() - listeners.clear() steam3?.close() @@ -1869,6 +2009,12 @@ class DepotDownloader @JvmOverloads constructor( cdnClientPool?.close() cdnClientPool = null - logger = null + bufferPool.clear() + + // Ours, derived from the SteamClient's HTTP client, which is left untouched. + synchronized(httpClientLock) { + ownHttpClient?.let { HttpClient.shutdown(it) } + ownHttpClient = null + } } } diff --git a/javasteam-depotdownloader/src/main/kotlin/in/dragonbra/javasteam/depotdownloader/DepotDownloaderException.kt b/javasteam-depotdownloader/src/main/kotlin/in/dragonbra/javasteam/depotdownloader/DepotDownloaderException.kt index 4c3b4bbc3..9ce6f8489 100644 --- a/javasteam-depotdownloader/src/main/kotlin/in/dragonbra/javasteam/depotdownloader/DepotDownloaderException.kt +++ b/javasteam-depotdownloader/src/main/kotlin/in/dragonbra/javasteam/depotdownloader/DepotDownloaderException.kt @@ -8,4 +8,7 @@ package `in`.dragonbra.javasteam.depotdownloader * @author Lossy * @since Oct 1, 2025 */ -class DepotDownloaderException(value: String) : Exception(value) +class DepotDownloaderException @JvmOverloads constructor( + value: String, + cause: Throwable? = null, +) : Exception(value, cause) diff --git a/javasteam-depotdownloader/src/main/kotlin/in/dragonbra/javasteam/depotdownloader/HttpClient.kt b/javasteam-depotdownloader/src/main/kotlin/in/dragonbra/javasteam/depotdownloader/HttpClient.kt index 67f35d486..2aa49e452 100644 --- a/javasteam-depotdownloader/src/main/kotlin/in/dragonbra/javasteam/depotdownloader/HttpClient.kt +++ b/javasteam-depotdownloader/src/main/kotlin/in/dragonbra/javasteam/depotdownloader/HttpClient.kt @@ -1,66 +1,97 @@ package `in`.dragonbra.javasteam.depotdownloader import `in`.dragonbra.javasteam.util.Versions -import io.ktor.client.HttpClient -import io.ktor.client.engine.cio.CIO -import io.ktor.client.engine.cio.endpoint -import io.ktor.client.plugins.UserAgent -import kotlinx.coroutines.isActive -import java.io.Closeable +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import okhttp3.ConnectionPool +import okhttp3.Dispatcher +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.coroutines.executeAsync +import okio.FileSystem +import okio.Path +import okio.buffer +import java.util.concurrent.SynchronousQueue +import java.util.concurrent.ThreadPoolExecutor +import java.util.concurrent.TimeUnit /** - * HTTP client wrapper for content downloader operations. + * The HTTP side of a [DepotDownloader]: builds the client it downloads with, and downloads plain web files. * - * Provides a configured Ktor HTTP client optimized for Steam CDN downloads. - * Each instance maintains its own connection pool based on the specified - * maximum concurrent connections. - * - * @param maxConnections Maximum number of concurrent connections - * - * @author Lossy - * @since Oct 1, 2025 + * OkHttp runs at most 5 requests per host and 64 in total on a client, whatever the caller asks + * for, and keeps 5 idle connections. The downloader therefore derives its own client from the one + * in the SteamClient configuration: same timeouts, interceptors and proxy, but with request limits + * and a connection pool sized from the downloader's settings. The original client is not changed. */ -class HttpClient( - private val maxConnections: Int, -) : Closeable { - - private var httpClient: HttpClient? = null +internal object HttpClient { /** - * Returns the HTTP client instance, creating it lazily on first access. - * - * The client is configured with: - * - Custom User-Agent identifying JavaSteam DepotDownloader - * - Connection pooling based on [maxConnections] - * - 5 second keep-alive and connect timeout - * - 30 second request timeout + * @param base The client to derive from. + * @param maxDownloads Concurrent requests, in total and to a single host. */ - fun getClient(): HttpClient { - if (httpClient?.isActive != true) { - httpClient = HttpClient(CIO) { - install(UserAgent) { - agent = "JavaSteam-DepotDownloader/${Versions.getVersion()}" - } - engine { - maxConnectionsCount = maxConnections - endpoint { - maxConnectionsPerRoute = (maxConnections / 2).coerceAtLeast(1) - pipelineMaxSize = maxConnections * 2 - keepAliveTime = 5000 - connectTimeout = 5000 - requestTimeout = 30000 - } - } - } + fun create(base: OkHttpClient, maxDownloads: Int): OkHttpClient { + val total = maxDownloads.coerceAtLeast(1) + + // Same executor OkHttp creates by default, but with daemon threads, so a downloader that + // was not closed does not keep the JVM alive for the 60 second keep-alive. + val executor = ThreadPoolExecutor(0, Int.MAX_VALUE, 60, TimeUnit.SECONDS, SynchronousQueue()) { runnable -> + Thread(runnable, "JavaSteam DepotDownloader HTTP").apply { isDaemon = true } + } + + val dispatcher = Dispatcher(executor).apply { + maxRequests = total + maxRequestsPerHost = total } - return httpClient!! + // Keep one connection per concurrent download alive between chunks. + val pool = ConnectionPool(total, 5, TimeUnit.MINUTES) + + return base.newBuilder() + .dispatcher(dispatcher) + .connectionPool(pool) + .build() } - override fun close() { - if (httpClient?.isActive == true) { - httpClient?.close() - httpClient = null + /** + * Releases a client made by [create]. Never call this with the client it was derived from. + */ + fun shutdown(client: OkHttpClient) { + client.dispatcher.executorService.shutdown() + client.connectionPool.evictAll() + } + + /** + * Downloads a plain web file, which is how some workshop and UGC items are served instead of + * depot chunks, to [destination], replacing the file if it exists. + * + * @param httpClient The client to use. Its timeouts apply. + * @param filesystem The file system [destination] is on. + * @return The number of bytes written. + * @throws DepotDownloaderException The server did not answer with a success status. Nothing is written. + * @throws java.io.IOException A network or file error occurred. + */ + suspend fun downloadFile( + httpClient: OkHttpClient, + url: String, + destination: Path, + filesystem: FileSystem = FileSystem.SYSTEM, + ): Long { + val request = Request.Builder() + .url(url) + .header("User-Agent", "JavaSteam-DepotDownloader/${Versions.getVersion()}") + .build() + + return httpClient.newCall(request).executeAsync().use { response -> + // Otherwise the body of an error page would be saved as the file. + if (!response.isSuccessful) { + throw DepotDownloaderException("Failed to download $url: HTTP ${response.code}") + } + + withContext(Dispatchers.IO) { + filesystem.sink(destination).buffer().use { sink -> + sink.writeAll(response.body.source()) + } + } } } } diff --git a/javasteam-depotdownloader/src/main/kotlin/in/dragonbra/javasteam/depotdownloader/IDownloadListener.kt b/javasteam-depotdownloader/src/main/kotlin/in/dragonbra/javasteam/depotdownloader/IDownloadListener.kt index f005c6cb8..5bccfa100 100644 --- a/javasteam-depotdownloader/src/main/kotlin/in/dragonbra/javasteam/depotdownloader/IDownloadListener.kt +++ b/javasteam-depotdownloader/src/main/kotlin/in/dragonbra/javasteam/depotdownloader/IDownloadListener.kt @@ -32,6 +32,16 @@ interface IDownloadListener { */ fun onDownloadFailed(item: DownloadItem, error: Throwable) {} + /** + * Called when a depot that was part of a download is left out, for example because the account + * has no access to it, no depot key could be obtained, or it has no manifest for the branch. + * The rest of the download continues; if every depot is skipped, [onDownloadFailed] is called. + * + * @param depotId The depot that will not be downloaded + * @param reason An explanation + */ + fun onDepotSkipped(depotId: Int, reason: String) {} + /** * Called during file preparation with informational messages. * Examples: "Pre-allocating depots\441\file.txt", "Validating file.cab" @@ -39,7 +49,7 @@ interface IDownloadListener { fun onStatusUpdate(message: String) {} /** - * Called when a file completes downloading. + * Called when a file completes downloading, after the [onChunkCompleted] of its last chunk. * Use this for printing progress like "20.42% depots\441\maps\ctf_haarp.bsp" * * @param depotId The depot being downloaded @@ -49,8 +59,8 @@ interface IDownloadListener { fun onFileCompleted(depotId: Int, fileName: String, depotPercentComplete: Float) {} /** - * Called when a chunk completes downloading. - * Provides more frequent progress updates than onFileCompleted. + * Called when a chunk completes downloading, for every chunk including the last one of a file. + * Provides more frequent progress updates than onFileCompleted, and is the one to count bytes in. * * @param depotId The depot being downloaded * @param depotPercentComplete Overall depot completion percentage (0f to 1f) diff --git a/javasteam-depotdownloader/src/main/kotlin/in/dragonbra/javasteam/depotdownloader/Steam3Session.kt b/javasteam-depotdownloader/src/main/kotlin/in/dragonbra/javasteam/depotdownloader/Steam3Session.kt index f92dfa32d..598a87406 100644 --- a/javasteam-depotdownloader/src/main/kotlin/in/dragonbra/javasteam/depotdownloader/Steam3Session.kt +++ b/javasteam-depotdownloader/src/main/kotlin/in/dragonbra/javasteam/depotdownloader/Steam3Session.kt @@ -21,6 +21,8 @@ import `in`.dragonbra.javasteam.util.log.LogManager import `in`.dragonbra.javasteam.util.log.Logger import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext @@ -44,7 +46,10 @@ class Steam3Session( debug: Boolean, ) : Closeable { - private var logger: Logger? = null + // Errors are always logged. Everything else goes through [logger], which is only set with debug. + private val log: Logger = LogManager.getLogger(Steam3Session::class.java) + + private val logger: Logger? = if (debug) log else null private var isAborted: Boolean = false // Stubbed, no way to set true/false yet. @@ -67,10 +72,6 @@ class Steam3Session( internal data class Optional(val value: T?) init { - if (debug) { - logger = LogManager.getLogger(Steam3Session::class.java) - } - unifiedMessages = requireNotNull(steamClient.getHandler()) steamApps = requireNotNull(steamClient.getHandler()) steamCloud = requireNotNull(steamClient.getHandler()) @@ -101,8 +102,6 @@ class Steam3Session( packageTokens.clear() appInfo.clear() packageInfo.clear() - - logger = null } suspend fun requestAppInfo(appId: Int, bForce: Boolean = false) { @@ -114,7 +113,7 @@ class Steam3Session( val appTokens = steamApps!!.picsGetAccessTokens(appId).await() if (appTokens.appTokensDenied.contains(appId)) { - logger?.error("Insufficient privileges to get access token for app $appId") + log.error("Insufficient privileges to get access token for app $appId") } appTokens.appTokens.forEach { tokenDict -> @@ -198,7 +197,8 @@ class Steam3Session( return resultInfo.grantedApps.contains(appId) } catch (e: Exception) { - logger?.error("Failed to request FreeOnDemand license for app $appId: ${e.message}") + currentCoroutineContext().ensureActive() + log.error("Failed to request FreeOnDemand license for app $appId: ${e.message}") return false } } @@ -217,7 +217,7 @@ class Steam3Session( ) if (depotKey.result != EResult.OK) { - logger?.error("requestDepotKey result was ${depotKey.result}") + log.error("requestDepotKey result was ${depotKey.result}") return } @@ -245,7 +245,7 @@ class Steam3Session( ).await().toULong() if (requestCode == 0UL) { - logger?.error("No manifest request code was returned for depot $depotId from app $appId, manifest $manifestId") + log.error("No manifest request code was returned for depot $depotId from app $appId, manifest $manifestId") if (steamClient.isDisconnected) { logger?.debug("Suggestion: Try logging in with a username as old manifests may not be available for anonymous accounts.") @@ -284,7 +284,7 @@ class Steam3Session( logger?.debug("Got CDN auth token for ${server.host} result: ${cdnAuth.result} (expires ${cdnAuth.expiration})") if (cdnAuth.result != EResult.OK) { - logger?.error("requestCDNAuthToken result was ${cdnAuth.result}") + log.error("requestCDNAuthToken result was ${cdnAuth.result}") return@withContext } @@ -349,7 +349,7 @@ class Steam3Session( if (callback.result == EResult.OK) { return callback } else if (callback.result == EResult.FileNotFound) { - logger?.error("getUGCDetails got FileNotFound for ${ugcHandle.value}") + log.error("getUGCDetails got FileNotFound for ${ugcHandle.value}") return null } diff --git a/javasteam-depotdownloader/src/main/kotlin/in/dragonbra/javasteam/depotdownloader/Util.kt b/javasteam-depotdownloader/src/main/kotlin/in/dragonbra/javasteam/depotdownloader/Util.kt index a46951a0a..d5cc3a29d 100644 --- a/javasteam-depotdownloader/src/main/kotlin/in/dragonbra/javasteam/depotdownloader/Util.kt +++ b/javasteam-depotdownloader/src/main/kotlin/in/dragonbra/javasteam/depotdownloader/Util.kt @@ -28,6 +28,10 @@ object Util { @JvmOverloads @JvmStatic fun getSteamOS(androidEmulation: Boolean = false): String { + // Hack for PC emulation on android. Most of them use Windows. + if (androidEmulation && SystemUtils.IS_OS_ANDROID) { + return "windows" + } if (SystemUtils.IS_OS_WINDOWS) { return "windows" } @@ -42,11 +46,6 @@ object Util { return "linux" } - // Hack for PC emulation on android. (Pluvia, GameNative, GameHub) - if (androidEmulation && SystemUtils.IS_OS_ANDROID) { - return "windows" - } - return "unknown" } diff --git a/javasteam-depotdownloader/src/test/java/in/dragonbra/javasteam/depotdownloader/ChunkBufferPoolTest.java b/javasteam-depotdownloader/src/test/java/in/dragonbra/javasteam/depotdownloader/ChunkBufferPoolTest.java new file mode 100644 index 000000000..bd90db7d2 --- /dev/null +++ b/javasteam-depotdownloader/src/test/java/in/dragonbra/javasteam/depotdownloader/ChunkBufferPoolTest.java @@ -0,0 +1,67 @@ +package in.dragonbra.javasteam.depotdownloader; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class ChunkBufferPoolTest { + + @Test + public void rentsABufferOfTheStandardSize() { + var pool = new ChunkBufferPool(4); + + Assertions.assertEquals(ChunkBufferPool.BUFFER_SIZE, pool.rent(1).length); + Assertions.assertEquals(ChunkBufferPool.BUFFER_SIZE, pool.rent(1024 * 1024).length); + Assertions.assertEquals(ChunkBufferPool.BUFFER_SIZE, pool.rent(ChunkBufferPool.BUFFER_SIZE).length); + } + + @Test + public void reusesABufferThatWasGivenBack() { + var pool = new ChunkBufferPool(4); + + var first = pool.rent(100); + pool.giveBack(first); + + Assertions.assertEquals(1, pool.getIdleCount()); + Assertions.assertSame(first, pool.rent(200_000)); + Assertions.assertEquals(0, pool.getIdleCount()); + + // The pool is empty again, so this one is new. + Assertions.assertNotSame(first, pool.rent(100)); + } + + @Test + public void aRequestAboveTheStandardSizeGetsItsOwnBufferWhichIsNotKept() { + var pool = new ChunkBufferPool(4); + + var large = pool.rent(ChunkBufferPool.BUFFER_SIZE + 1); + Assertions.assertEquals(ChunkBufferPool.BUFFER_SIZE + 1, large.length); + + pool.giveBack(large); + Assertions.assertEquals(0, pool.getIdleCount()); + } + + @Test + public void keepsNoMoreIdleBuffersThanTheCap() { + var pool = new ChunkBufferPool(2); + + var a = pool.rent(1); + var b = pool.rent(1); + var c = pool.rent(1); + + pool.giveBack(a); + pool.giveBack(b); + pool.giveBack(c); + + Assertions.assertEquals(2, pool.getIdleCount()); + } + + @Test + public void clearDropsTheIdleBuffers() { + var pool = new ChunkBufferPool(2); + + pool.giveBack(pool.rent(1)); + pool.clear(); + + Assertions.assertEquals(0, pool.getIdleCount()); + } +} diff --git a/javasteam-depotdownloader/src/test/java/in/dragonbra/javasteam/depotdownloader/HttpClientTest.java b/javasteam-depotdownloader/src/test/java/in/dragonbra/javasteam/depotdownloader/HttpClientTest.java new file mode 100644 index 000000000..9b7440b7a --- /dev/null +++ b/javasteam-depotdownloader/src/test/java/in/dragonbra/javasteam/depotdownloader/HttpClientTest.java @@ -0,0 +1,132 @@ +package in.dragonbra.javasteam.depotdownloader; + +import mockwebserver3.MockResponse; +import mockwebserver3.MockWebServer; +import mockwebserver3.RecordedRequest; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import org.jetbrains.annotations.NotNull; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +public class HttpClientTest { + + @Test + public void appliesTheLimit() { + // One number for both: all downloads may go to a single host, such as a LAN cache. + var client = HttpClient.INSTANCE.create(new OkHttpClient(), 50); + try { + Assertions.assertEquals(50, client.dispatcher().getMaxRequests()); + Assertions.assertEquals(50, client.dispatcher().getMaxRequestsPerHost()); + } finally { + HttpClient.INSTANCE.shutdown(client); + } + } + + @Test + public void treatsANonPositiveLimitAsOne() { + for (int maxDownloads : new int[]{0, -3}) { + var client = HttpClient.INSTANCE.create(new OkHttpClient(), maxDownloads); + try { + Assertions.assertEquals(1, client.dispatcher().getMaxRequests()); + Assertions.assertEquals(1, client.dispatcher().getMaxRequestsPerHost()); + } finally { + HttpClient.INSTANCE.shutdown(client); + } + } + } + + @Test + public void keepsTheSettingsOfTheBaseClientAndLeavesItAlone() { + var base = new OkHttpClient.Builder() + .readTimeout(42, TimeUnit.SECONDS) + .addInterceptor(chain -> chain.proceed(chain.request())) + .build(); + + var client = HttpClient.INSTANCE.create(base, 16); + HttpClient.INSTANCE.shutdown(client); + + Assertions.assertEquals(42_000, client.readTimeoutMillis()); + Assertions.assertEquals(1, client.interceptors().size()); + + // Its own dispatcher and connection pool, so shutting it down does not touch the base client. + Assertions.assertNotSame(base.dispatcher(), client.dispatcher()); + Assertions.assertNotSame(base.connectionPool(), client.connectionPool()); + Assertions.assertTrue(client.dispatcher().executorService().isShutdown()); + Assertions.assertFalse(base.dispatcher().executorService().isShutdown()); + Assertions.assertEquals(64, base.dispatcher().getMaxRequests()); + Assertions.assertEquals(5, base.dispatcher().getMaxRequestsPerHost()); + } + + @Test + public void runsMoreThanFiveRequestsAgainstOneHost() throws Exception { + // OkHttp's default is 5 per host, which would cap this at 5. + Assertions.assertEquals(12, peakConcurrency(12, 24)); + } + + @Test + public void aLowSettingLimitsTheRequests() throws Exception { + Assertions.assertEquals(2, peakConcurrency(2, 24)); + } + + /** + * Fires [requests] requests at one server and returns how many it had in flight at the same time at most. + */ + private static int peakConcurrency(int maxDownloads, int requests) throws Exception { + var inFlight = new AtomicInteger(); + var peak = new AtomicInteger(); + + try (var server = new MockWebServer()) { + server.setDispatcher(new mockwebserver3.Dispatcher() { + @NotNull + @Override + public MockResponse dispatch(@NotNull RecordedRequest request) throws InterruptedException { + var now = inFlight.incrementAndGet(); + peak.accumulateAndGet(now, Math::max); + Thread.sleep(150); + inFlight.decrementAndGet(); + return new MockResponse.Builder().code(200).body("chunk").build(); + } + }); + server.start(); + + var client = HttpClient.INSTANCE.create(new OkHttpClient(), maxDownloads); + try { + var done = new CountDownLatch(requests); + var failures = new AtomicInteger(); + + for (int i = 0; i < requests; i++) { + var request = new Request.Builder().url(server.url("/depot/1/chunk/" + i)).build(); + client.newCall(request).enqueue(new Callback() { + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + failures.incrementAndGet(); + done.countDown(); + } + + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) { + response.close(); + done.countDown(); + } + }); + } + + Assertions.assertTrue(done.await(30, TimeUnit.SECONDS), "requests did not finish"); + Assertions.assertEquals(0, failures.get()); + } finally { + HttpClient.INSTANCE.shutdown(client); + } + } + + return peak.get(); + } +} diff --git a/javasteam-depotdownloader/src/test/kotlin/in/dragonbra/javasteam/depotdownloader/HttpClientDownloadFileTest.kt b/javasteam-depotdownloader/src/test/kotlin/in/dragonbra/javasteam/depotdownloader/HttpClientDownloadFileTest.kt new file mode 100644 index 000000000..3b77895f1 --- /dev/null +++ b/javasteam-depotdownloader/src/test/kotlin/in/dragonbra/javasteam/depotdownloader/HttpClientDownloadFileTest.kt @@ -0,0 +1,103 @@ +package `in`.dragonbra.javasteam.depotdownloader + +import kotlinx.coroutines.runBlocking +import mockwebserver3.MockResponse +import mockwebserver3.MockWebServer +import okhttp3.OkHttpClient +import okio.Buffer +import okio.FileSystem +import okio.Path +import okio.Path.Companion.toOkioPath +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.Assertions.assertArrayEquals +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import java.io.IOException +import java.util.Random + +// Kotlin, not Java: HttpClient.downloadFile is a suspend function. +class HttpClientDownloadFileTest { + + private lateinit var server: MockWebServer + + private lateinit var destination: Path + + private val filesystem = FileSystem.SYSTEM + + @BeforeEach + fun setUp(@TempDir tempDir: java.nio.file.Path) { + server = MockWebServer() + server.start() + + destination = tempDir.toOkioPath() / "workshop_file.bin" + } + + @AfterEach + fun tearDown() { + server.close() + } + + @Test + fun downloadsTheFile() { + // Larger than one okio segment and one socket read. + val content = ByteArray(3 * 1024 * 1024 + 17).also { Random(7).nextBytes(it) } + server.enqueue(MockResponse.Builder().code(200).body(Buffer().write(content)).build()) + + val written = download() + + assertEquals(content.size.toLong(), written) + assertArrayEquals(content, filesystem.read(destination) { readByteArray() }) + + val request = server.takeRequest() + assertEquals("GET", request.method) + assertEquals("/ugc/123/file.bin", request.url.encodedPath) + assertTrue(request.headers["User-Agent"]!!.startsWith("JavaSteam-DepotDownloader/")) + } + + @Test + fun replacesAnExistingFile() { + filesystem.write(destination) { writeUtf8("a much longer leftover from an earlier attempt") } + server.enqueue(MockResponse.Builder().code(200).body("new").build()) + + assertEquals(3L, download()) + assertEquals("new", filesystem.read(destination) { readUtf8() }) + } + + @Test + fun downloadsAnEmptyFile() { + server.enqueue(MockResponse.Builder().code(200).build()) + + assertEquals(0L, download()) + assertEquals(0L, filesystem.metadata(destination).size) + } + + @Test + fun failsOnAnErrorStatusWithoutWritingTheErrorPage() { + server.enqueue(MockResponse.Builder().code(404).body("Not Found").build()) + + val exception = assertThrows(DepotDownloaderException::class.java) { download() } + + assertTrue(exception.message!!.contains("404")) + assertFalse(filesystem.exists(destination)) + } + + @Test + fun failsWhenTheServerIsUnreachable() { + val url = server.url("/ugc/123/file.bin").toString() + server.close() + + assertThrows(IOException::class.java) { + runBlocking { HttpClient.downloadFile(OkHttpClient(), url, destination, filesystem) } + } + assertFalse(filesystem.exists(destination)) + } + + private fun download(): Long = runBlocking { + HttpClient.downloadFile(OkHttpClient(), server.url("/ugc/123/file.bin").toString(), destination, filesystem) + } +} diff --git a/javasteam-protobufs-webui/src/main/proto/in/dragonbra/javasteam/protobufs/webui/common.proto b/javasteam-protobufs-webui/src/main/proto/in/dragonbra/javasteam/protobufs/webui/common.proto index 94b01a3aa..e797d1aed 100644 --- a/javasteam-protobufs-webui/src/main/proto/in/dragonbra/javasteam/protobufs/webui/common.proto +++ b/javasteam-protobufs-webui/src/main/proto/in/dragonbra/javasteam/protobufs/webui/common.proto @@ -42,6 +42,14 @@ message AppUpdateInfo { optional uint32 target_build_id = 16; } +message AssetPropertyFilter { + optional uint32 property_id = 1; + optional float float_min = 2; + optional float float_max = 3; + optional int64 int_min = 4; + optional int64 int_max = 5; +} + // Used by: common.proto message CAppOverview { optional uint32 appid = 1; @@ -2718,6 +2726,7 @@ message CMsgClientSettings { optional int32 system_idle_screensaver_battery_sec = 24008; optional int32 system_idle_screensaver_ac_sec = 24009; optional bool vr_show_perf_graph_in_hmd = 25000; + optional string vr_launch_programs_hidden = 25003; optional bool accessibility_debug_visualizer = 26000; optional bool accessibility_screen_reader_enabled = 26001; optional float accessibility_screen_reader_rate = 26002; @@ -5295,10 +5304,6 @@ message CPhaseAttribute { optional uint32 priority = 3; } -message CProductInfo_ForceEmitPriceConversion { - optional int32 method = 1 [(webui.description) = "enum"]; -} - message CQuitRequest { } @@ -7217,6 +7222,7 @@ message StoreBrowseFilterFailure { optional bool already_owned = 5; optional bool on_wishlist = 6; optional bool ignored = 7; + optional bool ignored_creator = 8; optional bool not_in_users_language = 10; optional bool not_on_users_platform = 11; optional bool demo_for_owned_game = 12; @@ -7269,6 +7275,7 @@ message StoreGameRating { optional bool use_age_gate = 11; repeated int32 descriptor_images = 12 [(webui.description) = "enum"]; optional string content_survey_notes = 13; + optional int32 agency_rating = 14 [(webui.description) = "enum"]; optional string image_url = 20; optional string image_target = 21; } @@ -7328,22 +7335,6 @@ message StoreItem { repeated StoreItem_PurchaseNote purchase_notes = 78; } -// Used by: Checkout, MarketingMessages, PartnerStoreBrowse, SteamCharts, Store, StoreAppSimilarity, StoreBrowse, StoreMarketing, StoreQuery, StoreTopSellers, UserStoreVisit, Wishlist -message StoreItem_AIGeneratedContentService { - optional string name = 1; - optional string url = 2; -} - -// Used by: Checkout, MarketingMessages, PartnerStoreBrowse, SteamCharts, Store, StoreAppSimilarity, StoreBrowse, StoreMarketing, StoreQuery, StoreTopSellers, UserStoreVisit, Wishlist -message StoreItem_Anticheat { - optional bool kernel_mode = 1; - optional bool uninstall_completely = 2; - optional bool boot_protection = 3; - optional string boot_protection_name = 4; - optional string name = 5; - optional string name_loc = 6; -} - // Used by: Checkout, MarketingMessages, PartnerStoreBrowse, SteamCharts, Store, StoreAppSimilarity, StoreBrowse, StoreMarketing, StoreQuery, StoreTopSellers, UserStoreVisit, Wishlist message StoreItem_Assets { optional string asset_url_format = 1; @@ -7399,12 +7390,6 @@ message StoreItem_Demo { optional bool show_above_purchase = 3; } -// Used by: Checkout, MarketingMessages, PartnerStoreBrowse, SteamCharts, Store, StoreAppSimilarity, StoreBrowse, StoreMarketing, StoreQuery, StoreTopSellers, UserStoreVisit, Wishlist -message StoreItem_Eula { - optional string name = 1; - optional string url = 2; -} - // Used by: Checkout, MarketingMessages, PartnerStoreBrowse, SteamCharts, Store, StoreAppSimilarity, StoreBrowse, StoreMarketing, StoreQuery, StoreTopSellers, UserStoreVisit, Wishlist message StoreItem_ExtraDetails { repeated SteamAward steam_award = 1; @@ -7416,20 +7401,15 @@ message StoreItem_ExtraDetails { optional string user_account_third_party = 7; optional bool user_account_third_party_link_to_steam = 8; optional StoreItem_ExtraDetails_Anticheat anticheat = 9; - //optional StoreItem_Anticheat anticheat = 9; repeated StoreItem_ExtraDetails_Eula eula = 10; - //repeated StoreItem_Eula eula = 10; optional StoreItem_ExtraDetails_AIGeneratedContentService ai_generation_service = 11; - //optional StoreItem_AIGeneratedContentService ai_generation_service = 11; optional bool refund_checks_ea_playtime = 12; repeated StoreItem_ExtraDetails_PageSection section = 13; - //repeated StoreItem_PageSection section = 13; optional string legal_notice_bbcode = 14; repeated int32 interactive_elements = 15 [(webui.description) = "enum"]; optional string content_survey_notes = 16; optional string content_survey_ai_notes = 17; repeated StoreItem_ExtraDetails_PressReview press_review = 18; - //repeated StoreItem_PressReview press_review = 18; optional string partner_awards_bbcode = 19; optional StoreItem_ExtraDetails_EarlyAccess early_access = 20; optional CSeasonPass season_pass = 21; @@ -7444,6 +7424,12 @@ message StoreItem_ExtraDetails { repeated StoreItem_ExtraDetails_Season seasons = 31; optional int32 video_extras_note = 32 [(webui.description) = "enum"]; optional bool has_community_hub = 33; + optional StoreItem_ExtraDetails_EventSpotlight event_spotlight = 34; + optional StoreItem_ExtraDetails_MusicAlbum music_album = 35; + repeated StoreItem_ExtraDetails_SalePage sale_pages = 36; + optional bool item_store_show_featured = 37; + optional StoreItem_ExtraDetails_HardwareCompatibility hardware_compatibility = 38; + optional StoreItem_ExtraDetails_DLCForPurchase dlc_for_purchase = 39; } // Used by: Checkout, MarketingMessages, PartnerStoreBrowse, SteamCharts, Store, StoreAppSimilarity, StoreBrowse, StoreMarketing, StoreQuery, StoreTopSellers, UserStoreVisit, Wishlist @@ -7471,6 +7457,30 @@ message StoreItem_ExtraDetails_CastAndCrew { repeated string actors = 5; } +// Used by: Checkout, MarketingMessages, PartnerStoreBrowse, SteamCharts, Store, StoreAppSimilarity, StoreBrowse, StoreMarketing, StoreQuery, StoreTopSellers, UserStoreVisit, Wishlist +message StoreItem_ExtraDetails_DLCForPurchase { + repeated StoreItem_ExtraDetails_DLCForPurchase_DLC dlc = 1; + optional uint32 dlc_count = 2; + repeated StoreItem_ExtraDetails_DLCForPurchase_Dependency dependencies = 3; + optional uint32 packageid = 4; + optional string formatted_total_price = 5; +} + +// Used by: Checkout, MarketingMessages, PartnerStoreBrowse, SteamCharts, Store, StoreAppSimilarity, StoreBrowse, StoreMarketing, StoreQuery, StoreTopSellers, UserStoreVisit, Wishlist +message StoreItem_ExtraDetails_DLCForPurchase_Dependency { + optional uint32 appid = 1; + optional uint32 packageid = 2; + optional bool required = 3; +} + +// Used by: Checkout, MarketingMessages, PartnerStoreBrowse, SteamCharts, Store, StoreAppSimilarity, StoreBrowse, StoreMarketing, StoreQuery, StoreTopSellers, UserStoreVisit, Wishlist +message StoreItem_ExtraDetails_DLCForPurchase_DLC { + optional uint32 appid = 1; + optional uint32 packageid = 2; + repeated int32 content_descriptorids = 3 [(webui.description) = "enum"]; + optional int32 highlight_reason = 4 [(webui.description) = "enum"]; +} + // Used by: Checkout, MarketingMessages, PartnerStoreBrowse, SteamCharts, Store, StoreAppSimilarity, StoreBrowse, StoreMarketing, StoreQuery, StoreTopSellers, UserStoreVisit, Wishlist message StoreItem_ExtraDetails_EarlyAccess { optional string why_bbcode = 1; @@ -7495,6 +7505,34 @@ message StoreItem_ExtraDetails_Eula { optional string url = 2; } +// Used by: Checkout, MarketingMessages, PartnerStoreBrowse, SteamCharts, Store, StoreAppSimilarity, StoreBrowse, StoreMarketing, StoreQuery, StoreTopSellers, UserStoreVisit, Wishlist +message StoreItem_ExtraDetails_EventSpotlight { + optional uint32 clan_account_id = 1; + optional fixed64 event_gid = 2; + optional fixed64 announcement_gid = 3; +} + +// Used by: Checkout, MarketingMessages, PartnerStoreBrowse, SteamCharts, Store, StoreAppSimilarity, StoreBrowse, StoreMarketing, StoreQuery, StoreTopSellers, UserStoreVisit, Wishlist +message StoreItem_ExtraDetails_HardwareCompatibility { + repeated StoreItem_ExtraDetails_HardwareCompatibility_TestResult steam_deck_tests = 1; + repeated StoreItem_ExtraDetails_HardwareCompatibility_SteamOSTestResult steam_os_tests = 2; + repeated StoreItem_ExtraDetails_HardwareCompatibility_TestResult steam_machine_tests = 3; + repeated StoreItem_ExtraDetails_HardwareCompatibility_TestResult steam_frame_tests = 4; + optional string steam_deck_blog_url = 5; +} + +// Used by: Checkout, MarketingMessages, PartnerStoreBrowse, SteamCharts, Store, StoreAppSimilarity, StoreBrowse, StoreMarketing, StoreQuery, StoreTopSellers, UserStoreVisit, Wishlist +message StoreItem_ExtraDetails_HardwareCompatibility_SteamOSTestResult { + optional int32 display_type = 1 [(webui.description) = "enum"]; + optional string loc_token = 2; +} + +// Used by: Checkout, MarketingMessages, PartnerStoreBrowse, SteamCharts, Store, StoreAppSimilarity, StoreBrowse, StoreMarketing, StoreQuery, StoreTopSellers, UserStoreVisit, Wishlist +message StoreItem_ExtraDetails_HardwareCompatibility_TestResult { + optional int32 display_type = 1 [(webui.description) = "enum"]; + optional string loc_token = 2; +} + // Used by: Checkout, MarketingMessages, PartnerStoreBrowse, SteamCharts, Store, StoreAppSimilarity, StoreBrowse, StoreMarketing, StoreQuery, StoreTopSellers, UserStoreVisit, Wishlist message StoreItem_ExtraDetails_LinksAndInfo { optional string website = 1; @@ -7516,6 +7554,24 @@ message StoreItem_ExtraDetails_Metacritic { optional bool always_show = 3; } +// Used by: Checkout, MarketingMessages, PartnerStoreBrowse, SteamCharts, Store, StoreAppSimilarity, StoreBrowse, StoreMarketing, StoreQuery, StoreTopSellers, UserStoreVisit, Wishlist +message StoreItem_ExtraDetails_MusicAlbum { + repeated StoreItem_ExtraDetails_MusicAlbum_Track tracks = 1; + optional string artist = 2; + optional string composer = 3; + optional string label = 4; + optional string other_credits = 5; +} + +// Used by: Checkout, MarketingMessages, PartnerStoreBrowse, SteamCharts, Store, StoreAppSimilarity, StoreBrowse, StoreMarketing, StoreQuery, StoreTopSellers, UserStoreVisit, Wishlist +message StoreItem_ExtraDetails_MusicAlbum_Track { + optional uint32 disc_number = 1; + optional uint32 track_number = 2; + optional string name = 3; + optional string other_name = 4; + optional uint32 duration_seconds = 5; +} + // Used by: Checkout, MarketingMessages, PartnerStoreBrowse, SteamCharts, Store, StoreAppSimilarity, StoreBrowse, StoreMarketing, StoreQuery, StoreTopSellers, UserStoreVisit, Wishlist message StoreItem_ExtraDetails_PageSection { optional string label = 1; @@ -7531,6 +7587,12 @@ message StoreItem_ExtraDetails_PressReview { optional string url = 4; } +// Used by: Checkout, MarketingMessages, PartnerStoreBrowse, SteamCharts, Store, StoreAppSimilarity, StoreBrowse, StoreMarketing, StoreQuery, StoreTopSellers, UserStoreVisit, Wishlist +message StoreItem_ExtraDetails_SalePage { + optional uint32 clan_account_id = 1; + optional fixed64 event_gid = 2; +} + // Used by: Checkout, MarketingMessages, PartnerStoreBrowse, SteamCharts, Store, StoreAppSimilarity, StoreBrowse, StoreMarketing, StoreQuery, StoreTopSellers, UserStoreVisit, Wishlist message StoreItem_ExtraDetails_Season { optional int32 index = 1; @@ -7614,13 +7676,6 @@ message StoreItem_PackageGroup { optional string dropdown_description_bbcode = 5; } -// Used by: Checkout, MarketingMessages, PartnerStoreBrowse, SteamCharts, Store, StoreAppSimilarity, StoreBrowse, StoreMarketing, StoreQuery, StoreTopSellers, UserStoreVisit, Wishlist -message StoreItem_PageSection { - optional string label = 1; - optional string content_bbcode = 2; - optional int32 banner = 3 [(webui.description) = "enum"]; -} - // Used by: Checkout, MarketingMessages, PartnerStoreBrowse, SteamCharts, Store, StoreAppSimilarity, StoreBrowse, StoreMarketing, StoreQuery, StoreTopSellers, UserStoreVisit, Wishlist message StoreItem_Platforms { optional bool windows = 1; @@ -7650,14 +7705,6 @@ message StoreItem_Playtest { optional bool is_open = 2; } -// Used by: Checkout, MarketingMessages, PartnerStoreBrowse, SteamCharts, Store, StoreAppSimilarity, StoreBrowse, StoreMarketing, StoreQuery, StoreTopSellers, UserStoreVisit, Wishlist -message StoreItem_PressReview { - optional string quote = 1; - optional string score = 2; - optional string site = 3; - optional string url = 4; -} - // Used by: Checkout, MarketingMessages, PartnerStoreBrowse, SteamCharts, Store, StoreAppSimilarity, StoreBrowse, StoreMarketing, StoreQuery, StoreTopSellers, UserStoreVisit, Wishlist message StoreItem_PurchaseNote { optional int32 type = 1 [(webui.description) = "enum"]; @@ -7698,6 +7745,7 @@ message StoreItem_PurchaseOption { optional uint32 free_with_master_sub_appid = 54; optional string formatted_lowest_recent_price = 55; optional bool is_free_license = 56; + optional int32 combined_discount_pct = 57; } // Used by: Checkout, MarketingMessages, PartnerStoreBrowse, SteamCharts, Store, StoreAppSimilarity, StoreBrowse, StoreMarketing, StoreQuery, StoreTopSellers, UserStoreVisit, Wishlist @@ -7761,6 +7809,7 @@ message StoreItem_Reviews { optional StoreItem_Reviews_StoreReviewSummary summary_filtered = 1; optional StoreItem_Reviews_StoreReviewSummary summary_unfiltered = 2; optional StoreItem_Reviews_StoreReviewSummary summary_language_specific = 3; + optional bool counts_all_purchases = 4; } // Used by: Checkout, MarketingMessages, PartnerStoreBrowse, SteamCharts, Store, StoreAppSimilarity, StoreBrowse, StoreMarketing, StoreQuery, StoreTopSellers, UserStoreVisit, Wishlist @@ -7781,6 +7830,8 @@ message StoreItem_Screenshots { message StoreItem_Screenshots_Screenshot { optional string filename = 1; optional int32 ordinal = 2; + optional string alt_text = 3; + optional int32 category = 4 [(webui.description) = "enum"]; } // Used by: Checkout, MarketingMessages, PartnerStoreBrowse, SteamCharts, Store, StoreAppSimilarity, StoreBrowse, StoreMarketing, StoreQuery, StoreTopSellers, UserStoreVisit, Wishlist @@ -7824,6 +7875,8 @@ message StoreItem_Trailers_Trailer { optional int32 trailer_base_id = 12; optional int32 trailer_category = 13 [(webui.description) = "enum"]; optional bool all_ages = 14; + optional string screenshot_small = 15; + optional uint32 trailer_id = 16; } // Used by: Checkout, MarketingMessages, PartnerStoreBrowse, SteamCharts, Store, StoreAppSimilarity, StoreBrowse, StoreMarketing, StoreQuery, StoreTopSellers, UserStoreVisit, Wishlist diff --git a/javasteam-protobufs-webui/src/main/proto/in/dragonbra/javasteam/protobufs/webui/service_friendslist.proto b/javasteam-protobufs-webui/src/main/proto/in/dragonbra/javasteam/protobufs/webui/service_friendslist.proto new file mode 100644 index 000000000..2ab2ee2c1 --- /dev/null +++ b/javasteam-protobufs-webui/src/main/proto/in/dragonbra/javasteam/protobufs/webui/service_friendslist.proto @@ -0,0 +1,80 @@ +import "in/dragonbra/javasteam/protobufs/webui/common_base.proto"; + +package webui; + +option java_package = "in.dragonbra.javasteam.protobufs.webui"; + +option optimize_for = SPEED; +option java_generic_services = false; + +message CFriendsList_FavoritesChanged_Notification { + repeated CFriendsListFavoriteEntry favorites = 1; +} + +message CFriendsList_GetCategories_Request { +} + +message CFriendsList_GetCategories_Response { + repeated CFriendsListCategory categories = 1; +} + +message CFriendsList_GetFavorites_Request { +} + +message CFriendsList_GetFavorites_Response { + repeated CFriendsListFavoriteEntry favorites = 1; +} + +message CFriendsList_GetFriendsList_Request { +} + +message CFriendsList_GetFriendsList_Response { + optional CMsgClientFriendsList friendslist = 1; +} + +message CFriendsList_SetFavorites_Request { + repeated CFriendsListFavoriteEntry favorites = 1; +} + +message CFriendsList_SetFavorites_Response { +} + +message CFriendsListCategory { + optional uint32 groupid = 1; + optional string name = 2; + repeated uint32 accountid_members = 3; +} + +message CFriendsListFavoriteEntry { + optional uint32 accountid = 1; + optional uint32 clanid = 2; + optional uint64 chat_group_id = 3; +} + +message CMsgClientFriendsList { + optional bool bincremental = 1; + repeated CMsgClientFriendsList_Friend friends = 2; + optional uint32 max_friend_count = 3; + optional uint32 active_friend_count = 4; + optional bool friends_limit_hit = 5; +} + +message CMsgClientFriendsList_Friend { + optional fixed64 ulfriendid = 1; + optional uint32 efriendrelationship = 2; +} + +service FriendsList { + // bConstMethod=true, ePrivilege=1 + rpc GetCategories (CFriendsList_GetCategories_Request) returns (CFriendsList_GetCategories_Response); + // bConstMethod=true, ePrivilege=1 + rpc GetFavorites (CFriendsList_GetFavorites_Request) returns (CFriendsList_GetFavorites_Response); + // bConstMethod=true, ePrivilege=1 + rpc GetFriendsList (CFriendsList_GetFriendsList_Request) returns (CFriendsList_GetFriendsList_Response); + // ePrivilege=1 + rpc SetFavorites (CFriendsList_SetFavorites_Request) returns (CFriendsList_SetFavorites_Response); +} + +service FriendsListClient { + rpc FavoritesChanged (CFriendsList_FavoritesChanged_Notification) returns (NoResponse); +} diff --git a/javasteam-protobufs-webui/src/main/proto/in/dragonbra/javasteam/protobufs/webui/service_remote.proto b/javasteam-protobufs-webui/src/main/proto/in/dragonbra/javasteam/protobufs/webui/service_remote.proto new file mode 100644 index 000000000..53965c6b7 --- /dev/null +++ b/javasteam-protobufs-webui/src/main/proto/in/dragonbra/javasteam/protobufs/webui/service_remote.proto @@ -0,0 +1,139 @@ +import "in/dragonbra/javasteam/protobufs/webui/common.proto"; +import "in/dragonbra/javasteam/protobufs/webui/common_base.proto"; + +package webui; + +option java_package = "in.dragonbra.javasteam.protobufs.webui"; + +option optimize_for = SPEED; +option java_generic_services = false; + +message CRemoteClient_AllocateRelayServer_Request { + optional uint32 cellid = 1; + optional string credentials = 2; +} + +message CRemoteClient_AllocateRelayServer_Response { + optional string relay_server = 1; +} + +message CRemoteClient_AllocateSDR_Request { + optional uint32 appid = 1; +} + +message CRemoteClient_AllocateSDR_Response { +} + +message CRemoteClient_ClientDetails { + optional fixed64 remote_client_id = 1; + optional CRemoteClient_DeviceDetails device_details = 2; + optional uint64 last_seen = 4; + optional string city = 5; + optional string state = 6; + optional string country = 7; + optional bool is_online = 8; +} + +message CRemoteClient_CreateRemotePlayTogetherInvitation_Request { + optional uint32 appid = 1; + optional string launch_parameters = 2; +} + +message CRemoteClient_CreateRemotePlayTogetherInvitation_Response { + optional string invitation_code = 1; +} + +message CRemoteClient_DeleteRemotePlayTogetherInvitation_Request { + optional string invitation_code = 1; +} + +message CRemoteClient_DeleteRemotePlayTogetherInvitation_Response { +} + +message CRemoteClient_GetPairingInfo_Request { + optional uint32 pin = 1; +} + +message CRemoteClient_GetPairingInfo_Response { + optional fixed64 session_id = 1; + optional fixed64 device_id = 2; + optional bytes request = 3; +} + +message CRemoteClient_GetRecentClients_Request { +} + +message CRemoteClient_GetRecentClients_Response { + repeated CRemoteClient_ClientDetails clients = 1; +} + +message CRemoteClient_MarkTaskComplete_Request { + optional fixed64 remote_client_id = 1; + optional fixed64 task_id = 2; + optional string content_id = 3; +} + +message CRemoteClient_MarkTaskComplete_Response { +} + +message CRemoteClient_Online_Notification { + optional fixed64 steamid = 1; + optional fixed64 remote_client_id = 2; + optional CRemoteClient_DeviceDetails device_details = 3; +} + +message CRemoteClient_ReplyPacket_Notification { + optional fixed64 session_id = 1; + optional bytes payload = 2; +} + +message CRemotePlay_SessionStarted_Request { + optional uint32 host_account_id = 1; + optional uint32 client_account_id = 2; + optional uint32 appid = 3; + optional int32 device_form_factor = 4; + optional bool remote_play_together = 5; + optional bool guest_session = 6; +} + +message CRemotePlay_SessionStarted_Response { + optional fixed64 record_id = 1; +} + +message CRemotePlay_SessionStopped_Notification { + optional fixed64 record_id = 1; + optional bool used_x264 = 2; + optional bool used_h264 = 3; + optional bool used_hevc = 4; +} + +service RemoteClient { + // ePrivilege=1 + rpc AllocateRelayServer (CRemoteClient_AllocateRelayServer_Request) returns (CRemoteClient_AllocateRelayServer_Response); + // ePrivilege=1 + rpc AllocateSDR (CRemoteClient_AllocateSDR_Request) returns (CRemoteClient_AllocateSDR_Response); + // ePrivilege=1 + rpc CreateRemotePlayTogetherInvitation (CRemoteClient_CreateRemotePlayTogetherInvitation_Request) returns (CRemoteClient_CreateRemotePlayTogetherInvitation_Response); + // ePrivilege=1 + rpc DeleteRemotePlayTogetherInvitation (CRemoteClient_DeleteRemotePlayTogetherInvitation_Request) returns (CRemoteClient_DeleteRemotePlayTogetherInvitation_Response); + // ePrivilege=1 + rpc GetPairingInfo (CRemoteClient_GetPairingInfo_Request) returns (CRemoteClient_GetPairingInfo_Response); + // ePrivilege=1 + rpc GetRecentClients (CRemoteClient_GetRecentClients_Request) returns (CRemoteClient_GetRecentClients_Response); + // ePrivilege=1 + rpc MarkTaskComplete (CRemoteClient_MarkTaskComplete_Request) returns (CRemoteClient_MarkTaskComplete_Response); + // ePrivilege=1 + rpc NotifyOnline (CRemoteClient_Online_Notification) returns (NoResponse); + // ePrivilege=1 + rpc NotifyReplyPacket (CRemoteClient_ReplyPacket_Notification) returns (NoResponse); + // ePrivilege=1 + rpc SendRemotePlaySessionStarted (CRemotePlay_SessionStarted_Request) returns (CRemotePlay_SessionStarted_Response); + // ePrivilege=1 + rpc SendRemotePlaySessionStopped (CRemotePlay_SessionStopped_Notification) returns (NoResponse); + // ePrivilege=1 + rpc SendRemotePlayTogetherPacket (CRemotePlayTogether_Notification) returns (NoResponse); + // ePrivilege=1 + rpc SendSteamBroadcastPacket (CRemoteClient_SteamBroadcast_Notification) returns (NoResponse); + // ePrivilege=1 + rpc SendSteamToSteamPacket (CRemoteClient_SteamToSteam_Notification) returns (NoResponse); +} diff --git a/javasteam-protobufs-webui/src/main/proto/in/dragonbra/javasteam/protobufs/webui/service_remoteclientsteam.proto b/javasteam-protobufs-webui/src/main/proto/in/dragonbra/javasteam/protobufs/webui/service_remoteclientsteam.proto new file mode 100644 index 000000000..d555974b5 --- /dev/null +++ b/javasteam-protobufs-webui/src/main/proto/in/dragonbra/javasteam/protobufs/webui/service_remoteclientsteam.proto @@ -0,0 +1,32 @@ +import "in/dragonbra/javasteam/protobufs/webui/common.proto"; +import "in/dragonbra/javasteam/protobufs/webui/common_base.proto"; + +package webui; + +option java_package = "in.dragonbra.javasteam.protobufs.webui"; + +option optimize_for = SPEED; +option java_generic_services = false; + +message CRemoteClient_DisableSteamBroadcast_Notification { +} + +message CRemoteClient_EnableSteamBroadcast_Notification { +} + +message CRemoteClient_TaskList_Notification { + optional fixed64 remote_client_id = 1; + repeated CRemoteClient_Task tasklist = 2; +} + +service RemoteClientSteamClient { + rpc NotifyDisableSteamBroadcast (CRemoteClient_DisableSteamBroadcast_Notification) returns (NoResponse); + rpc NotifyEnableSteamBroadcast (CRemoteClient_EnableSteamBroadcast_Notification) returns (NoResponse); + rpc NotifyRegisterStatusUpdate (CRemoteClient_RegisterStatusUpdate_Notification) returns (NoResponse); + rpc NotifyRemotePacket (CRemoteClient_RemotePacket_Notification) returns (NoResponse); + rpc NotifyRemotePlayTogetherPacket (CRemotePlayTogether_Notification) returns (NoResponse); + rpc NotifySteamBroadcastPacket (CRemoteClient_SteamBroadcast_Notification) returns (NoResponse); + rpc NotifySteamToSteamPacket (CRemoteClient_SteamToSteam_Notification) returns (NoResponse); + rpc NotifyTaskList (CRemoteClient_TaskList_Notification) returns (NoResponse); + rpc NotifyUnregisterStatusUpdate (CRemoteClient_UnregisterStatusUpdate_Notification) returns (NoResponse); +} diff --git a/javasteam-protobufs-webui/src/main/proto/in/dragonbra/javasteam/protobufs/webui/service_wishlist.proto b/javasteam-protobufs-webui/src/main/proto/in/dragonbra/javasteam/protobufs/webui/service_wishlist.proto new file mode 100644 index 000000000..49c43b916 --- /dev/null +++ b/javasteam-protobufs-webui/src/main/proto/in/dragonbra/javasteam/protobufs/webui/service_wishlist.proto @@ -0,0 +1,230 @@ +import "in/dragonbra/javasteam/protobufs/webui/common.proto"; +import "in/dragonbra/javasteam/protobufs/webui/common_base.proto"; + +package webui; + +option java_package = "in.dragonbra.javasteam.protobufs.webui"; + +option optimize_for = SPEED; +option java_generic_services = false; + +message CWishlist_AddToWishlist_Request { + optional uint32 appid = 1; + optional CUserInterface_NavData navdata = 2; +} + +message CWishlist_AddToWishlist_Response { + optional uint32 wishlist_count = 1; +} + +message CWishlist_AddWishlistItemCategory_Request { + optional uint32 appid = 1; + optional uint64 categoryid = 2; + optional string category_name = 3; +} + +message CWishlist_AddWishlistItemCategory_Response { + optional uint64 categoryid = 1; + optional string name = 2; + optional int32 item_count = 3; + optional bool notification_opt_in = 4; +} + +message CWishlist_GetItemCategories_Request { + optional uint32 appid = 1; +} + +message CWishlist_GetItemCategories_Response { + repeated CWishlistCategory categories = 1; +} + +message CWishlist_GetSharedWishlistCategories_Request { + optional fixed64 steamid = 1; + optional string share_token = 2; +} + +message CWishlist_GetSharedWishlistCategories_Response { + repeated CWishlistCategory categories = 1; +} + +message CWishlist_GetWishlist_Request { + optional fixed64 steamid = 1; +} + +message CWishlist_GetWishlist_Response { + repeated CWishlist_GetWishlist_Response_WishlistItem items = 1; +} + +message CWishlist_GetWishlist_Response_WishlistItem { + optional uint32 appid = 1; + optional uint32 priority = 2; + optional uint32 date_added = 3; +} + +message CWishlist_GetWishlistCategories_Request { +} + +message CWishlist_GetWishlistCategories_Response { + repeated CWishlistCategory categories = 1; +} + +message CWishlist_GetWishlistItemCount_Request { + optional fixed64 steamid = 1; +} + +message CWishlist_GetWishlistItemCount_Response { + optional uint32 count = 1; +} + +message CWishlist_GetWishlistItemsOnSale_Request { + optional StoreBrowseContext context = 1; + optional StoreBrowseItemDataRequest data_request = 2; +} + +message CWishlist_GetWishlistItemsOnSale_Response { + repeated CWishlist_GetWishlistItemsOnSale_Response_WishlistItem items = 1; + optional int32 total_items_on_sale = 2; +} + +message CWishlist_GetWishlistItemsOnSale_Response_WishlistItem { + optional uint32 appid = 1; + optional StoreItem store_item = 2; +} + +message CWishlist_GetWishlistSortedFiltered_Request { + optional fixed64 steamid = 1; + optional StoreBrowseContext context = 2; + optional StoreBrowseItemDataRequest data_request = 3; + optional int32 sort_order = 4 [default = 0, (webui.description) = "enum"]; + optional CWishlistFilters filters = 5; + optional int32 start_index = 6 [default = 0]; + optional int32 page_size = 7 [default = 100]; + optional string share_token = 8; +} + +message CWishlist_GetWishlistSortedFiltered_Response { + repeated CWishlist_GetWishlistSortedFiltered_Response_WishlistItem items = 1; +} + +message CWishlist_GetWishlistSortedFiltered_Response_WishlistItem { + optional uint32 appid = 1; + optional uint32 priority = 2; + optional uint32 date_added = 3; + optional StoreItem store_item = 4; + repeated uint64 category_ids = 5; +} + +message CWishlist_RemoveFromWishlist_Request { + optional uint32 appid = 1; +} + +message CWishlist_RemoveFromWishlist_Response { + optional uint32 wishlist_count = 1; +} + +message CWishlist_RemoveWishlistItemCategory_Request { + optional uint32 appid = 1; + optional uint64 categoryid = 2; +} + +message CWishlist_RemoveWishlistItemCategory_Response { +} + +message CWishlist_RenameWishlistCategory_Request { + optional uint64 categoryid = 1; + optional string name = 2; +} + +message CWishlist_RenameWishlistCategory_Response { +} + +message CWishlist_SetWishlistCategoryNotifications_Request { + repeated CWishlist_SetWishlistCategoryNotifications_Request_CategorySettings categories = 1; +} + +message CWishlist_SetWishlistCategoryNotifications_Request_CategorySettings { + optional uint64 categoryid = 1; + optional bool notification_opt_in = 2; +} + +message CWishlist_SetWishlistCategoryNotifications_Response { +} + +message CWishlist_SetWishlistItemCategoryBulk_Request { + repeated uint32 appids = 1; + optional uint64 categoryid = 2; + optional string category_name = 3; + optional bool remove = 4; +} + +message CWishlist_SetWishlistItemCategoryBulk_Response { + optional CWishlistCategory category = 1; + repeated uint32 appids_updated = 2; + repeated uint32 appids_failed = 3; +} + +message CWishlistCategory { + optional uint64 categoryid = 1; + optional string name = 2; + optional int32 item_count = 3; + optional bool notification_opt_in = 4; +} + +message CWishlistFilters { + optional bool macos_only = 1; + optional bool steamos_linux_only = 2; + optional bool only_games = 10; + optional bool only_software = 11; + optional bool only_dlc = 12; + optional bool only_free = 13; + optional int64 max_price_in_cents = 20; + optional int32 min_discount_percent = 21; + optional CWishlistFilters_ExcludeTypeFilters exclude_types = 22; + optional CWishlistFilters_SteamDeckFilters steam_deck_filters = 23; + repeated int32 tagids_must_match = 24; + repeated int32 excluded_content_descriptors = 25 [(webui.description) = "enum"]; + repeated uint64 category_ids = 26; + optional bool has_demo = 27; +} + +message CWishlistFilters_ExcludeTypeFilters { + optional bool exclude_early_access = 1; + optional bool exclude_coming_soon = 2; + optional bool exclude_vr_only = 3; +} + +message CWishlistFilters_SteamDeckFilters { + optional bool include_verified = 1; + optional bool include_playable = 2; +} + +service Wishlist { + // ePrivilege=1 + rpc AddToWishlist (CWishlist_AddToWishlist_Request) returns (CWishlist_AddToWishlist_Response); + // ePrivilege=1 + rpc AddWishlistItemCategory (CWishlist_AddWishlistItemCategory_Request) returns (CWishlist_AddWishlistItemCategory_Response); + // bConstMethod=true, ePrivilege=1 + rpc GetItemCategories (CWishlist_GetItemCategories_Request) returns (CWishlist_GetItemCategories_Response); + // bConstMethod=true, ePrivilege=2, eWebAPIKeyRequirement=1 + rpc GetSharedWishlistCategories (CWishlist_GetSharedWishlistCategories_Request) returns (CWishlist_GetSharedWishlistCategories_Response); + // bConstMethod=true, ePrivilege=2, eWebAPIKeyRequirement=1 + rpc GetWishlist (CWishlist_GetWishlist_Request) returns (CWishlist_GetWishlist_Response); + // bConstMethod=true, ePrivilege=1 + rpc GetWishlistCategories (CWishlist_GetWishlistCategories_Request) returns (CWishlist_GetWishlistCategories_Response); + // bConstMethod=true, ePrivilege=2, eWebAPIKeyRequirement=1 + rpc GetWishlistItemCount (CWishlist_GetWishlistItemCount_Request) returns (CWishlist_GetWishlistItemCount_Response); + // bConstMethod=true, ePrivilege=1 + rpc GetWishlistItemsOnSale (CWishlist_GetWishlistItemsOnSale_Request) returns (CWishlist_GetWishlistItemsOnSale_Response); + // bConstMethod=true, ePrivilege=2, eWebAPIKeyRequirement=1 + rpc GetWishlistSortedFiltered (CWishlist_GetWishlistSortedFiltered_Request) returns (CWishlist_GetWishlistSortedFiltered_Response); + // ePrivilege=1 + rpc RemoveFromWishlist (CWishlist_RemoveFromWishlist_Request) returns (CWishlist_RemoveFromWishlist_Response); + // ePrivilege=1 + rpc RemoveWishlistItemCategory (CWishlist_RemoveWishlistItemCategory_Request) returns (CWishlist_RemoveWishlistItemCategory_Response); + // ePrivilege=1 + rpc RenameWishlistCategory (CWishlist_RenameWishlistCategory_Request) returns (CWishlist_RenameWishlistCategory_Response); + // ePrivilege=1 + rpc SetWishlistCategoryNotifications (CWishlist_SetWishlistCategoryNotifications_Request) returns (CWishlist_SetWishlistCategoryNotifications_Response); + // ePrivilege=1 + rpc SetWishlistItemCategoryBulk (CWishlist_SetWishlistItemCategoryBulk_Request) returns (CWishlist_SetWishlistItemCategoryBulk_Response); +} diff --git a/javasteam-protobufs-webui/src/test/java/in/dragonbra/javasteam/rpc/WebUiUnifiedInterfaceTest.java b/javasteam-protobufs-webui/src/test/java/in/dragonbra/javasteam/rpc/WebUiUnifiedInterfaceTest.java index 9fde5549e..d50cf5548 100644 --- a/javasteam-protobufs-webui/src/test/java/in/dragonbra/javasteam/rpc/WebUiUnifiedInterfaceTest.java +++ b/javasteam-protobufs-webui/src/test/java/in/dragonbra/javasteam/rpc/WebUiUnifiedInterfaceTest.java @@ -23,8 +23,13 @@ public class WebUiUnifiedInterfaceTest { "ClientComm.kt", "CloudConfigStore.kt", "CloudConfigStoreClient.kt", + "FriendsList.kt", + "FriendsListClient.kt", + "RemoteClient.kt", + "RemoteClientSteamClient.kt", "Store.kt", "StoreClient.kt", + "Wishlist.kt", }; @Test @@ -54,4 +59,4 @@ public void testKnownServices() { Assertions.assertTrue(file.exists() && file.isFile(), "File " + filename + " should exist"); } } -} \ No newline at end of file +} diff --git a/protosync-whitelist.txt b/protosync-whitelist.txt index 9202324ec..e0b5fda1b 100644 --- a/protosync-whitelist.txt +++ b/protosync-whitelist.txt @@ -54,6 +54,9 @@ steammessages_useraccount.steamclient.proto steammessages_seasonpass_types.proto steammessages_steamawards_types.proto steammessages_appratings_types.proto +steammessages_remoteclient_discovery.proto +steammessages_remoteclient.proto +steammessages_remoteplay.proto [webui] common.proto @@ -61,6 +64,10 @@ common_base.proto service_clientcomm.proto service_cloudconfigstore.proto service_store.proto +service_remote.proto +service_remoteclientsteam.proto +service_friendslist.proto +service_wishlist.proto [cs] base_gcmessages.proto diff --git a/src/main/java/in/dragonbra/javasteam/steam/authentication/AuthSession.kt b/src/main/java/in/dragonbra/javasteam/steam/authentication/AuthSession.kt index 53adbb1c5..35c34b525 100644 --- a/src/main/java/in/dragonbra/javasteam/steam/authentication/AuthSession.kt +++ b/src/main/java/in/dragonbra/javasteam/steam/authentication/AuthSession.kt @@ -25,7 +25,7 @@ import kotlin.time.Duration.Companion.seconds * @param clientID Unique identifier of requestor, also used for routing, portion of QR code. * @param requestID Unique request ID to be presented by requestor at poll time. * @param allowedConfirmations Confirmation types that will be able to confirm the request. - * @param pollingInterval Refresh interval with which requestor should call PollAuthSessionStatus. + * @param pollingInterval Refresh interval, in seconds, with which requestor should call PollAuthSessionStatus. * @param defaultScope Default coroutine scope used for authentication operations and polling. */ @Suppress("MemberVisibilityCanBePrivate", "unused") diff --git a/src/main/java/in/dragonbra/javasteam/steam/authentication/SteamAuthentication.kt b/src/main/java/in/dragonbra/javasteam/steam/authentication/SteamAuthentication.kt index 627044a1b..9f88303fc 100644 --- a/src/main/java/in/dragonbra/javasteam/steam/authentication/SteamAuthentication.kt +++ b/src/main/java/in/dragonbra/javasteam/steam/authentication/SteamAuthentication.kt @@ -69,8 +69,9 @@ class SteamAuthentication(private val steamClient: SteamClient) { * @param refreshToken the refresh token. * @param allowRenewal If true, allow renewing the token. * @return A [AccessTokenGenerateResult] containing the new token + * The future fails with an [AuthenticationException] if Steam did not generate the token; + * see [AuthenticationException.result]. */ - @Throws(IllegalArgumentException::class, IllegalArgumentException::class) @JvmOverloads fun generateAccessTokenForApp( steamID: SteamID, @@ -90,7 +91,7 @@ class SteamAuthentication(private val steamClient: SteamClient) { val response = authenticationService.generateAccessTokenForApp(request.build()).await() if (response.result != EResult.OK) { - throw IllegalArgumentException("Failed to generate token ${response.result}") + throw AuthenticationException("Failed to generate token", response.result) } return@future AccessTokenGenerateResult(response.body) diff --git a/src/main/java/in/dragonbra/javasteam/steam/cdn/Client.kt b/src/main/java/in/dragonbra/javasteam/steam/cdn/Client.kt index 1fe2ad9d1..d3aeab82e 100644 --- a/src/main/java/in/dragonbra/javasteam/steam/cdn/Client.kt +++ b/src/main/java/in/dragonbra/javasteam/steam/cdn/Client.kt @@ -8,6 +8,7 @@ import `in`.dragonbra.javasteam.util.SteamKitWebRequestException import `in`.dragonbra.javasteam.util.Strings import `in`.dragonbra.javasteam.util.log.LogManager import `in`.dragonbra.javasteam.util.log.Logger +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob @@ -29,8 +30,13 @@ import java.util.zip.ZipInputStream * @constructor Initializes a new instance of the [Client] class. * @param steamClient The [SteamClient] this instance will be associated with. * The SteamClient instance must be connected and logged onto Steam. + * @param httpClient The HTTP client to download with. Defaults to the one of the [steamClient] configuration. + * It is never closed by this class; whoever created it owns it. */ -class Client(steamClient: SteamClient) : Closeable { +class Client @JvmOverloads constructor( + steamClient: SteamClient, + private val httpClient: OkHttpClient = steamClient.configuration.httpClient, +) : Closeable { private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob()) @@ -84,15 +90,15 @@ class Client(steamClient: SteamClient) : Closeable { } } - private val httpClient: OkHttpClient = steamClient.configuration.httpClient - /** - * Disposes of this object. + * Disposes of this object. Cancels the downloads started with the `Future` methods. + * + * The HTTP client is left alone: it belongs to the [SteamClient] configuration or to the caller, and may be shared with + * other [Client] instances and the rest of the library, so shutting it down here would make + * their later requests fail. */ override fun close() { scope.cancel() - httpClient.connectionPool.evictAll() - httpClient.dispatcher.executorService.shutdown() } /** @@ -166,12 +172,17 @@ class Client(steamClient: SteamClient) : Closeable { depotManifest } } + } catch (e: CancellationException) { + // Cancellation is not an error. + throw e } catch (e: Exception) { logger.error("Failed to download manifest ${request.url}: ${e.message}", e) throw e } } + // TODO: depotKey is unused. Restore SK behavior: process the chunk into destination when a key is given. + /** * Downloads the specified depot chunk, and optionally processes the chunk and verifies the checksum if the depot decryption key has been provided. * This function will also validate the length of the downloaded chunk with the value of [ChunkData.compressedLength], @@ -180,10 +191,11 @@ class Client(steamClient: SteamClient) : Closeable { * @param chunk A [ChunkData] instance that represents the chunk to download. * This value should come from a manifest downloaded with [downloadManifest]. * @param server The content server to connect to. - * @param destination The buffer to receive the chunk data. If [depotKey] is provided, this will be the decompressed buffer. - * Allocate or rent a buffer that is equal or longer than [ChunkData.uncompressedLength] + * @param destination The buffer to receive the downloaded chunk data, still encrypted and compressed, starting at index 0. + * Allocate or rent a buffer that is equal or longer than [ChunkData.compressedLength]. A longer one is only filled + * up to the returned length; pass that length on to [DepotChunk.process]. * @param depotKey The depot decryption key for the depot that will be downloaded. - * This is used to process the chunk data. + * Not used here yet: the chunk is not processed by this method. * @param proxyServer Optional content server marked as UseAsProxy which transforms the request. * @param cdnAuthToken CDN auth token for CDN content server endpoints if necessary. Get one with [SteamContent.getCDNAuthToken]. * @return The total number of bytes written to [destination]. @@ -202,8 +214,11 @@ class Client(steamClient: SteamClient) : Closeable { ): Int = withContext(Dispatchers.IO) { val chunkIdBytes = requireNotNull(chunk.chunkID) { "Chunk must have a ChunkID." } - if (destination.size != chunk.compressedLength) { - throw IllegalArgumentException("The destination buffer must be the same size as the chunk CompressedLength (Since we take out decompression step from download") + if (destination.size < chunk.compressedLength) { + throw IllegalArgumentException( + "The destination buffer must be at least as long as the chunk CompressedLength " + + "(is ${destination.size}, needs ${chunk.compressedLength})." + ) } val chunkID = Strings.toHex(chunkIdBytes) @@ -218,55 +233,65 @@ class Client(steamClient: SteamClient) : Closeable { .build() } - try { - val response = httpClient.newCall(request).executeAsync() + val response = httpClient.newCall(request).executeAsync() - response.use { resp -> - if (!resp.isSuccessful) { - throw SteamKitWebRequestException( - "Response status code does not indicate success: ${resp.code} (${resp.message})", - resp - ) - } + response.use { resp -> + if (!resp.isSuccessful) { + throw SteamKitWebRequestException( + "Response status code does not indicate success: ${resp.code} (${resp.message})", + resp + ) + } - var contentLength = chunk.compressedLength + var contentLength = chunk.compressedLength - if (resp.body.contentLength().toInt() > 0) { - contentLength = resp.body.contentLength().toInt() + if (resp.body.contentLength().toInt() > 0) { + contentLength = resp.body.contentLength().toInt() - // assert that lengths match only if the chunk has a length assigned. - if (chunk.compressedLength > 0 && contentLength != chunk.compressedLength) { - throw SteamKitWebRequestException( - "Content-Length mismatch for depot chunk! (was $contentLength, but should be ${chunk.compressedLength})" - ) - } - } else if (contentLength > 0) { - logger.debug("Response does not have Content-Length, falling back to chunk.CompressedLength.") - } else { + // assert that lengths match only if the chunk has a length assigned. + if (chunk.compressedLength > 0 && contentLength != chunk.compressedLength) { throw SteamKitWebRequestException( - "Response does not have Content-Length and chunk.CompressedLength is not set.", - response + "Content-Length mismatch for depot chunk! (was $contentLength, but should be ${chunk.compressedLength})" ) } + } else if (contentLength > 0) { + logger.debug("Response does not have Content-Length, falling back to chunk.CompressedLength.") + } else { + throw SteamKitWebRequestException( + "Response does not have Content-Length and chunk.CompressedLength is not set.", + response + ) + } - val responseBody = resp.body.bytes() + // Only possible when the chunk has no length assigned; otherwise both were checked above. + if (contentLength > destination.size) { + throw SteamKitWebRequestException( + "Depot chunk does not fit the destination buffer! (is $contentLength bytes, buffer is ${destination.size})" + ) + } - if (responseBody.isEmpty()) { - throw SteamKitWebRequestException("Response is empty") - } + val source = resp.body.source() - if (responseBody.size != contentLength) { + // The body is read straight into destination, which may be longer than the chunk + // (a pooled buffer), instead of into a second array that is then copied. + var read = 0 + while (read < contentLength) { + val count = source.read(destination, read, contentLength - read) + if (count == -1) { throw SteamKitWebRequestException( - "Length mismatch after downloading depot chunk! (was ${responseBody.size}, but should be $contentLength)" + "Length mismatch after downloading depot chunk! (body ended after $read of $contentLength bytes)" ) } + read += count + } - System.arraycopy(responseBody, 0, destination, 0, contentLength) - return@withContext contentLength + if (!source.exhausted()) { + throw SteamKitWebRequestException( + "Length mismatch after downloading depot chunk! (body is longer than $contentLength bytes)" + ) } - } catch (e: Exception) { - logger.error("Failed to download a depot chunk ${request.url}: ${e.message}", e) - throw e + + return@withContext contentLength } } diff --git a/src/main/java/in/dragonbra/javasteam/steam/cdn/DepotChunk.kt b/src/main/java/in/dragonbra/javasteam/steam/cdn/DepotChunk.kt index 8d4f9ac44..e94e45e5c 100644 --- a/src/main/java/in/dragonbra/javasteam/steam/cdn/DepotChunk.kt +++ b/src/main/java/in/dragonbra/javasteam/steam/cdn/DepotChunk.kt @@ -2,13 +2,17 @@ package `in`.dragonbra.javasteam.steam.cdn import `in`.dragonbra.javasteam.types.ChunkData import `in`.dragonbra.javasteam.util.Adler32 +import `in`.dragonbra.javasteam.util.JavaSteamAddition import `in`.dragonbra.javasteam.util.Strings import `in`.dragonbra.javasteam.util.VZipUtil import `in`.dragonbra.javasteam.util.VZstdUtil import `in`.dragonbra.javasteam.util.ZipUtil import `in`.dragonbra.javasteam.util.crypto.CryptoHelper import `in`.dragonbra.javasteam.util.stream.MemoryStream +import org.apache.commons.lang3.SystemUtils import java.io.IOException +import java.security.Provider +import java.security.Security import javax.crypto.Cipher import javax.crypto.spec.IvParameterSpec import javax.crypto.spec.SecretKeySpec @@ -18,11 +22,34 @@ import javax.crypto.spec.SecretKeySpec */ object DepotChunk { + /** + * The provider chunks are decrypted with: the platform's own, which uses the AES instructions of + * the CPU where it has them. Bouncy Castle's AES is plain Java and several times slower, which + * matters here because every byte of a download passes through it. It is only the fallback, for a + * runtime that does not have the platform provider. + * + * The provider is named because [CryptoHelper] puts Bouncy Castle first in the provider list on + * Android, so a lookup without one would still pick it there. + */ + @JavaSteamAddition + private val aesProvider: Provider by lazy { + val platform = if (SystemUtils.IS_OS_ANDROID) "AndroidOpenSSL" else "SunJCE" + + Security.getProvider(platform) + ?: Security.getProvider(CryptoHelper.SEC_PROV) + ?: throw IllegalStateException( + "No security provider to decrypt depot chunks with: " + + "neither $platform nor ${CryptoHelper.SEC_PROV} is registered." + ) + } + /** * Processes the specified depot key by decrypting the data with the given depot encryption key, and then by decompressing the data. * If the chunk has already been processed, this function does nothing. + * + * The chunk is decrypted in place: the contents of [data] are overwritten and must not be used afterwards. * @param info The depot chunk data representing. - * @param data The encrypted chunk data. + * @param data The encrypted chunk data. Overwritten by this call. * @param destination The buffer to receive the decrypted chunk data. * @param depotKey The depot decryption key. * @exception IOException Thrown if the processed data does not match the expected checksum given in its chunk information. @@ -34,6 +61,42 @@ object DepotChunk { data: ByteArray, destination: ByteArray, depotKey: ByteArray, + ): Int = process(info, data, data.size, destination, depotKey) + + /** + * Processes the specified depot key by decrypting the data with the given depot encryption key, and then by decompressing the data. + * This overload is for a [data] buffer that is longer than the chunk in it, such as a pooled one. + * + * The chunk is decrypted in place: the first [length] bytes of [data] are overwritten and must not be used afterwards. + * @param info The depot chunk data representing. + * @param data The buffer holding the encrypted chunk data, starting at index 0. Overwritten by this call. + * @param length The number of bytes of [data] that hold the encrypted chunk. + * @param destination The buffer to receive the decrypted chunk data. + * @param depotKey The depot decryption key. + * @exception IOException Thrown if the processed data does not match the expected checksum given in its chunk information. + * @exception IllegalArgumentException Thrown if the destination size is too small, [length] is outside [data], + * or the depot key is not 32 bytes long + */ + @JavaSteamAddition + @JvmStatic + fun process( + info: ChunkData, + data: ByteArray, + length: Int, + destination: ByteArray, + depotKey: ByteArray, + ): Int = process(info, data, length, destination, depotKey, aesProvider) + + /** The implementation, with the provider as a parameter so tests can run it on the fallback provider too. */ + @JvmStatic + @JvmName("processWithProvider") + internal fun process( + info: ChunkData, + data: ByteArray, + length: Int, + destination: ByteArray, + depotKey: ByteArray, + provider: Provider, ): Int { require(destination.size >= info.uncompressedLength) { "The destination buffer must be longer than the chunk ${ChunkData::uncompressedLength.name}." @@ -42,25 +105,39 @@ object DepotChunk { require(depotKey.size == 32) { "Tried to decrypt depot chunk with non 32 byte key!" } // first 16 bytes of input is the ECB encrypted IV + val iv = ByteArray(16) + + require(length in iv.size..data.size) { + "length ($length) must be between ${iv.size} and the size of the data buffer (${data.size})." + } + val keySpec = SecretKeySpec(depotKey, "AES") - val ecbCipher = Cipher.getInstance("AES/ECB/NoPadding", CryptoHelper.SEC_PROV) + val ecbCipher = Cipher.getInstance("AES/ECB/NoPadding", provider) ecbCipher.init(Cipher.DECRYPT_MODE, keySpec) - val iv = ByteArray(16) val ivBytesRead = ecbCipher.doFinal(data, 0, iv.size, iv) require(iv.size == ivBytesRead) { "Failed to decrypt depot chunk iv (${iv.size} != $ivBytesRead)" } - val aes = Cipher.getInstance("AES/CBC/PKCS7Padding", CryptoHelper.SEC_PROV) + // PKCS5Padding is the name every provider knows; for AES it is the same padding as PKCS7. + val aes = Cipher.getInstance("AES/CBC/PKCS5Padding", provider) aes.init(Cipher.DECRYPT_MODE, keySpec, IvParameterSpec(iv)) - // With CBC and padding, the decrypted size will always be smaller - val buffer = ByteArray(data.size - iv.size) + // Decrypted in place instead of into a second array per chunk: the output starts exactly + // where the input does, right after the IV. With CBC and padding the decrypted size is + // always smaller than the input. + // + // The output must not be moved to index 0, 16 bytes behind the input. Cipher.doFinal is + // documented as copy-safe, but Android's provider (Conscrypt) hands both ranges straight to + // BoringSSL, which only supports an output that is the input exactly or does not overlap it + // at all. A shifted overlap may work on one CPU's AES code path and corrupt on another's. + val buffer = data + val start = iv.size val writtenDecompressed: Int try { - val written = aes.doFinal(data, iv.size, data.size - iv.size, buffer) + val written = aes.doFinal(data, start, length - start, buffer, start) // Per SK: // Steam client checks for like 20 bytes for pkzip, and 22 bytes for vzip, @@ -69,39 +146,43 @@ object DepotChunk { throw IOException("Not enough data in the decrypted depot chunk (was $written bytes).") } - if (buffer[0] == 'V'.code.toByte() && - buffer[1] == 'S'.code.toByte() && - buffer[2] == 'Z'.code.toByte() && - buffer[3] == 'a'.code.toByte() + if (buffer[start] == 'V'.code.toByte() && + buffer[start + 1] == 'S'.code.toByte() && + buffer[start + 2] == 'Z'.code.toByte() && + buffer[start + 3] == 'a'.code.toByte() ) { - // Zstd + // Zstd. VZstdUtil reads from index 0, so the decrypted data is moved down first; + // System.arraycopy is safe for ranges that overlap. + System.arraycopy(buffer, start, buffer, 0, written) + writtenDecompressed = VZstdUtil.decompress( - buffer = buffer.copyOfRange(0, written), + buffer = buffer, destination = destination, verifyChecksum = false, + length = written, ) - } else if (buffer[0] == 'V'.code.toByte() && - buffer[1] == 'Z'.code.toByte() && - buffer[2] == 'a'.code.toByte() + } else if (buffer[start] == 'V'.code.toByte() && + buffer[start + 1] == 'Z'.code.toByte() && + buffer[start + 2] == 'a'.code.toByte() ) { // LZMA - MemoryStream(buffer, 0, written).use { decryptedStream -> + MemoryStream(buffer, start, written).use { decryptedStream -> writtenDecompressed = VZipUtil.decompress( ms = decryptedStream, destination = destination, verifyChecksum = false ) } - } else if (buffer[0] == 'P'.code.toByte() && - buffer[1] == 'K'.code.toByte() && - buffer[2].toInt() == 0x03 && - buffer[3].toInt() == 0x04 + } else if (buffer[start] == 'P'.code.toByte() && + buffer[start + 1] == 'K'.code.toByte() && + buffer[start + 2].toInt() == 0x03 && + buffer[start + 3].toInt() == 0x04 ) { // Per SK: // Steam client code performs the same check. // PKzip - MemoryStream(buffer, 0, written).use { decryptedStream -> + MemoryStream(buffer, start, written).use { decryptedStream -> writtenDecompressed = ZipUtil.decompress( ms = decryptedStream, destination = destination, @@ -111,14 +192,12 @@ object DepotChunk { } else { throw IOException( "Unexpected depot chunk compression " + - "(first four bytes are ${Strings.toHex(buffer.copyOfRange(0, 4))})." + "(first four bytes are ${Strings.toHex(buffer.copyOfRange(start, start + 4))})." ) } } catch (e: Exception) { val chunkID = info.chunkID?.let { Strings.toHex(it) } ?: "unknown" throw IOException("Failed to decompress chunk $chunkID: $e\n${e.stackTraceToString()}") - } finally { - buffer.fill(0) } if (info.uncompressedLength != writtenDecompressed) { @@ -128,7 +207,7 @@ object DepotChunk { ) } - val dataCrc = Adler32.calculate(destination.sliceArray(0 until writtenDecompressed)) + val dataCrc = Adler32.calculate(0, destination, 0, writtenDecompressed) if (dataCrc != info.checksum) { throw IOException("Processed data checksum is incorrect ($dataCrc != ${info.checksum})! Downloaded depot chunk is corrupt or invalid/wrong depot key?") diff --git a/src/main/java/in/dragonbra/javasteam/steam/handlers/steamfriends/SteamFriends.kt b/src/main/java/in/dragonbra/javasteam/steam/handlers/steamfriends/SteamFriends.kt index 0a482c51d..abdab5de3 100644 --- a/src/main/java/in/dragonbra/javasteam/steam/handlers/steamfriends/SteamFriends.kt +++ b/src/main/java/in/dragonbra/javasteam/steam/handlers/steamfriends/SteamFriends.kt @@ -657,7 +657,7 @@ class SteamFriends : ClientMsgHandler() { * @return The Job ID of the request. This can be used to find the appropriate [NicknameCallback]. */ @JavaSteamAddition - fun setFriendNickname(friendID: SteamID, nickname: String): JobID { + fun setFriendNickname(friendID: SteamID, nickname: String): AsyncJobSingle { val jobID: JobID = client.getNextJobID() val request = ClientMsgProtobuf( CMsgClientSetPlayerNickname::class.java, @@ -671,7 +671,7 @@ class SteamFriends : ClientMsgHandler() { client.send(request) - return jobID + return AsyncJobSingle(client, jobID) } /** @@ -865,11 +865,20 @@ class SteamFriends : ClientMsgHandler() { if (EClientPersonaStateFlag.Presence in flags) { cacheFriend.avatarHash = friend.avatarHash.toByteArray() - cacheFriend.personaState = EPersonaState.from(friend.personaState) ?: EPersonaState.Offline - cacheFriend.personaStateFlags = EPersonaStateFlag.from(friend.personaStateFlags) + + // JavaSteam addition: SteamKit copies these fields unconditionally. + // Replies to ClientRequestFriendData carry profile data only and omit the + // presence fields; an absent persona_state must not reset a cached state. + // The same presence check guards the GameDataBlob block below. + if (friend.hasPersonaState()) { + cacheFriend.personaState = EPersonaState.from(friend.personaState) ?: EPersonaState.Offline + } + if (friend.hasPersonaStateFlags()) { + cacheFriend.personaStateFlags = EPersonaStateFlag.from(friend.personaStateFlags) + } } - if (EClientPersonaStateFlag.GameDataBlob in flags) { + if (EClientPersonaStateFlag.GameDataBlob in flags && friend.hasGamePlayedAppId()) { cacheFriend.gameName = friend.gameName cacheFriend.gameID = GameID(friend.gameid) cacheFriend.gameAppID = friend.gamePlayedAppId diff --git a/src/main/java/in/dragonbra/javasteam/steam/handlers/steamfriends/callback/NicknameListCallback.kt b/src/main/java/in/dragonbra/javasteam/steam/handlers/steamfriends/callback/NicknameListCallback.kt index 0fad1d4a6..f8a3340fb 100644 --- a/src/main/java/in/dragonbra/javasteam/steam/handlers/steamfriends/callback/NicknameListCallback.kt +++ b/src/main/java/in/dragonbra/javasteam/steam/handlers/steamfriends/callback/NicknameListCallback.kt @@ -11,6 +11,17 @@ import `in`.dragonbra.javasteam.steam.steamclient.callbackmgr.CallbackMsg */ class NicknameListCallback(packetMsg: IPacketMsg) : CallbackMsg() { + /** + * Gets a value indicating whether this [NicknameListCallback] is an incremental update. + * If **false**, [nicknames] is the whole list and replaces any nicknames known before. + */ + val isIncremental: Boolean + + /** + * Gets a value indicating whether the [nicknames] of this update were removed. + */ + val isRemoval: Boolean + /** * Gets the list of nicknames */ @@ -22,6 +33,8 @@ class NicknameListCallback(packetMsg: IPacketMsg) : CallbackMsg() { packetMsg ) + isIncremental = response.body.incremental + isRemoval = response.body.removal nicknames = response.body.nicknamesList.map { PlayerNickname(it) } } } diff --git a/src/main/java/in/dragonbra/javasteam/steam/handlers/steamfriends/callback/PersonaStateCallback.kt b/src/main/java/in/dragonbra/javasteam/steam/handlers/steamfriends/callback/PersonaStateCallback.kt index e2957ab0f..5612ccd26 100644 --- a/src/main/java/in/dragonbra/javasteam/steam/handlers/steamfriends/callback/PersonaStateCallback.kt +++ b/src/main/java/in/dragonbra/javasteam/steam/handlers/steamfriends/callback/PersonaStateCallback.kt @@ -7,9 +7,11 @@ import `in`.dragonbra.javasteam.protobufs.steamclient.SteammessagesClientserverF import `in`.dragonbra.javasteam.steam.handlers.steamfriends.ClanData import `in`.dragonbra.javasteam.steam.handlers.steamfriends.KV import `in`.dragonbra.javasteam.steam.handlers.steamfriends.OtherGameData +import `in`.dragonbra.javasteam.steam.handlers.steamfriends.SteamFriends import `in`.dragonbra.javasteam.steam.steamclient.callbackmgr.CallbackMsg import `in`.dragonbra.javasteam.types.GameID import `in`.dragonbra.javasteam.types.SteamID +import `in`.dragonbra.javasteam.util.JavaSteamAddition import `in`.dragonbra.javasteam.util.NetHelpers import java.net.InetAddress import java.util.* @@ -39,6 +41,23 @@ class PersonaStateCallback( @get:JvmName("getState") val personaState: EPersonaState = EPersonaState.from(friend.personaState) ?: EPersonaState.Offline + /** + * Gets whether the message included a persona state at all. + * + * Replies to [SteamFriends.requestFriendInfo] carry + * profile data only and omit `persona_state`; [personaState] is then [EPersonaState.Offline] by default and + * must not be treated as the friend going offline. Genuine presence updates always set this to `true`. + */ + @JavaSteamAddition + val hasPersonaState: Boolean = friend.hasPersonaState() + + /** + * Gets whether the message included game information (`game_played_app_id`). + * Profile-only replies omit it; see [hasPersonaState]. + */ + @JavaSteamAddition + val hasGamePlayedAppId: Boolean = friend.hasGamePlayedAppId() + /** * Gets the game app ID being played. */ diff --git a/src/main/java/in/dragonbra/javasteam/steam/steamclient/AsyncJobTimeoutException.kt b/src/main/java/in/dragonbra/javasteam/steam/steamclient/AsyncJobTimeoutException.kt new file mode 100644 index 000000000..a771dc831 --- /dev/null +++ b/src/main/java/in/dragonbra/javasteam/steam/steamclient/AsyncJobTimeoutException.kt @@ -0,0 +1,17 @@ +package `in`.dragonbra.javasteam.steam.steamclient + +import `in`.dragonbra.javasteam.util.JavaSteamAddition +import java.util.concurrent.CancellationException + +/** + * Thrown when a pending [in.dragonbra.javasteam.types.AsyncJob] gets no answer from Steam in time. + * + * As in SteamKit a timed out job is cancelled, so this is a [CancellationException] and the job's future + * reports `isCancelled`. Catching this type tells a timeout apart from the caller itself being cancelled. + */ +@Suppress("unused") +@JavaSteamAddition +class AsyncJobTimeoutException : CancellationException { + constructor() : super("The async job timed out waiting for a response from Steam.") + constructor(message: String?) : super(message) +} diff --git a/src/main/java/in/dragonbra/javasteam/types/AsyncJobMultiple.kt b/src/main/java/in/dragonbra/javasteam/types/AsyncJobMultiple.kt index 849c7ff5a..af8f8f9af 100644 --- a/src/main/java/in/dragonbra/javasteam/types/AsyncJobMultiple.kt +++ b/src/main/java/in/dragonbra/javasteam/types/AsyncJobMultiple.kt @@ -1,6 +1,7 @@ package `in`.dragonbra.javasteam.types import `in`.dragonbra.javasteam.steam.steamclient.AsyncJobFailedException +import `in`.dragonbra.javasteam.steam.steamclient.AsyncJobTimeoutException import `in`.dragonbra.javasteam.steam.steamclient.SteamClient import `in`.dragonbra.javasteam.steam.steamclient.callbackmgr.CallbackMsg import kotlinx.coroutines.CancellationException @@ -50,6 +51,10 @@ class AsyncJobMultiple( /** * Suspends until this job completes. The caller resumes on its own dispatcher, * not on the network thread that completed the job. + * + * @throws AsyncJobFailedException Steam reported a remote failure before any result arrived. + * @throws AsyncJobTimeoutException The job timed out before any result arrived. This is a + * `CancellationException`: left uncaught it ends the calling coroutine as if it had been cancelled. */ suspend fun await(): ResultSet = deferred.await() @@ -88,7 +93,7 @@ class AsyncJobMultiple( deferred.completeExceptionally(AsyncJobFailedException()) } else { // otherwise, normal task cancellation for timeouts - deferred.cancel() + deferred.cancel(AsyncJobTimeoutException()) } } else { deferred.complete(ResultSet(false, dueToRemoteFailure, Collections.unmodifiableList(results.toList()))) diff --git a/src/main/java/in/dragonbra/javasteam/types/AsyncJobSingle.kt b/src/main/java/in/dragonbra/javasteam/types/AsyncJobSingle.kt index 16f06046d..2a472490e 100644 --- a/src/main/java/in/dragonbra/javasteam/types/AsyncJobSingle.kt +++ b/src/main/java/in/dragonbra/javasteam/types/AsyncJobSingle.kt @@ -1,6 +1,7 @@ package `in`.dragonbra.javasteam.types import `in`.dragonbra.javasteam.steam.steamclient.AsyncJobFailedException +import `in`.dragonbra.javasteam.steam.steamclient.AsyncJobTimeoutException import `in`.dragonbra.javasteam.steam.steamclient.SteamClient import `in`.dragonbra.javasteam.steam.steamclient.callbackmgr.CallbackMsg import kotlinx.coroutines.CompletableDeferred @@ -26,6 +27,10 @@ class AsyncJobSingle(client: SteamClient, jobId: JobID) : Async /** * Suspends until this job completes. The caller resumes on its own dispatcher, * not on the network thread that completed the job. + * + * @throws AsyncJobFailedException Steam reported a remote failure. + * @throws AsyncJobTimeoutException The job timed out. This is a `CancellationException`: left uncaught + * it ends the calling coroutine as if it had been cancelled. */ suspend fun await(): T = deferred.await() @@ -57,7 +62,7 @@ class AsyncJobSingle(client: SteamClient, jobId: JobID) : Async deferred.completeExceptionally(AsyncJobFailedException()) } else { // if we time out, we cancel the future - deferred.cancel() + deferred.cancel(AsyncJobTimeoutException()) } } } diff --git a/src/main/java/in/dragonbra/javasteam/util/Adler32.kt b/src/main/java/in/dragonbra/javasteam/util/Adler32.kt index 08ee1f641..2c102f173 100644 --- a/src/main/java/in/dragonbra/javasteam/util/Adler32.kt +++ b/src/main/java/in/dragonbra/javasteam/util/Adler32.kt @@ -1,6 +1,16 @@ package `in`.dragonbra.javasteam.util -// See https://www.rfc-editor.org/rfc/rfc1950.html +import java.util.zip.Adler32 as ZlibAdler32 + +/** + * Adler-32 checksums (see [RFC 1950](https://www.rfc-editor.org/rfc/rfc1950.html)) with a seed of the caller's choice. + * + * Steam checksums depot chunks with a seed of 0, where standard Adler-32 (zlib) starts at 1. + * + * The bytes are summed by [java.util.zip.Adler32], which is native code or a JIT intrinsic on + * every runtime and far faster than a loop written here. It can only start at 1, so the result is + * moved to the requested seed afterwards, which is a few arithmetic operations. + */ object Adler32 { /** @@ -9,85 +19,62 @@ object Adler32 { private const val BASE = 65521 /** - * NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 - */ - private const val NMAX = 5552 - - /** - * Calculates the Adler32 checksum with the bytes taken from the span using `one` as the initial seed. + * Calculates the Adler32 checksum of the whole [ByteArray] using 0 as the initial seed, + * which is what Steam uses for depot chunks. This is not the standard Adler-32 value, which starts at 1. + * @param buffer The byte array to process + * @return The Adler-32 checksum, seeded with 0 */ @JvmStatic fun calculate(buffer: ByteArray): Int = calculate(0, buffer) /** * Calculates the Adler32 checksum with the bytes taken from the [ByteArray] - * @param adler The input Adler32 value. (use 1 for initial calculation) + * @param adler The input Adler32 value: 0 for a Steam depot chunk checksum, 1 for standard Adler-32, + * or the result of an earlier call to continue that checksum with more data. * @param buffer The byte array to process * @return The updated Adler-32 checksum */ @JvmStatic - fun calculate(adler: Int, buffer: ByteArray): Int { - var s1 = (adler and 0xFFFF).toLong() - var s2 = ((adler ushr 16) and 0xFFFF).toLong() - - var offset = 0 - val length = buffer.size + fun calculate(adler: Int, buffer: ByteArray): Int = calculate(adler, buffer, 0, buffer.size) - while (offset < length) { - val k = minOf(length - offset, NMAX) - val chunkEnd = offset + k - var remaining = k - - // Unroll by 16 bytes for maximum performance - while (remaining >= 16) { - s1 += (buffer[offset].toInt() and 0xFF).toLong() - s2 += s1 - s1 += (buffer[offset + 1].toInt() and 0xFF).toLong() - s2 += s1 - s1 += (buffer[offset + 2].toInt() and 0xFF).toLong() - s2 += s1 - s1 += (buffer[offset + 3].toInt() and 0xFF).toLong() - s2 += s1 - s1 += (buffer[offset + 4].toInt() and 0xFF).toLong() - s2 += s1 - s1 += (buffer[offset + 5].toInt() and 0xFF).toLong() - s2 += s1 - s1 += (buffer[offset + 6].toInt() and 0xFF).toLong() - s2 += s1 - s1 += (buffer[offset + 7].toInt() and 0xFF).toLong() - s2 += s1 - s1 += (buffer[offset + 8].toInt() and 0xFF).toLong() - s2 += s1 - s1 += (buffer[offset + 9].toInt() and 0xFF).toLong() - s2 += s1 - s1 += (buffer[offset + 10].toInt() and 0xFF).toLong() - s2 += s1 - s1 += (buffer[offset + 11].toInt() and 0xFF).toLong() - s2 += s1 - s1 += (buffer[offset + 12].toInt() and 0xFF).toLong() - s2 += s1 - s1 += (buffer[offset + 13].toInt() and 0xFF).toLong() - s2 += s1 - s1 += (buffer[offset + 14].toInt() and 0xFF).toLong() - s2 += s1 - s1 += (buffer[offset + 15].toInt() and 0xFF).toLong() - s2 += s1 + /** + * Calculates the Adler32 checksum over a range of the [ByteArray], without copying it. + * @param adler The input Adler32 value: 0 for a Steam depot chunk checksum, 1 for standard Adler-32, + * or the result of an earlier call to continue that checksum with more data. + * @param buffer The byte array to process + * @param offset Index of the first byte to process + * @param length Number of bytes to process. With 0, [adler] is returned unchanged. + * @return The updated Adler-32 checksum + * @throws IllegalArgumentException if the range is outside [buffer] + */ + @JvmStatic + fun calculate(adler: Int, buffer: ByteArray, offset: Int, length: Int): Int { + require(offset >= 0 && length >= 0 && offset <= buffer.size - length) { + "Range (offset $offset, length $length) is outside the buffer (size ${buffer.size})." + } - offset += 16 - remaining -= 16 - } + // Nothing to add: the seed is the result, as before. + if (length == 0) return adler - for (i in 0 until remaining) { - s1 += (buffer[offset + i].toInt() and 0xFF).toLong() - s2 += s1 - } + // zlib's sum of the data alone. It always starts at 1. + val zlib = ZlibAdler32() + zlib.update(buffer, offset, length) + val value = zlib.value - offset = chunkEnd + // Move the sum from zlib's start (1, 0) to the seed that was passed in. + // Over n bytes, the low half is seed1 + sum(bytes) and the high half is + // seed2 + n * seed1 + (sum of the running low sums), both modulo BASE. zlib computed the + // same with seed1 = 1 and seed2 = 0, so the difference is (seed1 - 1) in the low half + // and seed2 + n * (seed1 - 1) in the high half. Every term below fits a Long easily. + val seed1 = (adler and 0xFFFF).toLong() + val seed2 = ((adler ushr 16) and 0xFFFF).toLong() - s1 %= BASE - s2 %= BASE - } + val s1 = mod(seed1 + (value and 0xFFFF) - 1) + val s2 = mod(seed2 + (value ushr 16) + (length % BASE) * mod(seed1 - 1)) return ((s2 shl 16) or s1).toInt() } + + /** Remainder that is never negative. */ + private fun mod(x: Long): Long = ((x % BASE) + BASE) % BASE } diff --git a/src/main/java/in/dragonbra/javasteam/util/HardwareUtils.kt b/src/main/java/in/dragonbra/javasteam/util/HardwareUtils.kt index 71cfd3dda..9d2525f77 100644 --- a/src/main/java/in/dragonbra/javasteam/util/HardwareUtils.kt +++ b/src/main/java/in/dragonbra/javasteam/util/HardwareUtils.kt @@ -16,6 +16,7 @@ object HardwareUtils { private val serialNumber: String by lazy { when { + SystemUtils.IS_OS_ANDROID -> null SystemUtils.IS_OS_WINDOWS -> getSerialNumberWin() SystemUtils.IS_OS_MAC -> getSerialNumberMac() SystemUtils.IS_OS_LINUX -> getSerialNumberUnix() diff --git a/src/main/java/in/dragonbra/javasteam/util/VZipUtil.kt b/src/main/java/in/dragonbra/javasteam/util/VZipUtil.kt index fa705a3a0..55a06fb47 100644 --- a/src/main/java/in/dragonbra/javasteam/util/VZipUtil.kt +++ b/src/main/java/in/dragonbra/javasteam/util/VZipUtil.kt @@ -5,11 +5,11 @@ import `in`.dragonbra.javasteam.util.log.LogManager import `in`.dragonbra.javasteam.util.stream.BinaryReader import `in`.dragonbra.javasteam.util.stream.MemoryStream import `in`.dragonbra.javasteam.util.stream.SeekOrigin +import org.tukaani.xz.BasicArrayCache import org.tukaani.xz.LZMAInputStream import java.util.zip.DataFormatException -import kotlin.math.max -@Suppress("SpellCheckingInspection", "unused") +@Suppress("unused") object VZipUtil { private val logger = LogManager.getLogger() @@ -60,15 +60,15 @@ object VZipUtil { // jump back to the beginning of the compressed data ms.position = compressedBytesOffset - // If the value of dictionary size in properties is smaller than (1 << 12), - // the LZMA decoder must set the dictionary size variable to (1 << 12). - val windowBuffer = ByteArray(max(1 shl 12, dictionarySize)) + // No preset dictionary. The cache hands the decoder's own dictionary array + // back for the next chunk once the stream is closed. val bytesRead = LZMAInputStream( ms, sizeDecompressed.toLong(), propertyBits, dictionarySize, - windowBuffer + null, + BasicArrayCache.getInstance() ).use { lzmaInput -> lzmaInput.readNBytesCompat(destination, 0, sizeDecompressed) } diff --git a/src/main/java/in/dragonbra/javasteam/util/VZstdUtil.kt b/src/main/java/in/dragonbra/javasteam/util/VZstdUtil.kt index 20dd000ef..b5013f0a1 100644 --- a/src/main/java/in/dragonbra/javasteam/util/VZstdUtil.kt +++ b/src/main/java/in/dragonbra/javasteam/util/VZstdUtil.kt @@ -1,5 +1,6 @@ package `in`.dragonbra.javasteam.util +import com.github.luben.zstd.RecyclingBufferPool import com.github.luben.zstd.ZstdInputStream import `in`.dragonbra.javasteam.util.log.LogManager import java.io.ByteArrayInputStream @@ -16,11 +17,26 @@ object VZstdUtil { private val logger = LogManager.getLogger() + /** + * Decompresses VZstd data. + * @param buffer The compressed data, starting at index 0. + * @param destination The buffer to receive the decompressed data. + * @param verifyChecksum Whether to verify the CRC32 of the decompressed data. + * @param length Number of bytes of [buffer] that hold the compressed data. Defaults to all of it. + * @return The number of bytes written to [destination]. + */ @Throws(IOException::class, IllegalArgumentException::class) @JvmStatic @JvmOverloads - fun decompress(buffer: ByteArray, destination: ByteArray, verifyChecksum: Boolean = false): Int { - if (buffer.size < HEADER_SIZE + FOOTER_SIZE) { + fun decompress( + buffer: ByteArray, + destination: ByteArray, + verifyChecksum: Boolean = false, + length: Int = buffer.size, + ): Int { + require(length in 0..buffer.size) { "length ($length) is outside the buffer (size ${buffer.size})." } + + if (length < HEADER_SIZE + FOOTER_SIZE) { throw IOException("Buffer too small to contain VZstd header and footer") } @@ -34,7 +50,7 @@ object VZstdUtil { // val crc32 = byteBuffer.getInt(4) // Read footer - val footerOffset = buffer.size - FOOTER_SIZE + val footerOffset = length - FOOTER_SIZE val crc32Footer = byteBuffer.getInt(footerOffset) val sizeDecompressed = byteBuffer.getInt(footerOffset + 4) @@ -44,9 +60,9 @@ object VZstdUtil { // logger.debug("CRC32 appears to be written twice in the data") // } - if (buffer[buffer.size - 3] != 'z'.code.toByte() || - buffer[buffer.size - 2] != 's'.code.toByte() || - buffer[buffer.size - 1] != 'v'.code.toByte() + if (buffer[length - 3] != 'z'.code.toByte() || + buffer[length - 2] != 's'.code.toByte() || + buffer[length - 1] != 'v'.code.toByte() ) { throw IOException("Expecting VZstdFooter at end of stream") } @@ -60,8 +76,12 @@ object VZstdUtil { var totalDecompressed = 0 // Use direct ByteArrayInputStream with offset to avoid copying compressed data - ByteArrayInputStream(buffer, HEADER_SIZE, buffer.size - FOOTER_SIZE).use { byteStream -> - ZstdInputStream(byteStream).use { zstdStream -> + // The third argument is a length from the offset, not an end position. + ByteArrayInputStream(buffer, HEADER_SIZE, length - HEADER_SIZE - FOOTER_SIZE).use { byteStream -> + // The pool hands the ~128KB source buffer back on close(), so chunks reuse it instead of + // allocating one each. It is thread-safe. Keep this reference inside the try block: + // zstd is 'compileOnly', and the pool class must not load before the catch below can see it. + ZstdInputStream(byteStream, RecyclingBufferPool.INSTANCE).use { zstdStream -> var bytesRead: Int var offset = 0 diff --git a/src/main/java/in/dragonbra/javasteam/util/crypto/CryptoHelper.java b/src/main/java/in/dragonbra/javasteam/util/crypto/CryptoHelper.java index 08083784a..b758349f4 100644 --- a/src/main/java/in/dragonbra/javasteam/util/crypto/CryptoHelper.java +++ b/src/main/java/in/dragonbra/javasteam/util/crypto/CryptoHelper.java @@ -41,7 +41,10 @@ public class CryptoHelper { } catch (Exception e) { // Try BouncyCastle as fallback var provider = (Class) Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider"); - Security.insertProviderAt(provider.getDeclaredConstructor().newInstance(), 1); + var bouncyCastle = provider.getDeclaredConstructor().newInstance(); + // Android's built-in "BC" must be removed first, or the insert is ignored. + Security.removeProvider(bouncyCastle.getName()); + Security.insertProviderAt(bouncyCastle, 1); androidSecProv = "BC"; } diff --git a/src/main/proto/in/dragonbra/javasteam/protobufs/steamclient/steammessages_cloud.steamclient.proto b/src/main/proto/in/dragonbra/javasteam/protobufs/steamclient/steammessages_cloud.steamclient.proto index 3a2ee6545..bad4bdb5f 100644 --- a/src/main/proto/in/dragonbra/javasteam/protobufs/steamclient/steammessages_cloud.steamclient.proto +++ b/src/main/proto/in/dragonbra/javasteam/protobufs/steamclient/steammessages_cloud.steamclient.proto @@ -61,6 +61,7 @@ message CCloud_BeginUGCUpload_Request { optional string file_sha = 4; optional string content_type = 5; optional bool is_public = 6; + optional uint64 timestamp = 7; } message CCloud_BeginUGCUpload_Response { diff --git a/src/main/proto/in/dragonbra/javasteam/protobufs/steamclient/steammessages_remoteclient.proto b/src/main/proto/in/dragonbra/javasteam/protobufs/steamclient/steammessages_remoteclient.proto new file mode 100644 index 000000000..f494aa616 --- /dev/null +++ b/src/main/proto/in/dragonbra/javasteam/protobufs/steamclient/steammessages_remoteclient.proto @@ -0,0 +1,291 @@ +import "in/dragonbra/javasteam/protobufs/steamclient/steammessages_base.proto"; +import "in/dragonbra/javasteam/protobufs/steamclient/steammessages_remoteclient_discovery.proto"; + +option java_package = "in.dragonbra.javasteam.protobufs.steamclient"; + +option optimize_for = SPEED; +option java_generic_services = false; + +enum ERemoteClientPairWifiAPResult { + k_ERemoteClientPairWifiAPOK = 1; + k_ERemoteClientPairWifiAPFail = 2; + k_ERemoteClientPairWifiAPNetworkError = 3; + k_ERemoteClientPairWifiAPUnauthorized = 4; + k_ERemoteClientPairWifiAPNoDonglePresent = 5; + k_ERemoteClientPairWifiAPTimeout = 6; + k_ERemoteClientPairWifiAPCanceled = 7; + k_ERemoteClientPairWifiAPProgress = 8; + k_ERemoteClientPairWifiAPConnectFailed = 9; + k_ERemoteClientPairWifiAPPINTimeout = 10; +} + +enum EStreamingDongleFixResult { + k_EStreamingDongleFixResultSuccess = 1; + k_EStreamingDongleFixResultFailure = 2; +} + +message CMsgRemoteClientStatus { + optional uint64 client_id = 1; + optional uint64 instance_id = 2; + optional .CMsgRemoteClientBroadcastStatus status = 3; +} + +message CMsgRemoteClientDownloadStatus { + optional uint32 current_connections = 1; + optional uint32 current_bps = 2; + optional uint64 total_bytes_downloaded = 3; + optional uint32 recent_bps = 4; + optional uint64 remote_client_id = 5; + optional int32 download_throttle_rate = 6; + optional string remote_client_name = 7; +} + +message CMsgRemoteClientUploadStatus { + optional uint32 served_app_id = 1; + optional uint32 num_clients = 2; + optional uint32 send_bytes_per_sec = 3; + optional uint32 read_bytes_per_sec = 4; + optional uint64 send_bytes_total = 5; + optional uint64 read_bytes_total = 6; + optional uint64 remote_client_id = 7; + optional string remote_client_name = 8; +} + +message CMsgRemoteClientRestrictAutoUpdates { + optional bool restrict_auto_updates = 1; + optional int32 restrict_auto_updates_start = 2; + optional int32 restrict_auto_updates_end = 3; +} + +message AppStageProgress { + optional uint64 in_progress = 1; + optional uint64 total = 2; + optional int32 estimated_time_remaining_secs = 3; + optional float weight = 4; +} + +message AppUpdateInfo { + optional fixed32 time_update_start = 1; + optional uint64 bytes_to_download = 2; + optional uint64 bytes_downloaded = 3; + optional uint64 bytes_to_process = 4; + optional uint64 bytes_processed = 5; + optional int32 estimated_seconds_remaining = 6 [default = -1]; + optional int32 update_result = 7; + optional uint32 update_state = 8; + optional uint32 download_type = 9; + optional uint64 staging_bytes_staged = 10; + optional uint64 staging_bytes_to_stage = 11; + optional uint32 bytes_to_disc_per_second = 12; + repeated .AppStageProgress progress_weights = 13; + optional uint32 time_deferred_until = 14; + optional uint32 source_build_id = 15; + optional uint32 target_build_id = 16; +} + +message AppCloudStatus { + optional uint32 status = 1; + optional uint32 sync_state = 2; + optional double transfer_percentage = 3; +} + +message CMsgRemoteClientAppStatus { + message AppStatus { + optional uint32 app_id = 1; + optional uint32 app_install_state = 2; + optional .AppUpdateInfo update_info = 3; + optional .CMsgRemoteClientAppStatus.ShortcutInfo shortcut_info = 4; + optional bool vr_not_required = 5 [default = true]; + optional bool shader_update_available = 6; + optional bool workshop_update_avilable = 7; + optional bool download_complete = 8; + optional .AppCloudStatus cloud_status = 9; + } + + message ShortcutInfo { + optional string name = 1; + optional string icon = 2; + repeated string categories = 3; + optional string exepath = 4; + } + + repeated .CMsgRemoteClientAppStatus.AppStatus status_updates = 1; +} + +message CMsgRemoteClientDownloadsManagement { + message ChangeAppQueuePlacement { + optional uint32 app_id = 1; + optional uint32 queue_placement = 2; + } + + message ChangeDownloadIndex { + optional uint32 app_id = 1; + optional uint32 download_index = 3; + } + + optional .CMsgRemoteClientDownloadsManagement.ChangeAppQueuePlacement change_queue_placement = 1; + optional .CMsgRemoteClientDownloadsManagement.ChangeDownloadIndex change_download_index = 2; + optional bool enable_all_downloads = 3; + optional uint32 remove_from_download_list_app_id = 4; + optional bool suspend_download_throttling = 5; + optional uint32 uninstalling_app_id = 6; + optional uint32 installing_app_id = 7; +} + +message CMsgRemoteClientUpdateDownloadsController { + optional bool update_download_items = 1; + optional bool update_download_overview = 2; +} + +message CMsgRemoteClientPeerContentServerChanged { + optional uint32 app_id = 1; + optional uint32 num_connections = 2; + optional uint64 remote_client_id = 3; +} + +message CMsgRemoteClientDownloadingAppChanged { + optional uint32 downloading_app_id = 1; +} + +message CMsgRemoteClientSuspendLanPeerContent { + optional bool suspend = 1; +} + +message CMsgRemoteClientDownloadScheduleChanged { + optional bool download_enabled = 1; + optional uint32 start_index = 2; + optional bool final_message = 3; + optional uint32 num_apps_scheduled = 4; + repeated uint32 apps_scheduled = 5; +} + +message CMsgRemoteClientDownloadScheduleItemChanged { + optional uint32 app_id = 2; +} + +message CMsgRemoteClientAppUpdateStopped { + optional uint32 app_id = 1; + optional .AppUpdateInfo update_info = 2; + optional string error_detail = 3; + optional int32 install_folder_index = 4; + optional uint32 app_install_state = 5; +} + +message CMsgRemoteClientAppUpdateInfoComplete { + optional uint32 result = 1; +} + +message CMsgRemoteClientDownloadingAppID { + optional uint32 downloading_app_id = 1; + optional .AppUpdateInfo update_info = 2; +} + +message CMsgRemoteClientInstallApp { + optional uint32 app_id = 1; +} + +message CMsgRemoteClientInstallAppResponse { + optional int32 e_launch_result = 1 [default = 2]; +} + +message CMsgRemoteClientStartStream { + message ReservedGamepad { + optional uint32 controller_type = 1; + optional uint32 controller_subtype = 2; + } + + optional uint32 app_id = 1; + optional int32 environment = 2; + optional int32 gamepad_count = 3; + optional int32 launch_option = 4 [default = -1]; + optional bool lock_parental_lock = 5 [default = false]; + optional string unlock_parental_lock = 6; + optional int32 maximum_resolution_x = 7; + optional int32 maximum_resolution_y = 8; + repeated .CMsgRemoteClientStartStream.ReservedGamepad gamepads = 9; + optional int32 audio_channel_count = 10 [default = 2]; + repeated .EStreamTransport supported_transport = 11; + optional int32 maximum_framerate_numerator = 12; + optional int32 maximum_framerate_denominator = 13; + optional bool display_hdr = 14; + optional bool launch_only = 15 [default = false]; + optional int32 gaming_device_type = 16; + optional int32 cloud_conflict_resolution = 17 [default = -1]; + optional int32 controller_config_conflict_resolution = 18 [default = -1]; +} + +message CMsgRemoteClientStartStreamResponse { + message CloudConflict { + optional uint32 appid = 1; + optional uint32 local_time = 2; + optional uint32 remote_time = 3; + } + + optional int32 e_launch_result = 1 [default = 2]; + optional uint32 stream_port = 2; + repeated int32 launch_options = 3; + optional bytes auth_token = 4; + optional .EStreamTransport transport = 5 [default = k_EStreamTransportUDP]; + optional string relay_server = 6; + optional string launch_task = 7; + optional string launch_task_detail = 8; + optional int32 launch_tasks_done = 9; + optional int32 launch_tasks_total = 10; + optional string vr_connection_params = 11; + optional bool launch_only = 12 [default = false]; + optional .CMsgRemoteClientStartStreamResponse.CloudConflict cloud_conflict = 13; +} + +message CMsgRemoteClientPing { +} + +message CMsgRemoteClientPingResponse { +} + +message CMsgRemoteClientAcceptEULA { + repeated uint32 app_id = 1; + repeated string eula_id = 2; + repeated uint32 eula_version = 3; +} + +message CMsgRemoteClientAcceptAllEULAs { + optional uint32 app_id = 1; +} + +message CMsgRemoteClientGetControllerConfig { + optional uint32 app_id = 1; + optional uint32 controller_index = 3; +} + +message CMsgRemoteClientGetControllerConfigResponse { + optional int32 eresult = 1 [default = 2]; + optional bytes config_vdf = 2; +} + +message CMsgRemoteClientStreamingEnabled { + required bool enabled = 1; +} + +message CMsgRemoteClientWifiAPStatus { + optional string ssid = 1; + optional string password = 2; + optional bool wpa2_deprecated = 3; + optional bool is_pairing_capable = 4; + optional fixed64 paired_network_hash = 5; +} + +message CMsgRemoteClientPairWifiAP { + optional string ssid = 1; + optional string password = 2; + optional bool supports_progress = 3; +} + +message CMsgRemoteClientPairWifiAPResponse { + optional int32 e_pair_result = 1 [default = 2]; + optional string ssid = 2; + optional string password = 3; + optional int32 steps_done = 4; + optional int32 steps_total = 5; + optional string step_name = 6; + optional uint32 estimated_seconds = 7; +} diff --git a/src/main/proto/in/dragonbra/javasteam/protobufs/steamclient/steammessages_remoteclient_discovery.proto b/src/main/proto/in/dragonbra/javasteam/protobufs/steamclient/steammessages_remoteclient_discovery.proto new file mode 100644 index 000000000..89438e23c --- /dev/null +++ b/src/main/proto/in/dragonbra/javasteam/protobufs/steamclient/steammessages_remoteclient_discovery.proto @@ -0,0 +1,271 @@ +option java_package = "in.dragonbra.javasteam.protobufs.steamclient"; + +option optimize_for = SPEED; +option java_generic_services = false; + +enum ERemoteClientBroadcastMsg { + k_ERemoteClientBroadcastMsgDiscovery = 0; + k_ERemoteClientBroadcastMsgStatus = 1; + k_ERemoteClientBroadcastMsgOffline = 2; + k_ERemoteDeviceAuthorizationRequest = 3; + k_ERemoteDeviceAuthorizationResponse = 4; + k_ERemoteDeviceStreamingRequest = 5; + k_ERemoteDeviceStreamingResponse = 6; + k_ERemoteDeviceProofRequest = 7; + k_ERemoteDeviceProofResponse = 8; + k_ERemoteDeviceAuthorizationCancelRequest = 9; + k_ERemoteDeviceStreamingCancelRequest = 10; + k_ERemoteClientBroadcastMsgClientIDDeconflict = 11; + k_ERemoteDeviceStreamTransportSignal = 12; + k_ERemoteDeviceStreamingProgress = 13; + k_ERemoteDeviceAuthorizationConfirmed = 14; + k_ERemoteClientBroadcastMsgPairingState = 15; + k_ERemoteClientBroadcastMsgPairingExclusivity = 16; +} + +enum ERemoteClientService { + k_ERemoteClientServiceNone = 0; + k_ERemoteClientServiceRemoteControl = 1; + k_ERemoteClientServiceGameStreaming = 2; + k_ERemoteClientServiceSiteLicense = 4; + k_ERemoteClientServiceContentCache = 8; + k_ERemoteClientServiceContentServer = 16; + k_ERemoteClientServiceManageDownloads = 32; + k_ERemoteClientServiceRemoteInstallWithoutPin = 64; +} + +enum EVRLinkCaps { + k_EVRLinkCapsUnknown = 0; + k_EVRLinkCapsAvailable = 1; + k_EVRLinkCapsUnimplemented = 2; + k_EVRLinkCapsMissingHardwareEncoding = 3; +} + +enum ERemoteDeviceAuthorizationResult { + k_ERemoteDeviceAuthorizationSuccess = 0; + k_ERemoteDeviceAuthorizationDenied = 1; + k_ERemoteDeviceAuthorizationNotLoggedIn = 2; + k_ERemoteDeviceAuthorizationOffline = 3; + k_ERemoteDeviceAuthorizationBusy = 4; + k_ERemoteDeviceAuthorizationInProgress = 5; + k_ERemoteDeviceAuthorizationTimedOut = 6; + k_ERemoteDeviceAuthorizationFailed = 7; + k_ERemoteDeviceAuthorizationCanceled = 8; +} + +enum EStreamDeviceFormFactor { + k_EStreamDeviceFormFactorUnknown = 0; + k_EStreamDeviceFormFactorPhone = 1; + k_EStreamDeviceFormFactorTablet = 2; + k_EStreamDeviceFormFactorComputer = 3; + k_EStreamDeviceFormFactorTV = 4; + k_EStreamDeviceFormFactorVRHeadset = 5; +} + +enum EStreamTransport { + k_EStreamTransportNone = 0; + k_EStreamTransportUDP = 1; + k_EStreamTransportUDPRelay_OBSOLETE = 2; + k_EStreamTransportWebRTC_OBSOLETE = 3; + k_EStreamTransportSDR = 4; + k_EStreamTransportUDP_SNS = 5; + k_EStreamTransportUDPRelay_SNS_OBSOLETE = 6; +} + +enum EStreamInterface { + k_EStreamInterfaceDefault = 0; + k_EStreamInterfaceRecentGames = 1; + k_EStreamInterfaceBigPicture = 2; + k_EStreamInterfaceDesktop = 3; + k_EStreamInterfaceSteamVR = 4; +} + +enum ERemoteDeviceStreamingResult { + k_ERemoteDeviceStreamingSuccess = 0; + k_ERemoteDeviceStreamingUnauthorized = 1; + k_ERemoteDeviceStreamingScreenLocked = 2; + k_ERemoteDeviceStreamingFailed = 3; + k_ERemoteDeviceStreamingBusy = 4; + k_ERemoteDeviceStreamingInProgress = 5; + k_ERemoteDeviceStreamingCanceled = 6; + k_ERemoteDeviceStreamingDriversNotInstalled = 7; + k_ERemoteDeviceStreamingDisabled = 8; + k_ERemoteDeviceStreamingBroadcastingActive = 9; + k_ERemoteDeviceStreamingVRActive = 10; + k_ERemoteDeviceStreamingPINRequired = 11; + k_ERemoteDeviceStreamingTransportUnavailable = 12; + k_ERemoteDeviceStreamingInvisible = 13; + k_ERemoteDeviceStreamingGameLaunchFailed = 14; + k_ERemoteDeviceStreamingSteamVRNotInstalled = 15; +} + +message CMsgRemoteClientBroadcastHeader { + optional uint64 client_id = 1; + optional .ERemoteClientBroadcastMsg msg_type = 2 [default = k_ERemoteClientBroadcastMsgDiscovery]; + optional uint64 instance_id = 3; + optional uint64 device_id_OBSOLETE = 4; + optional bytes device_token = 5; +} + +message CMsgRemoteClientBroadcastStatus { + message User { + optional fixed64 steamid = 1; + optional uint32 auth_key_id = 2; + } + + optional int32 version = 1; + optional int32 min_version = 2; + optional uint32 connect_port = 3; + optional string hostname = 4; + optional uint32 enabled_services = 6; + optional int32 ostype = 7 [default = 0]; + optional bool is64bit = 8; + repeated .CMsgRemoteClientBroadcastStatus.User users = 9; + optional int32 euniverse = 11; + optional uint32 timestamp = 12; + optional bool screen_locked = 13; + optional bool games_running = 14; + repeated string mac_addresses = 15; + optional uint32 download_lan_peer_group = 16; + optional bool broadcasting_active = 17; + optional bool vr_active = 18; + optional uint32 content_cache_port = 19; + repeated string ip_addresses = 20; + optional string public_ip_address = 21; + optional bool remoteplay_active = 22; + optional uint32 supported_services = 23; + optional bool steam_deck = 24; + optional uint64 steam_version = 25; + optional .EVRLinkCaps vr_link_caps = 26 [default = k_EVRLinkCapsUnknown]; + optional fixed64 vr_link_invite_client_id = 27; + optional fixed64 connected_paired_network_hash = 28; + optional fixed64 connecting_paired_network_hash = 32; + optional bool wifi_dongle_present = 29; + optional bool is_low_spec_hardware = 30; + optional uint32 gaming_device_type = 31; +} + +message CMsgRemoteClientBroadcastDiscovery { + optional uint32 seq_num = 1; + repeated uint64 client_ids = 2; +} + +message CMsgRemoteClientBroadcastClientIDDeconflict { + repeated uint64 client_ids = 2; +} + +message CMsgRemoteDeviceAuthorizationRequest { + message CKeyEscrow_Ticket { + optional bytes password = 1; + optional uint64 identifier = 2; + optional bytes payload = 3; + optional uint32 timestamp = 4; + optional .CMsgRemoteDeviceAuthorizationRequest.EKeyEscrowUsage usage = 5 [default = k_EKeyEscrowUsageStreamingDevice]; + optional string device_name = 6; + optional string device_model = 7; + optional string device_serial = 8; + optional uint32 device_provisioning_id = 9; + } + + enum EKeyEscrowUsage { + k_EKeyEscrowUsageStreamingDevice = 0; + } + + required bytes device_token = 1; + optional string device_name = 2; + required bytes encrypted_request = 3; + optional bytes auth_key = 4; + optional uint32 request_id = 5; +} + +message CMsgRemoteDeviceAuthorizationCancelRequest { +} + +message CMsgRemoteDeviceAuthorizationResponse { + required .ERemoteDeviceAuthorizationResult result = 1 [default = k_ERemoteDeviceAuthorizationSuccess]; + optional fixed64 steamid = 2; + optional bytes auth_key = 3; + optional bytes device_token = 4; +} + +message CMsgRemoteDeviceAuthorizationConfirmed { + required .ERemoteDeviceAuthorizationResult result = 1 [default = k_ERemoteDeviceAuthorizationSuccess]; +} + +message CMsgRemoteClientBroadcastClientPairingState { + optional fixed64 my_paired_network_hash = 1; + optional uint32 my_pairing_time = 2; +} + +message CMsgRemoteClientBroadcastClientPairingExclusivity { + optional fixed64 if_paired_network_hash_is = 1; + optional fixed64 unpair_unless_you_are_client_id = 2; + optional uint32 last_known_pairing_time = 3; +} + +message CMsgRemoteDeviceStreamingRequest { + message ReservedGamepad { + optional uint32 controller_type = 1; + optional uint32 controller_subtype = 2; + } + + required uint32 request_id = 1; + optional int32 maximum_resolution_x = 2; + optional int32 maximum_resolution_y = 3; + optional int32 audio_channel_count = 4 [default = 2]; + optional string device_version = 5; + optional bool stream_desktop = 6; + optional bytes device_token = 7; + optional bytes pin = 8; + optional bool enable_video_streaming = 9 [default = true]; + optional bool enable_audio_streaming = 10 [default = true]; + optional bool enable_input_streaming = 11 [default = true]; + optional bool network_test = 12; + optional uint64 client_id = 13; + repeated .EStreamTransport supported_transport = 14; + optional bool restricted = 15; + optional .EStreamDeviceFormFactor form_factor = 16 [default = k_EStreamDeviceFormFactorUnknown]; + optional int32 gamepad_count = 17; + repeated .CMsgRemoteDeviceStreamingRequest.ReservedGamepad gamepads = 18; + optional uint64 gameid = 19; + optional .EStreamInterface stream_interface = 20 [default = k_EStreamInterfaceDefault]; + optional int32 maximum_framerate_numerator = 21; + optional int32 maximum_framerate_denominator = 22; + optional bool display_hdr = 23; +} + +message CMsgRemoteDeviceStreamingCancelRequest { + required uint32 request_id = 1; +} + +message CMsgRemoteDeviceStreamingProgress { + required uint32 request_id = 1; + optional float progress = 2; +} + +message CMsgRemoteDeviceStreamingResponse { + required uint32 request_id = 1; + required .ERemoteDeviceStreamingResult result = 2 [default = k_ERemoteDeviceStreamingSuccess]; + optional uint32 port = 3; + optional bytes encrypted_session_key = 4; + optional .EStreamTransport transport = 6 [default = k_EStreamTransportUDP]; + optional string relay_server = 7; + optional string cert = 8; +} + +message CMsgRemoteDeviceProofRequest { + required bytes challenge = 1; + optional uint32 request_id = 2; + optional bool update_secret = 3; +} + +message CMsgRemoteDeviceProofResponse { + required bytes response = 1; + optional uint32 request_id = 2; + optional bool updated_secret = 3; +} + +message CMsgRemoteDeviceStreamTransportSignal { + optional bytes token = 1; + optional bytes payload = 2; +} diff --git a/src/main/proto/in/dragonbra/javasteam/protobufs/steamclient/steammessages_remoteplay.proto b/src/main/proto/in/dragonbra/javasteam/protobufs/steamclient/steammessages_remoteplay.proto new file mode 100644 index 000000000..a5f1c5dad --- /dev/null +++ b/src/main/proto/in/dragonbra/javasteam/protobufs/steamclient/steammessages_remoteplay.proto @@ -0,0 +1,1040 @@ +option java_package = "in.dragonbra.javasteam.protobufs.steamclient"; + +option optimize_for = SPEED; +option java_generic_services = false; + +enum EStreamChannel { + k_EStreamChannelInvalid = -1; + k_EStreamChannelDiscovery = 0; + k_EStreamChannelControl = 1; + k_EStreamChannelStats = 2; + k_EStreamChannelDataChannelStart = 3; +} + +enum EStreamDiscoveryMessage { + k_EStreamDiscoveryPingRequest = 1; + k_EStreamDiscoveryPingResponse = 2; +} + +enum EStreamControlMessage { + k_EStreamControlAuthenticationRequest = 1; + k_EStreamControlAuthenticationResponse = 2; + k_EStreamControlNegotiationInit = 3; + k_EStreamControlNegotiationSetConfig = 4; + k_EStreamControlNegotiationComplete = 5; + k_EStreamControlClientHandshake = 6; + k_EStreamControlServerHandshake = 7; + k_EStreamControlStartNetworkTest = 8; + k_EStreamControlKeepAlive = 9; + k_EStreamControl_LAST_SETUP_MESSAGE = 15; + k_EStreamControlStartAudioData = 50; + k_EStreamControlStopAudioData = 51; + k_EStreamControlStartVideoData = 52; + k_EStreamControlStopVideoData = 53; + k_EStreamControlInputMouseMotion = 54; + k_EStreamControlInputMouseWheel = 55; + k_EStreamControlInputMouseDown = 56; + k_EStreamControlInputMouseUp = 57; + k_EStreamControlInputKeyDown = 58; + k_EStreamControlInputKeyUp = 59; + k_EStreamControlInputGamepadAttached_OBSOLETE = 60; + k_EStreamControlInputGamepadEvent_OBSOLETE = 61; + k_EStreamControlInputGamepadDetached_OBSOLETE = 62; + k_EStreamControlShowCursor = 63; + k_EStreamControlHideCursor = 64; + k_EStreamControlSetCursor = 65; + k_EStreamControlGetCursorImage = 66; + k_EStreamControlSetCursorImage = 67; + k_EStreamControlDeleteCursor = 68; + k_EStreamControlSetTargetFramerate = 69; + k_EStreamControlInputLatencyTest_OBSOLETE = 70; + k_EStreamControlGamepadRumble_OBSOLETE = 71; + k_EStreamControlOverlayEnabled = 74; + k_EStreamControlInputControllerAttached_OBSOLETE = 75; + k_EStreamControlInputControllerState_OBSOLETE = 76; + k_EStreamControlTriggerHapticPulse_OBSOLETE = 77; + k_EStreamControlInputControllerDetached_OBSOLETE = 78; + k_EStreamControlVideoDecoderInfo = 80; + k_EStreamControlSetTitle = 81; + k_EStreamControlSetIcon = 82; + k_EStreamControlQuitRequest = 83; + k_EStreamControlSetQoS = 87; + k_EStreamControlInputControllerWirelessPresence_OBSOLETE = 88; + k_EStreamControlSetGammaRamp = 89; + k_EStreamControlVideoEncoderInfo = 90; + k_EStreamControlInputControllerStateHID_OBSOLETE = 93; + k_EStreamControlSetTargetBitrate = 94; + k_EStreamControlSetControllerPairingEnabled_OBSOLETE = 95; + k_EStreamControlSetControllerPairingResult_OBSOLETE = 96; + k_EStreamControlTriggerControllerDisconnect_OBSOLETE = 97; + k_EStreamControlSetActivity = 98; + k_EStreamControlSetStreamingClientConfig = 99; + k_EStreamControlSystemSuspend = 100; + k_EStreamControlSetControllerSettings_OBSOLETE = 101; + k_EStreamControlVirtualHereRequest = 102; + k_EStreamControlVirtualHereReady = 103; + k_EStreamControlVirtualHereShareDevice = 104; + k_EStreamControlSetSpectatorMode = 105; + k_EStreamControlRemoteHID = 106; + k_EStreamControlStartMicrophoneData = 107; + k_EStreamControlStopMicrophoneData = 108; + k_EStreamControlInputText = 109; + k_EStreamControlTouchConfigActive = 110; + k_EStreamControlGetTouchConfigData = 111; + k_EStreamControlSetTouchConfigData = 112; + k_EStreamControlSaveTouchConfigLayout = 113; + k_EStreamControlTouchActionSetActive = 114; + k_EStreamControlGetTouchIconData = 115; + k_EStreamControlSetTouchIconData = 116; + k_EStreamControlInputTouchFingerDown = 117; + k_EStreamControlInputTouchFingerMotion = 118; + k_EStreamControlInputTouchFingerUp = 119; + k_EStreamControlSetCaptureSize = 120; + k_EStreamControlSetFlashState = 121; + k_EStreamControlPause = 122; + k_EStreamControlResume = 123; + k_EStreamControlEnableHighResCapture = 124; + k_EStreamControlDisableHighResCapture = 125; + k_EStreamControlToggleMagnification = 126; + k_EStreamControlSetCapslock = 127; + k_EStreamControlSetKeymap = 128; + k_EStreamControlStopRequest = 129; + k_EStreamControlTouchActionSetLayerAdded = 130; + k_EStreamControlTouchActionSetLayerRemoved = 131; + k_EStreamControlRemotePlayTogetherGroupUpdate = 132; + k_EStreamControlSetInputTemporarilyDisabled = 133; + k_EStreamControlSetQualityOverride = 134; + k_EStreamControlSetBitrateOverride = 135; + k_EStreamControlShowOnScreenKeyboard = 136; + k_EStreamControlControllerConfigMsg = 137; + k_EStreamControlControllerPersonalizationUpdate = 138; + k_EStreamControlEnableNeptuneData_OBSOLETE = 139; + k_EStreamControlDisableNeptuneData_OBSOLETE = 140; + k_EStreamControlStartNeptuneData_OBSOLETE = 141; + k_EStreamControlStopNeptuneData_OBSOLETE = 142; + k_EStreamControlPauseControllerInput = 143; + k_EStreamControlResumeControllerInput = 144; + k_EStreamControlVRConnectionReady = 145; + k_EStreamControlSetCursorScale = 146; + k_EStreamControlCaptureFailed = 147; + k_EStreamControlVideoOverflow = 148; + k_EStreamControlSetSupportedColorspaces = 149; +} + +enum EStreamVersion { + k_EStreamVersionNone = 0; + k_EStreamVersionCurrent = 1; +} + +enum EStreamAudioCodec { + k_EStreamAudioCodecNone = 0; + k_EStreamAudioCodecRaw = 1; + k_EStreamAudioCodecVorbis = 2; + k_EStreamAudioCodecOpus = 3; + k_EStreamAudioCodecMP3 = 4; + k_EStreamAudioCodecAAC = 5; +} + +enum EStreamVideoCodec { + k_EStreamVideoCodecNone = 0; + k_EStreamVideoCodecRaw = 1; + k_EStreamVideoCodecH264 = 4; + k_EStreamVideoCodecHEVC = 5; + k_EStreamVideoCodecAV1 = 8; + k_EStreamVideoCodecPyrowave = 9; +} + +enum EStreamQualityPreference { + k_EStreamQualityAutomatic = -1; + k_EStreamQualityFast = 1; + k_EStreamQualityBalanced = 2; + k_EStreamQualityBeautiful = 3; +} + +enum EStreamBitrate { + k_EStreamBitrateAutomatic = -1; + k_EStreamBitrateUnlimited = 0; +} + +enum EStreamColorspace { + k_EStreamColorspace_Unknown = 0; + k_EStreamColorspace_BT601 = 1; + k_EStreamColorspace_BT601_Full = 2; + k_EStreamColorspace_BT709 = 3; + k_EStreamColorspace_BT709_Full = 4; + k_EStreamColorspace_HDR10 = 5; +} + +enum EStreamP2PScope { + k_EStreamP2PScopeAutomatic = 0; + k_EStreamP2PScopeDisabled = 1; + k_EStreamP2PScopeOnlyMe = 2; + k_EStreamP2PScopeFriends = 3; + k_EStreamP2PScopeEveryone = 4; +} + +enum EDisplayStyle { + k_EDisplayStyleLetterbox = 0; + k_EDisplayStyleStretch = 1; + k_EDisplayStyleZoom = 2; +} + +enum EStreamHDRMode { + k_EStreamHDRModeAuto = 0; + k_EStreamHDRModeOn = 1; + k_EStreamHDRModeOff = 2; +} + +enum EStreamHostPlayAudioPreference { + k_EStreamHostPlayAudioDefault = 0; + k_EStreamHostPlayAudioAlways = 1; +} + +enum EStreamHostDisplaySetting { + k_EStreamHostDisplaySettingNone = 0; + k_EStreamHostDisplaySettingClient = 1; + k_EStreamHostDisplaySettingCustom = 2; +} + +enum EStreamingDataType { + k_EStreamingAudioData = 0; + k_EStreamingVideoData = 1; + k_EStreamingMicrophoneData = 2; + k_EStreamingNeptuneData_OBSOLETE = 3; +} + +enum EStreamMouseButton { + k_EStreamMouseButtonLeft = 1; + k_EStreamMouseButtonRight = 2; + k_EStreamMouseButtonMiddle = 16; + k_EStreamMouseButtonX1 = 32; + k_EStreamMouseButtonX2 = 64; + k_EStreamMouseButtonUnknown = 4096; +} + +enum EStreamMouseWheelDirection { + k_EStreamMouseWheelUp = 120; + k_EStreamMouseWheelDown = -120; + k_EStreamMouseWheelLeft = 3; + k_EStreamMouseWheelRight = 4; +} + +enum EStreamFramerateLimiter { + k_EStreamFramerateSlowCapture = 1; + k_EStreamFramerateSlowConvert = 2; + k_EStreamFramerateSlowEncode = 4; + k_EStreamFramerateSlowNetwork = 8; + k_EStreamFramerateSlowDecode = 16; + k_EStreamFramerateSlowGame = 32; + k_EStreamFramerateSlowDisplay = 64; +} + +enum EStreamActivity { + k_EStreamActivityIdle = 1; + k_EStreamActivityGame = 2; + k_EStreamActivityDesktop = 3; + k_EStreamActivitySecureDesktop = 4; + k_EStreamActivityMusic = 5; +} + +enum ECaptureFailedReason { + k_ECaptureFailedReasonNone = 0; + k_ECaptureFailedReasonUnknown = 1; + k_ECaptureFailedReasonPipewireRequired = 2; + k_ECaptureFailedReasonPipewirePermissions = 3; + k_ECaptureFailedReasonMacOSPermissions = 4; +} + +enum EStreamDataMessage { + k_EStreamDataPacket = 1; + k_EStreamDataLost = 2; +} + +enum EAudioFormat { + k_EAudioFormatNone = 0; + k_EAudioFormat16BitLittleEndian = 1; + k_EAudioFormatFloat = 2; +} + +enum EStreamStatsMessage { + k_EStreamStatsFrameEvents = 1; + k_EStreamStatsDebugDump = 2; + k_EStreamStatsLogMessage = 3; + k_EStreamStatsLogUploadBegin = 4; + k_EStreamStatsLogUploadData = 5; + k_EStreamStatsLogUploadComplete = 6; +} + +enum EStreamFrameEvent { + k_EStreamInputEventStart = 0; + k_EStreamInputEventSend = 1; + k_EStreamInputEventRecv = 2; + k_EStreamInputEventQueued = 3; + k_EStreamInputEventHandled = 4; + k_EStreamFrameEventStart = 5; + k_EStreamFrameEventCaptureBegin = 6; + k_EStreamFrameEventCaptureEnd = 7; + k_EStreamFrameEventConvertBegin = 8; + k_EStreamFrameEventConvertEnd = 9; + k_EStreamFrameEventEncodeBegin = 10; + k_EStreamFrameEventEncodeEnd = 11; + k_EStreamFrameEventSend = 12; + k_EStreamFrameEventRecv = 13; + k_EStreamFrameEventDecodeBegin = 14; + k_EStreamFrameEventDecodeEnd = 15; + k_EStreamFrameEventUploadBegin = 16; + k_EStreamFrameEventUploadEnd = 17; + k_EStreamFrameEventComplete = 18; +} + +enum EStreamFrameResult { + k_EStreamFrameResultPending = 0; + k_EStreamFrameResultDisplayed = 1; + k_EStreamFrameResultDroppedNetworkSlow = 2; + k_EStreamFrameResultDroppedNetworkLost = 3; + k_EStreamFrameResultDroppedDecodeSlow = 4; + k_EStreamFrameResultDroppedDecodeCorrupt = 5; + k_EStreamFrameResultDroppedLate = 6; + k_EStreamFrameResultDroppedReset = 7; +} + +enum EFrameAccumulatedStat { + k_EFrameStatFPS = 0; + k_EFrameStatCaptureDurationMS = 1; + k_EFrameStatConvertDurationMS = 2; + k_EFrameStatEncodeDurationMS = 3; + k_EFrameStatSteamDurationMS = 4; + k_EFrameStatServerDurationMS = 5; + k_EFrameStatNetworkDurationMS = 6; + k_EFrameStatDecodeDurationMS = 7; + k_EFrameStatDisplayDurationMS = 8; + k_EFrameStatClientDurationMS = 9; + k_EFrameStatFrameDurationMS = 10; + k_EFrameStatInputLatencyMS = 11; + k_EFrameStatGameLatencyMS = 12; + k_EFrameStatRoundTripLatencyMS = 13; + k_EFrameStatPingTimeMS = 14; + k_EFrameStatServerBitrateKbitPerSec = 15; + k_EFrameStatClientBitrateKbitPerSec = 16; + k_EFrameStatLinkBandwidthKbitPerSec = 17; + k_EFrameStatPacketLossPercentage = 18; +} + +enum ELogFileType { + k_ELogFileSystemBoot = 0; + k_ELogFileSystemReset = 1; + k_ELogFileSystemDebug = 2; +} + +enum EStreamControllerConfigMsg { + k_EStreamControllerConfigMsg_RequestConfigsForApp = 0; + k_EStreamControllerConfigMsg_ConfigResponse = 1; + k_EStreamControllerConfigMsg_PersonalizationResponse = 2; + k_EStreamControllerConfigMsg_ActiveConfigChange = 3; + k_EStreamControllerConfigMsg_RequestActiveConfig = 4; +} + +message CDiscoveryPingRequest { + optional uint32 sequence = 1; + optional uint32 packet_size_requested = 2; +} + +message CDiscoveryPingResponse { + optional uint32 sequence = 1; + optional uint32 packet_size_received = 2; +} + +message CStreamingClientHandshakeInfo { + optional int32 network_test = 2; +} + +message CClientHandshakeMsg { + required .CStreamingClientHandshakeInfo info = 1; +} + +message CStreamingServerHandshakeInfo { + optional int32 mtu = 1; +} + +message CServerHandshakeMsg { + required .CStreamingServerHandshakeInfo info = 1; +} + +message CAuthenticationRequestMsg { + optional bytes token = 1; + optional .EStreamVersion version = 2 [default = k_EStreamVersionNone]; + optional uint64 steamid = 3; +} + +message CAuthenticationResponseMsg { + enum AuthenticationResult { + SUCCEEDED = 0; + FAILED = 1; + } + + optional .CAuthenticationResponseMsg.AuthenticationResult result = 1 [default = SUCCEEDED]; + optional .EStreamVersion version = 2 [default = k_EStreamVersionNone]; +} + +message CKeepAliveMsg { +} + +message CStartNetworkTestMsg { + optional uint32 frames = 1; + optional uint32 framerate = 2; + optional uint32 bitrate_kbps = 3; + optional uint32 burst_bitrate_kbps = 4; + optional bool bandwidth_test = 5; +} + +message CStreamVideoMode { + required uint32 width = 1; + required uint32 height = 2; + optional uint32 refresh_rate = 3; + optional uint32 refresh_rate_numerator = 4; + optional uint32 refresh_rate_denominator = 5; +} + +message CStreamVideoLimit { + optional .EStreamVideoCodec codec = 1 [default = k_EStreamVideoCodecNone]; + optional .CStreamVideoMode mode = 2; + optional int32 bitrate_kbps = 3; + optional int32 burst_bitrate_kbps = 4; +} + +message CStreamingClientCaps { + optional string system_info = 1; + optional bool system_can_suspend = 2; + optional int32 maximum_decode_bitrate_kbps = 3; + optional int32 maximum_burst_bitrate_kbps = 4; + optional bool supports_video_hevc_OBSOLETE = 5; + optional bool disable_steam_store = 6; + optional bool disable_client_cursor = 7; + optional bool disable_intel_hardware_encoding = 8; + optional bool disable_amd_hardware_encoding = 9; + optional bool disable_nvidia_hardware_encoding = 10; + optional int32 form_factor = 11; + optional bool has_on_screen_keyboard = 12; + repeated .EStreamColorspace supported_colorspaces = 13; + repeated .EStreamAudioCodec supported_audio_codecs = 14; + repeated .EStreamVideoCodec supported_video_codecs = 15; + optional bool can_toggle_fullscreen = 16; + optional bool supports_video_frame_header = 17; +} + +message CStreamingClientConfig { + optional .EStreamQualityPreference quality = 1 [default = k_EStreamQualityBalanced]; + optional uint32 desired_resolution_x = 2; + optional uint32 desired_resolution_y = 3; + optional uint32 desired_framerate_numerator = 4; + optional uint32 desired_framerate_denominator = 5; + optional int32 desired_bitrate_kbps = 6 [default = -1]; + optional bool enable_hardware_decoding = 7 [default = true]; + optional bool enable_performance_overlay = 8 [default = false]; + optional bool enable_video_streaming = 9 [default = true]; + optional bool enable_audio_streaming = 10 [default = true]; + optional bool enable_input_streaming = 11 [default = true]; + optional int32 audio_channels = 12 [default = 2]; + optional bool enable_video_hevc = 13 [default = false]; + optional bool enable_performance_icons = 14 [default = true]; + optional bool enable_microphone_streaming = 15 [default = false]; + optional string controller_overlay_hotkey = 16; + optional bool enable_touch_controller_OBSOLETE = 17 [default = false]; + optional .EStreamP2PScope p2p_scope = 19 [default = k_EStreamP2PScopeAutomatic]; + optional bool enable_audio_uncompressed = 20 [default = false]; + optional .CStreamVideoLimit display_limit = 21; + optional .CStreamVideoLimit quality_limit = 22; + optional .CStreamVideoLimit runtime_limit = 23; + repeated .CStreamVideoLimit decoder_limit = 24; + optional bool enable_unreliable_fec = 25 [default = false]; + optional bool enable_video_av1 = 26 [default = false]; + optional bool windowed = 27; + optional float window_pixel_density = 28; + optional int32 window_width = 29; + optional int32 window_height = 30; + optional int32 window_position_x = 31; + optional int32 window_position_y = 32; + optional int32 window_frame_offset_x = 33; + optional int32 window_frame_offset_y = 34; + optional bool enable_video_pyrowave = 35 [default = false]; + optional bool pyrowave_custom_bitrate_OBSOLETE = 36; + optional int32 pyrowave_custom_bitrate_kbps_OBSOLETE = 37; + optional float pyrowave_quality_modifier = 38; + optional bool pyrowave_yuv444 = 39; + optional int32 pyrowave_bitrate_kbps = 40 [default = -1]; + optional .EDisplayStyle display_style = 41 [default = k_EDisplayStyleLetterbox]; + optional .EStreamHDRMode hdr_mode = 42 [default = k_EStreamHDRModeAuto]; +} + +message CStreamingServerConfig { + optional .EStreamHostPlayAudioPreference host_play_audio = 1 [default = k_EStreamHostPlayAudioDefault]; + optional string custom_display_device = 2; + optional .EStreamHostDisplaySetting display_resolution_setting = 3 [default = k_EStreamHostDisplaySettingNone]; + optional int32 custom_display_resolution_x = 4; + optional int32 custom_display_resolution_y = 5; + optional .EStreamHostDisplaySetting display_refresh_rate_setting = 6 [default = k_EStreamHostDisplaySettingNone]; + optional string custom_display_refresh_rate = 7; + optional .EStreamHostDisplaySetting display_hdr_setting = 8 [default = k_EStreamHostDisplaySettingNone]; + optional bool custom_display_hdr = 9; + optional bool enable_capture_nvfbc = 10; + optional bool enable_hardware_encoding = 11; + optional int32 software_encoding_threads = 12; + optional bool enable_traffic_priority = 13; +} + +message CNegotiatedConfig { + optional bool reliable_data = 1; + optional .EStreamAudioCodec selected_audio_codec = 2 [default = k_EStreamAudioCodecNone]; + optional .EStreamVideoCodec selected_video_codec = 3 [default = k_EStreamVideoCodecNone]; + repeated .CStreamVideoMode available_video_modes_OBSOLETE = 4; + optional bool enable_remote_hid = 5; + optional bool enable_touch_input = 6; + optional bool disable_client_cursor = 7; +} + +message CNegotiationInitMsg { + optional bool reliable_data = 1; + repeated .EStreamAudioCodec supported_audio_codecs = 2; + repeated .EStreamVideoCodec supported_video_codecs = 3; + optional bool supports_remote_hid = 4; + optional bool supports_touch_input = 5; + optional int32 os_type = 6; + optional int32 gaming_device_type = 7; +} + +message CNegotiationSetConfigMsg { + required .CNegotiatedConfig config = 1; + optional .CStreamingClientConfig streaming_client_config = 2; + optional .CStreamingClientCaps streaming_client_caps = 3; +} + +message CNegotiationCompleteMsg { +} + +message CStartAudioDataMsg { + required uint32 channel = 2; + optional .EStreamAudioCodec codec = 3 [default = k_EStreamAudioCodecNone]; + optional bytes codec_data = 4; + optional uint32 frequency = 5; + optional uint32 channels = 6; +} + +message CStopAudioDataMsg { +} + +message CStartVideoDataMsg { + required uint32 channel = 1; + optional .EStreamVideoCodec codec = 2 [default = k_EStreamVideoCodecNone]; + optional bytes codec_data = 3; + optional uint32 width = 4; + optional uint32 height = 5; + optional .EStreamColorspace colorspace = 6 [default = k_EStreamColorspace_Unknown]; + optional bool video_frame_headers = 7; +} + +message CStopVideoDataMsg { +} + +message CRecordedInput { + optional .EStreamControlMessage type = 1 [default = k_EStreamControlAuthenticationRequest]; + optional uint32 timestamp = 2; + + oneof data { + .CInputTouchFingerDownMsg finger_down = 3; + .CInputTouchFingerMotionMsg finger_motion = 4; + .CInputTouchFingerUpMsg finger_up = 5; + .CInputMouseMotionMsg mouse_motion = 6; + .CInputMouseWheelMsg mouse_wheel = 7; + .CInputMouseDownMsg mouse_down = 8; + .CInputMouseUpMsg mouse_up = 9; + .CInputKeyDownMsg key_down = 10; + .CInputKeyUpMsg key_up = 11; + .CInputTextMsg text = 12; + .CRemoteHIDMsg hid = 13; + } +} + +message CRecordedInputStream { + repeated .CRecordedInput entries = 1; +} + +message CInputTouchFingerDownMsg { + optional uint32 input_mark = 1; + optional uint64 fingerid = 2; + optional float x_normalized = 3; + optional float y_normalized = 4; +} + +message CInputTouchFingerMotionMsg { + optional uint32 input_mark = 1; + optional uint64 fingerid = 2; + optional float x_normalized = 3; + optional float y_normalized = 4; +} + +message CInputTouchFingerUpMsg { + optional uint32 input_mark = 1; + optional uint64 fingerid = 2; + optional float x_normalized = 3; + optional float y_normalized = 4; + optional bool canceled = 5; +} + +message CInputMouseMotionMsg { + optional uint32 input_mark = 1; + optional float x_normalized = 2; + optional float y_normalized = 3; + optional int32 dx = 4; + optional int32 dy = 5; +} + +message CInputMouseWheelMsg { + optional uint32 input_mark = 1; + required .EStreamMouseWheelDirection direction = 2 [default = k_EStreamMouseWheelUp]; + optional float amount = 3 [default = 1]; +} + +message CInputMouseDownMsg { + optional uint32 input_mark = 1; + required .EStreamMouseButton button = 2 [default = k_EStreamMouseButtonLeft]; +} + +message CInputMouseUpMsg { + optional uint32 input_mark = 1; + required .EStreamMouseButton button = 2 [default = k_EStreamMouseButtonLeft]; +} + +message CInputKeyDownMsg { + optional uint32 input_mark = 1; + required uint32 scancode = 2; + optional uint32 modifiers = 3; + optional uint32 keycode = 4; +} + +message CInputKeyUpMsg { + optional uint32 input_mark = 1; + required uint32 scancode = 2; + optional uint32 modifiers = 3; + optional uint32 keycode = 4; +} + +message CInputTextMsg { + optional uint32 input_mark = 1; + required string text_utf8 = 2; +} + +message CSetTitleMsg { + optional string text = 1; +} + +message CSetCaptureSizeMsg { + optional int32 width = 1; + optional int32 height = 2; +} + +message CSetIconMsg { + optional int32 width = 1; + optional int32 height = 2; + optional bytes image = 3; +} + +message CSetFlashStateMsg { + optional uint32 flags = 1; + optional uint32 count = 2; + optional uint32 timeout_ms = 3; +} + +message CShowCursorMsg { + optional float x_normalized = 1; + optional float y_normalized = 2; + optional bool locked = 3; +} + +message CHideCursorMsg { +} + +message CSetCursorMsg { + required uint64 cursor_id = 1; +} + +message CGetCursorImageMsg { + required uint64 cursor_id = 1; +} + +message CSetCursorImageMsg { + required uint64 cursor_id = 1; + optional int32 width = 2; + optional int32 height = 3; + optional int32 hot_x = 4; + optional int32 hot_y = 5; + optional bytes image = 6; +} + +message CSetCursorScaleMsg { + optional float scale = 1; +} + +message CVideoDecoderInfoMsg { + optional string info = 1; + optional int32 threads = 2; +} + +message CVideoEncoderInfoMsg { + optional string info = 1; +} + +message CPauseMsg { +} + +message CResumeMsg { +} + +message CEnableHighResCaptureMsg { +} + +message CDisableHighResCaptureMsg { +} + +message CPauseControllerInputMsg { +} + +message CResumeControllerInputMsg { +} + +message CToggleMagnificationMsg { +} + +message CSetCapslockMsg { + optional bool pressed = 1; +} + +message CStreamingKeymapEntry { + optional int32 scancode = 1; + optional int32 normal_keycode = 2; + optional int32 shift_keycode = 3; + optional int32 capslock_keycode = 4; + optional int32 shift_capslock_keycode = 5; + optional int32 altgr_keycode = 6; + optional int32 altgr_shift_keycode = 7; + optional int32 altgr_capslock_keycode = 8; + optional int32 altgr_shift_capslock_keycode = 9; +} + +message CStreamingKeymap { + repeated .CStreamingKeymapEntry entries = 1; +} + +message CSetKeymapMsg { + optional .CStreamingKeymap keymap = 1; +} + +message CStopRequest { +} + +message CQuitRequest { +} + +message CDeleteCursorMsg { + required uint64 cursor_id = 1; +} + +message CSetStreamingClientConfig { + required .CStreamingClientConfig config = 1; +} + +message CSetQoSMsg { + required bool use_qos = 1; +} + +message CSetTargetFramerateMsg { + required uint32 framerate = 1; + optional uint32 reasons = 2; + optional uint32 framerate_numerator = 3; + optional uint32 framerate_denominator = 4; +} + +message CSetTargetBitrateMsg { + required int32 bitrate = 1; +} + +message COverlayEnabledMsg { + required bool enabled = 1; +} + +message CSetGammaRampMsg { + optional bytes gamma_ramp = 1; +} + +message CSetActivityMsg { + optional .EStreamActivity activity = 1 [default = k_EStreamActivityIdle]; + optional uint32 appid = 2; + optional uint64 gameid = 3; + optional string game_name = 4; +} + +message CSystemSuspendMsg { +} + +message CVirtualHereRequestMsg { + optional string hostname = 1; +} + +message CVirtualHereReadyMsg { + optional uint32 licensed_device_count = 1; +} + +message CVirtualHereShareDeviceMsg { + optional string device_address = 1; +} + +message CSetSpectatorModeMsg { + optional bool enabled = 1; +} + +message CRemoteHIDMsg { + optional bytes data = 1; + optional bool active_input = 2; +} + +message CTouchConfigActiveMsg { + optional uint32 appid = 1; + optional uint32 revision = 2; + optional uint64 creator = 3; +} + +message CGetTouchConfigDataMsg { + optional uint32 appid = 1; +} + +message CSetTouchConfigDataMsg { + optional uint32 appid = 1; + optional uint32 revision = 2; + optional bytes data = 3; + optional bytes layout = 4; + optional uint64 creator = 5; +} + +message CSaveTouchConfigLayoutMsg { + optional uint32 appid = 1; + optional bytes layout = 4; +} + +message CTouchActionSetActiveMsg { + optional uint32 appid = 1; + optional int32 actionset_id = 2; +} + +message CTouchActionSetLayerAddedMsg { + optional uint32 appid = 1; + optional int32 actionset_id = 2; +} + +message CTouchActionSetLayerRemovedMsg { + optional uint32 appid = 1; + optional int32 actionset_id = 2; +} + +message CGetTouchIconDataMsg { + optional uint32 appid = 1; + optional string icon = 2; +} + +message CSetTouchIconDataMsg { + optional uint32 appid = 1; + optional string icon = 2; + optional bytes data = 3; +} + +message CRemotePlayTogetherGroupUpdateMsg { + message Player { + optional uint32 accountid = 1; + optional uint32 guestid = 2; + optional bool keyboard_enabled = 3; + optional bool mouse_enabled = 4; + optional bool controller_enabled = 5; + repeated uint32 controller_slots = 6; + optional bytes avatar_hash = 7; + } + + repeated .CRemotePlayTogetherGroupUpdateMsg.Player players = 1; + optional int32 player_index = 2; + optional string miniprofile_location = 3; + optional string game_name = 4; + optional string avatar_location = 5; + optional bool direct_input = 6; +} + +message CSetInputTemporarilyDisabledMsg { + optional bool disabled = 1; +} + +message CSetQualityOverrideMsg { + optional int32 value = 1; +} + +message CSetBitrateOverrideMsg { + optional int32 value = 1; +} + +message CShowOnScreenKeyboardMsg { +} + +message CControllerPersonalizationUpdateMsg { + optional string controller_path = 1; + optional string controller_name = 2; + optional bool reverse_diamond_button_layout = 3; +} + +message CVRConnectionReady { + optional string connect_params = 1; +} + +message CCaptureFailedMsg { + optional .ECaptureFailedReason reason = 1 [default = k_ECaptureFailedReasonNone]; +} + +message CStreamVideoOverflowMsg { + optional uint32 first_frame_id = 1; + optional uint32 last_frame_id = 2; +} + +message CSetSupportedColorspacesMsg { + repeated .EStreamColorspace supported_colorspaces = 1; +} + +message CStreamDataLostMsg { + repeated uint32 packets = 1; +} + +message CAudioFormat { + required .EAudioFormat format = 1 [default = k_EAudioFormatNone]; + optional uint32 frequency = 2; + optional uint32 channels = 3; +} + +message CVideoFrameHeader { + optional uint32 frame_id = 1; + optional uint32 timestamp = 2; + optional .EStreamVideoCodec codec = 3 [default = k_EStreamVideoCodecNone]; + optional uint32 pixel_bits = 4; + optional bool yuv420 = 5; + optional bool yuv444 = 6; + optional .EStreamColorspace colorspace = 7 [default = k_EStreamColorspace_Unknown]; + optional uint32 min_luminance = 8; + optional uint32 max_luminance = 9; + optional uint32 sdr_luminance = 10; + optional uint32 width = 11; + optional uint32 height = 12; + optional bool cursor_captured = 13; +} + +message CFrameEvent { + required .EStreamFrameEvent event_id = 1 [default = k_EStreamInputEventStart]; + required uint32 timestamp = 2; +} + +message CFrameStats { + required uint32 frame_id = 1; + optional uint32 input_mark = 2; + repeated .CFrameEvent events = 3; + required .EStreamFrameResult result = 4 [default = k_EStreamFrameResultPending]; + optional float frame_start_delta = 5; + optional float frame_display_delta = 6; + optional float ping_time = 7; + optional float server_bitrate = 8; + optional float client_bitrate = 9; + optional float link_bandwidth = 10; + optional float packet_loss = 11; + optional uint32 frame_size = 12; +} + +message CFrameStatAccumulatedValue { + required .EFrameAccumulatedStat stat_type = 1 [default = k_EFrameStatFPS]; + required int32 count = 2; + required float average = 3; + optional float stddev = 4; +} + +message CFrameStatsListMsg { + required .EStreamingDataType data_type = 1 [default = k_EStreamingAudioData]; + repeated .CFrameStats stats = 2; + repeated .CFrameStatAccumulatedValue accumulated_stats = 3; + required int32 latest_frame_id = 4; +} + +message CStreamingSessionStats { + optional float frame_loss_percentage = 1; + optional float average_network_time_ms = 2; + optional float stddev_network_time_ms = 3; + optional string test_data = 4; +} + +message CDebugDumpMsg { + optional bytes screenshot = 1; +} + +message CLogMsg { + optional int32 type = 1; + optional string message = 2; +} + +message CLogUploadMsg { + optional .ELogFileType type = 1 [default = k_ELogFileSystemBoot]; + optional bytes data = 3; +} + +message CTransportSignalMsg { + message WebRTCMessage { + message Candidate { + optional string sdp_mid = 1; + optional int32 sdp_mline_index = 2; + optional string candidate = 3; + } + + oneof msg { + bool greeting = 1; + string offer = 2; + string answer = 3; + .CTransportSignalMsg.WebRTCMessage.Candidate candidate = 4; + } + } + + optional .CTransportSignalMsg.WebRTCMessage webrtc = 1; + repeated bytes sdr = 2; +} + +message CControllerConfigMsg { + message ControllerConfigResponse { + optional uint32 appid = 1; + optional string configURL = 2; + optional uint32 controllerType = 3; + optional string controllerData = 4; + optional uint32 selectionOrder = 5; + optional bool actionBlock = 6; + } + + message ControllerPersonalizationResponse { + optional string personalizationData = 1; + } + + message ControllerActiveConfigChangeResponse { + optional string configURL = 2; + optional uint32 controllerType = 3; + optional string controllerData = 4; + optional uint32 selectionOrder = 5; + } + + message ControllerActiveConfigMsg { + optional uint32 appid = 1; + optional string configURL = 2; + optional uint32 controllerType = 3; + optional string controllerData = 4; + } + + required .EStreamControllerConfigMsg type = 1 [default = k_EStreamControllerConfigMsg_RequestConfigsForApp]; + optional string controllerPath = 2; + optional uint32 appid = 3; + optional .CControllerConfigMsg.ControllerPersonalizationResponse personalizationResponse = 4; + repeated .CControllerConfigMsg.ControllerConfigResponse configResponse = 6; + optional .CControllerConfigMsg.ControllerActiveConfigMsg activeConfigChangeMsg = 7; +} diff --git a/src/test/java/in/dragonbra/javasteam/TestPackets.java b/src/test/java/in/dragonbra/javasteam/TestPackets.java index b2c6e9eb5..cdbe362bf 100644 --- a/src/test/java/in/dragonbra/javasteam/TestPackets.java +++ b/src/test/java/in/dragonbra/javasteam/TestPackets.java @@ -304,6 +304,7 @@ private static byte[] clientPersonaChangeResponse() { private static byte[] clientPlayerNicknameList() { ClientMsgProtobuf msg = new ClientMsgProtobuf<>(CMsgClientPlayerNicknameList.class, EMsg.ClientPlayerNicknameList); + msg.getBody().setIncremental(true); msg.getBody().addNicknames(CMsgClientPlayerNicknameList.PlayerNickname.newBuilder().setNickname("testnickname")); return msg.serialize(); diff --git a/src/test/java/in/dragonbra/javasteam/steam/cdn/CDNClientTest.java b/src/test/java/in/dragonbra/javasteam/steam/cdn/CDNClientTest.java index 22b0d7e7d..f67a1126f 100644 --- a/src/test/java/in/dragonbra/javasteam/steam/cdn/CDNClientTest.java +++ b/src/test/java/in/dragonbra/javasteam/steam/cdn/CDNClientTest.java @@ -4,6 +4,8 @@ import in.dragonbra.javasteam.steam.steamclient.configuration.SteamConfiguration; import in.dragonbra.javasteam.types.ChunkData; import in.dragonbra.javasteam.util.SteamKitWebRequestException; +import kotlin.coroutines.EmptyCoroutineContext; +import kotlinx.coroutines.BuildersKt; import okhttp3.*; import org.jetbrains.annotations.NotNull; import org.junit.jupiter.api.Assertions; @@ -12,6 +14,7 @@ import org.junit.jupiter.params.provider.CsvSource; import java.net.InetAddress; +import java.util.Arrays; import java.util.concurrent.ExecutionException; /** @@ -78,6 +81,32 @@ public void throwsSteamKitWebExceptionOnUnsuccessfulWebResponseForChunk() { } } + @Test + public void closingOneClientLeavesTheSharedHttpClientUsable() { + OkHttpClient httpClient = new OkHttpClient.Builder() + .addInterceptor(new TeapotInterceptor()) + .build(); + + var configuration = SteamConfiguration.create(x -> x.withHttpClient(httpClient)); + var steam = new SteamClient(configuration); + var server = Server.fromHostAndPort("localhost", 80); + + // The HTTP client belongs to the configuration, closing a CDN client must not shut it down. + new Client(steam).close(); + + Assertions.assertFalse(httpClient.dispatcher().executorService().isShutdown()); + + try (var client = new Client(steam)) { + Exception exception = Assertions.assertThrows(ExecutionException.class, () -> + client.downloadManifestFuture(0, 0, 0, server).get() + ); + + // The request still reaches the server (the interceptor), it is not rejected by a dead executor. + Assertions.assertInstanceOf(SteamKitWebRequestException.class, exception.getCause()); + Assertions.assertTrue(exception.getMessage().contains("418")); + } + } + @Test public void throwsWhenNoChunkIDIsSet() { OkHttpClient httpClient = new OkHttpClient.Builder() @@ -150,6 +179,122 @@ public void throwsWhenDestinationBufferSmallerWithDepotKey() { } } + /** Answers every request with the given bytes as the body. */ + static class BodyInterceptor implements Interceptor { + private final byte[] body; + + BodyInterceptor(byte[] body) { + this.body = body; + } + + @Override + public @NotNull Response intercept(Chain chain) { + return new Response.Builder() + .code(200) + .protocol(Protocol.HTTP_1_1) + .message("OK") + .request(chain.request()) + .body(ResponseBody.create(body, null)) + .build(); + } + } + + /** Calls the suspending downloadDepotChunk and waits for it. */ + private static int downloadChunk(Client client, ChunkData chunk, byte[] destination) throws InterruptedException { + var server = Server.fromHostAndPort("localhost", 80); + return BuildersKt.runBlocking( + EmptyCoroutineContext.INSTANCE, + (scope, continuation) -> client.downloadDepotChunk(0, chunk, server, destination, null, null, null, continuation) + ); + } + + private static byte[] sequence(int length) { + var bytes = new byte[length]; + for (int i = 0; i < length; i++) { + bytes[i] = (byte) (i + 1); + } + return bytes; + } + + @Test + public void downloadsChunkIntoADestinationLongerThanTheChunk() throws InterruptedException { + var body = sequence(48); + + OkHttpClient httpClient = new OkHttpClient.Builder() + .addInterceptor(new BodyInterceptor(body)) + .build(); + + var configuration = SteamConfiguration.create(x -> x.withHttpClient(httpClient)); + var steam = new SteamClient(configuration); + try (var client = new Client(steam)) { + var chunk = new ChunkData(new byte[]{(byte) 0xFF}, 0, 0L, body.length, 64); + + // What a pooled buffer looks like: longer than the chunk, with old content in it. + var destination = new byte[100]; + Arrays.fill(destination, (byte) 0x7F); + + var written = downloadChunk(client, chunk, destination); + + Assertions.assertEquals(body.length, written); + Assertions.assertArrayEquals(body, Arrays.copyOf(destination, written)); + + // Nothing is written past the chunk. + for (int i = written; i < destination.length; i++) { + Assertions.assertEquals((byte) 0x7F, destination[i]); + } + } + } + + @Test + public void downloadsChunkIntoADestinationOfExactlyTheChunkLength() throws InterruptedException { + var body = sequence(48); + + OkHttpClient httpClient = new OkHttpClient.Builder() + .addInterceptor(new BodyInterceptor(body)) + .build(); + + var configuration = SteamConfiguration.create(x -> x.withHttpClient(httpClient)); + var steam = new SteamClient(configuration); + try (var client = new Client(steam)) { + var chunk = new ChunkData(new byte[]{(byte) 0xFF}, 0, 0L, body.length, 64); + var destination = new byte[body.length]; + + Assertions.assertEquals(body.length, downloadChunk(client, chunk, destination)); + Assertions.assertArrayEquals(body, destination); + } + } + + @Test + public void rejectsAChunkBodyOfTheWrongLength() { + OkHttpClient httpClient = new OkHttpClient.Builder() + .addInterceptor(new BodyInterceptor(sequence(40))) + .build(); + + var configuration = SteamConfiguration.create(x -> x.withHttpClient(httpClient)); + var steam = new SteamClient(configuration); + try (var client = new Client(steam)) { + // The chunk says 48 bytes, the server sends 40. The longer destination must not hide that. + var chunk = new ChunkData(new byte[]{(byte) 0xFF}, 0, 0L, 48, 64); + + Assertions.assertThrows(SteamKitWebRequestException.class, () -> downloadChunk(client, chunk, new byte[100])); + } + } + + @Test + public void rejectsADestinationShorterThanTheChunk() { + OkHttpClient httpClient = new OkHttpClient.Builder() + .addInterceptor(new BodyInterceptor(sequence(48))) + .build(); + + var configuration = SteamConfiguration.create(x -> x.withHttpClient(httpClient)); + var steam = new SteamClient(configuration); + try (var client = new Client(steam)) { + var chunk = new ChunkData(new byte[]{(byte) 0xFF}, 0, 0L, 48, 64); + + Assertions.assertThrows(IllegalArgumentException.class, () -> downloadChunk(client, chunk, new byte[47])); + } + } + @ParameterizedTest @CsvSource({ "10.0.0.1, true", // Private IPv4 (10.0.0.0/8) diff --git a/src/test/java/in/dragonbra/javasteam/steam/cdn/DepotChunkTest.java b/src/test/java/in/dragonbra/javasteam/steam/cdn/DepotChunkTest.java index bf05e6ab7..2040c441e 100644 --- a/src/test/java/in/dragonbra/javasteam/steam/cdn/DepotChunkTest.java +++ b/src/test/java/in/dragonbra/javasteam/steam/cdn/DepotChunkTest.java @@ -2,15 +2,34 @@ import in.dragonbra.javasteam.TestBase; import in.dragonbra.javasteam.types.ChunkData; +import in.dragonbra.javasteam.util.Adler32; import in.dragonbra.javasteam.util.stream.MemoryStream; import org.apache.commons.io.IOUtils; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.binary.Hex; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import javax.crypto.Cipher; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.util.Random; +import java.util.zip.CRC32; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.security.Provider; +import java.security.Security; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Stream; public class DepotChunkTest extends TestBase { @@ -133,4 +152,215 @@ public void decryptsAndDecompressesDepotChunkZStd() throws IOException, NoSuchAl Assertions.assertEquals("9E72678E305540630A665B93E1463BC3983EB55A", hash); } + + // region In-place decryption and oversized (pooled) buffers + + /** A chunk from the test resources. The SHA-1 of its content is its chunk id, which is in the file name. */ + private static final class Fixture { + final String name; + final String resource; + final ChunkData chunk; + final byte[] depotKey; + final String sha1; + + Fixture(String name, String resource, int checksum, int compressedLength, int uncompressedLength, String depotKey, String sha1) { + this.name = name; + this.resource = resource; + this.chunk = new ChunkData(new byte[0], checksum, 0, compressedLength, uncompressedLength); + this.depotKey = unhex(depotKey); + this.sha1 = sha1; + } + + @Override + public String toString() { + return name; + } + } + + private static byte[] unhex(String hex) { + try { + return Hex.decodeHex(hex); + } catch (DecoderException e) { + throw new IllegalArgumentException(e); + } + } + + private static final List FIXTURES = List.of( + new Fixture( + "PKZip", + "depot/depot_440_chunk_bac8e2657470b2eb70d6ddcd6c07004be8738697.bin", + 2130218374, 320, 544, + "44CE5C5297A415A1A6F69C856037A5A2FDD82CD474FA659EDFB4D59B2ABC55FC", + "BAC8E2657470B2EB70D6DDCD6C07004BE8738697" + ), + new Fixture( + "LZMA", + "depot/depot_232250_chunk_7b8567d9b3c09295cdbf4978c32b348d8e76c750.bin", + Integer.parseUnsignedInt("2894626744"), 304, 798, + "E5F6AED55E9ECE429E56B813FBF6BFE924F3CF72972FDBD0571FFCAD9F2F7DAA", + "7B8567D9B3C09295CDBF4978C32B348D8E76C750" + ), + new Fixture( + "Zstd", + "depot/depot_3441461_chunk_9e72678e305540630a665b93e1463bc3983eb55a.bin", + Integer.parseUnsignedInt("3753325726"), 176, 156, + "0102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F20", + "9E72678E305540630A665B93E1463BC3983EB55A" + ) + ); + + /** Every chunk kind, on the platform provider and on the Bouncy Castle fallback. */ + static Stream chunksAndProviders() { + var platform = Security.getProvider("SunJCE"); + Assertions.assertNotNull(platform, "This test expects to run on a JVM with the SunJCE provider."); + + var providers = List.of(platform, new BouncyCastleProvider()); + + return FIXTURES.stream().flatMap(fixture -> + providers.stream().map(provider -> Arguments.of(fixture, provider)) + ); + } + + private byte[] load(Fixture fixture) throws IOException { + try (var stream = getClass().getClassLoader().getResourceAsStream(fixture.resource)) { + Assertions.assertNotNull(stream, fixture.resource); + var data = IOUtils.toByteArray(stream); + Assertions.assertEquals(fixture.chunk.getCompressedLength(), data.length); + return data; + } + } + + private static String sha1(byte[] data, int length) throws NoSuchAlgorithmException { + var digest = MessageDigest.getInstance("SHA-1"); + digest.update(data, 0, length); + return Hex.encodeHexString(digest.digest(), false); + } + + @ParameterizedTest(name = "{0} with {1}") + @MethodSource("chunksAndProviders") + public void decryptsInPlace(Fixture fixture, Provider provider) throws IOException, NoSuchAlgorithmException { + var data = load(fixture); + var destination = new byte[fixture.chunk.getUncompressedLength()]; + + var written = DepotChunk.processWithProvider(fixture.chunk, data, data.length, destination, fixture.depotKey, provider); + + Assertions.assertEquals(fixture.chunk.getUncompressedLength(), written); + Assertions.assertEquals(fixture.sha1, sha1(destination, written)); + } + + @ParameterizedTest(name = "{0} with {1}") + @MethodSource("chunksAndProviders") + public void processesChunkInBuffersLongerThanTheData(Fixture fixture, Provider provider) throws IOException, NoSuchAlgorithmException { + var chunkData = load(fixture); + + // What pooled buffers look like: longer than the data, with old content after (and under) it. + var data = new byte[chunkData.length + 1000]; + Arrays.fill(data, (byte) 0x5A); + System.arraycopy(chunkData, 0, data, 0, chunkData.length); + + var destination = new byte[fixture.chunk.getUncompressedLength() + 1000]; + Arrays.fill(destination, (byte) 0x5A); + + var written = DepotChunk.processWithProvider(fixture.chunk, data, chunkData.length, destination, fixture.depotKey, provider); + + Assertions.assertEquals(fixture.chunk.getUncompressedLength(), written); + Assertions.assertEquals(fixture.sha1, sha1(destination, written)); + + // Nothing is written past the data, in either buffer. + for (int i = chunkData.length; i < data.length; i++) { + Assertions.assertEquals((byte) 0x5A, data[i], "data[" + i + "]"); + } + for (int i = written; i < destination.length; i++) { + Assertions.assertEquals((byte) 0x5A, destination[i], "destination[" + i + "]"); + } + } + + @Test + public void lengthOverloadUsesOnlyTheGivenLength() throws IOException, NoSuchAlgorithmException { + // The public overload, with whichever provider the library picks. + for (var fixture : FIXTURES) { + var chunkData = load(fixture); + var data = Arrays.copyOf(chunkData, chunkData.length + 333); + var destination = new byte[fixture.chunk.getUncompressedLength() + 333]; + + var written = DepotChunk.process(fixture.chunk, data, chunkData.length, destination, fixture.depotKey); + + Assertions.assertEquals(fixture.sha1, sha1(destination, written), fixture.name); + } + } + + static Stream providers() { + return Stream.of(Security.getProvider("SunJCE"), new BouncyCastleProvider()); + } + + /** + * The fixtures are a few hundred bytes. Real chunks are up to 1 MiB, which a provider decrypts in + * several pieces, so this is where an in-place decryption that is not copy-safe would show. + */ + @ParameterizedTest(name = "{0}") + @MethodSource("providers") + public void decryptsAFullSizeChunkInPlace(Provider provider) throws Exception { + var content = new byte[1024 * 1024]; + new Random(1234).nextBytes(content); + + // A PKZip chunk, stored, so the decrypted data is as long as a chunk can be. + var zipped = new ByteArrayOutputStream(); + try (var zip = new ZipOutputStream(zipped)) { + var crc = new CRC32(); + crc.update(content); + + var entry = new ZipEntry("z"); + entry.setMethod(ZipEntry.STORED); + entry.setSize(content.length); + entry.setCompressedSize(content.length); + entry.setCrc(crc.getValue()); + + zip.putNextEntry(entry); + zip.write(content); + zip.closeEntry(); + } + + var depotKey = FIXTURES.get(0).depotKey; + var keySpec = new SecretKeySpec(depotKey, "AES"); + + var iv = new byte[16]; + new Random(5678).nextBytes(iv); + + var ecb = Cipher.getInstance("AES/ECB/NoPadding"); + ecb.init(Cipher.ENCRYPT_MODE, keySpec); + + var cbc = Cipher.getInstance("AES/CBC/PKCS5Padding"); + cbc.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(iv)); + + var encrypted = new ByteArrayOutputStream(); + encrypted.write(ecb.doFinal(iv)); + encrypted.write(cbc.doFinal(zipped.toByteArray())); + + var chunkData = encrypted.toByteArray(); + var chunk = new ChunkData(new byte[0], Adler32.calculate(content), 0, chunkData.length, content.length); + + // Exactly sized, and in a longer buffer. + for (int extra : new int[]{0, 4096}) { + var data = Arrays.copyOf(chunkData, chunkData.length + extra); + var destination = new byte[content.length + extra]; + + var written = DepotChunk.processWithProvider(chunk, data, chunkData.length, destination, depotKey, provider); + + Assertions.assertEquals(content.length, written); + Assertions.assertArrayEquals(content, Arrays.copyOf(destination, written)); + } + } + + @Test + public void rejectsALengthOutsideTheData() { + var fixture = FIXTURES.get(0); + var destination = new byte[fixture.chunk.getUncompressedLength()]; + + Assertions.assertThrows(IllegalArgumentException.class, () -> + DepotChunk.process(fixture.chunk, new byte[320], 321, destination, fixture.depotKey)); + Assertions.assertThrows(IllegalArgumentException.class, () -> + DepotChunk.process(fixture.chunk, new byte[320], 15, destination, fixture.depotKey)); + } + + // endregion } diff --git a/src/test/java/in/dragonbra/javasteam/steam/handlers/steamfriends/SteamFriendsTest.java b/src/test/java/in/dragonbra/javasteam/steam/handlers/steamfriends/SteamFriendsTest.java index 4c6e36ac9..5cfa431da 100644 --- a/src/test/java/in/dragonbra/javasteam/steam/handlers/steamfriends/SteamFriendsTest.java +++ b/src/test/java/in/dragonbra/javasteam/steam/handlers/steamfriends/SteamFriendsTest.java @@ -10,6 +10,7 @@ import in.dragonbra.javasteam.protobufs.steamclient.SteammessagesClientserver2.CMsgClientChatGetFriendMessageHistory; import in.dragonbra.javasteam.protobufs.steamclient.SteammessagesClientserver2.CMsgClientChatGetFriendMessageHistoryForOfflineMessages; import in.dragonbra.javasteam.protobufs.steamclient.SteammessagesClientserverFriends.*; +import in.dragonbra.javasteam.steam.CMClient; import in.dragonbra.javasteam.steam.handlers.HandlerTestBase; import in.dragonbra.javasteam.steam.handlers.steamfriends.callback.*; import in.dragonbra.javasteam.types.SteamID; @@ -334,6 +335,51 @@ public void handlePersonaState() { assertEquals("klay", callback.getName()); } + private static IPacketMsg personaStatePacket(SteamID friendId, EnumSet flags, Integer personaState) { + ClientMsgProtobuf msg = + new ClientMsgProtobuf<>(CMsgClientPersonaState.class, EMsg.ClientPersonaState); + + msg.getBody().setStatusFlags(EClientPersonaStateFlag.code(flags)); + + CMsgClientPersonaState.Friend.Builder friend = CMsgClientPersonaState.Friend.newBuilder() + .setFriendid(friendId.convertToUInt64()) + .setPlayerName("testfriend"); + if (personaState != null) { + friend.setPersonaState(personaState); + } + msg.getBody().addFriends(friend); + + return CMClient.getPacketMsg(msg.serialize()); + } + + @Test + public void personaStateWithoutStateDoesNotResetCachedState() { + SteamID friendId = new SteamID(76561197960287930L); + EnumSet flags = EnumSet.of( + EClientPersonaStateFlag.Status, + EClientPersonaStateFlag.PlayerName, + EClientPersonaStateFlag.Presence, + EClientPersonaStateFlag.GameDataBlob + ); + + // A genuine presence push: persona_state is present and Online. + handler.handleMsg(personaStatePacket(friendId, flags, EPersonaState.Online.code())); + + PersonaStateCallback online = verifyCallback(); + assertTrue(online.getHasPersonaState()); + assertEquals(EPersonaState.Online, online.getState()); + assertEquals(EPersonaState.Online, handler.getFriendPersonaState(friendId)); + + // A reply to ClientRequestFriendData: same flags, but persona_state absent on the wire. + handler.handleMsg(personaStatePacket(friendId, flags, null)); + + PersonaStateCallback profileOnly = verifyCallback(); + assertFalse(profileOnly.getHasPersonaState()); + assertEquals(EPersonaState.Offline, profileOnly.getState()); // unchanged default, kept for compatibility + assertEquals("testfriend", profileOnly.getName()); + assertEquals(EPersonaState.Online, handler.getFriendPersonaState(friendId)); // cache must keep Online + } + @Test public void handleClanState() { IPacketMsg msg = getPacket(EMsg.ClientClanState, true); @@ -464,6 +510,8 @@ public void handleNicknameList() { NicknameListCallback callback = verifyCallback(); + assertTrue(callback.isIncremental()); + assertFalse(callback.isRemoval()); assertEquals(1, callback.getNicknames().size()); assertEquals("testnickname", callback.getNicknames().get(0).getNickname()); } diff --git a/src/test/java/in/dragonbra/javasteam/types/AsyncJobTest.kt b/src/test/java/in/dragonbra/javasteam/types/AsyncJobTest.kt index f9a2f9402..63175bffb 100644 --- a/src/test/java/in/dragonbra/javasteam/types/AsyncJobTest.kt +++ b/src/test/java/in/dragonbra/javasteam/types/AsyncJobTest.kt @@ -2,6 +2,7 @@ package `in`.dragonbra.javasteam.types import `in`.dragonbra.javasteam.ConnectedSteamClient import `in`.dragonbra.javasteam.steam.steamclient.AsyncJobFailedException +import `in`.dragonbra.javasteam.steam.steamclient.AsyncJobTimeoutException import `in`.dragonbra.javasteam.steam.steamclient.SteamClient import `in`.dragonbra.javasteam.steam.steamclient.callbackmgr.CallbackMsg import kotlinx.coroutines.CancellationException @@ -669,7 +670,9 @@ class AsyncJobTest { asyncJob.setFailed(false) - Assertions.assertThrows(CancellationException::class.java) { asyncJob.runBlock() } + Assertions.assertThrows(AsyncJobTimeoutException::class.java) { asyncJob.runBlock() } + Assertions.assertTrue(asyncJob.toFuture().isCancelled, "A timed out job should still be canceled") + Assertions.assertThrows(AsyncJobTimeoutException::class.java) { runBlocking { asyncJob.await() } } } @Test @@ -690,7 +693,9 @@ class AsyncJobTest { asyncJob.setFailed(false) - Assertions.assertThrows(CancellationException::class.java) { asyncJob.runBlock() } + Assertions.assertThrows(AsyncJobTimeoutException::class.java) { asyncJob.runBlock() } + Assertions.assertTrue(asyncJob.toFuture().isCancelled, "A timed out job should still be canceled") + Assertions.assertThrows(AsyncJobTimeoutException::class.java) { runBlocking { asyncJob.await() } } } @Test diff --git a/src/test/java/in/dragonbra/javasteam/util/Adler32Test.java b/src/test/java/in/dragonbra/javasteam/util/Adler32Test.java index edd4dd9e0..f26a1ef64 100644 --- a/src/test/java/in/dragonbra/javasteam/util/Adler32Test.java +++ b/src/test/java/in/dragonbra/javasteam/util/Adler32Test.java @@ -33,6 +33,28 @@ void matchesReference(int length) { Assertions.assertEquals(expected, actual); } + @ParameterizedTest + @ValueSource(ints = {0, 1, 15, 16, 17, 1024, 5552 - 1, 5552, 5552 + 1, 5552 * 2 + 3}) + void rangeMatchesCopyOfRange(int length) { + final var seed = 0; + final var offset = 7; + var data = new byte[offset + length + 11]; + new Random().nextBytes(data); + + var expected = referenceImplementation(seed, Arrays.copyOfRange(data, offset, offset + length)); + var actual = Adler32.calculate(seed, data, offset, length); + + Assertions.assertEquals(expected, actual); + } + + @Test + void rangeOutsideBufferThrows() { + var data = new byte[16]; + + Assertions.assertThrows(IllegalArgumentException.class, () -> Adler32.calculate(0, data, 8, 9)); + Assertions.assertThrows(IllegalArgumentException.class, () -> Adler32.calculate(0, data, -1, 4)); + } + @ParameterizedTest @ValueSource(strings = {"a", "Wikipedia", "123456789", "SteamKit is good software, you should use it. :)"}) void matchesKnownVectors(String input) { @@ -67,6 +89,81 @@ void noOverflowWithMaxBytes() { Assertions.assertEquals(expected, actual); } + /** Byte by byte, with both halves of the seed, the way the checksum is defined. */ + private static int seededReference(int seed, byte[] input, int offset, int length) { + long a = seed & 0xFFFF; + long b = (seed >>> 16) & 0xFFFF; + + for (int i = offset; i < offset + length; i++) { + a = (a + (input[i] & 0xFF)) % 65521; + b = (b + a) % 65521; + } + + return (int) ((b << 16) | a); + } + + @ParameterizedTest + @ValueSource(ints = { + 0, // what Steam uses + 1, // standard Adler-32 + 0x00010000, // high half only + 0x12345678, // both halves + 0xFFF0FFF0, // 65520, the largest reduced value, in both halves + 0xFFFFFFFF, // halves that are not reduced + 0xFFF10000, // 65521 in the high half + }) + void matchesReferenceForAnySeed(int seed) { + // Lengths around the modulus, and a chunk-sized one that is several times above it. + for (int length : new int[]{1, 2, 255, 65520, 65521, 65522, 2 * 65521, 1024 * 1024, 1024 * 1024 + 13}) { + var data = new byte[length + 5]; + new Random(length).nextBytes(data); + + Assertions.assertEquals( + seededReference(seed, data, 5, length), + Adler32.calculate(seed, data, 5, length), + "seed " + Integer.toHexString(seed) + ", length " + length + ); + } + } + + @Test + void matchesReferenceForWorstCaseData() { + // All 0xFF gives the largest sums. + var data = new byte[1024 * 1024]; + Arrays.fill(data, (byte) 0xFF); + + for (int seed : new int[]{0, 1, 0xFFF0FFF0, 0xFFFFFFFF}) { + Assertions.assertEquals(seededReference(seed, data, 0, data.length), Adler32.calculate(seed, data)); + } + } + + @ParameterizedTest + @ValueSource(ints = {0, 1}) + void continuingAChecksumMatchesOnePass(int seed) { + var data = new byte[300_000]; + new Random(99).nextBytes(data); + + var expected = Adler32.calculate(seed, data); + + for (int split : new int[]{0, 1, 16, 5552, 65521, 150_000, data.length - 1, data.length}) { + var first = Adler32.calculate(seed, data, 0, split); + var actual = Adler32.calculate(first, data, split, data.length - split); + + Assertions.assertEquals(expected, actual, "split at " + split); + } + } + + @Test + void seedOneMatchesZlib() { + var data = new byte[70_000]; + new Random(7).nextBytes(data); + + var zlib = new java.util.zip.Adler32(); + zlib.update(data, 3, 60_000); + + Assertions.assertEquals((int) zlib.getValue(), Adler32.calculate(1, data, 3, 60_000)); + } + // Additional benchmarking @SuppressWarnings("ResultOfMethodCallIgnored") @@ -171,7 +268,7 @@ void benchmarkVariousSizes() { int iterations = Math.max(1000, baseIterations / (size / 16)); // Warmup - for (int i = 0; i < Math.min(100, iterations / 10); i++) { + for (int i = 0; i < 100; i++) { referenceImplementation(data); Adler32.calculate(data); } diff --git a/src/test/java/in/dragonbra/javasteam/util/VZstdUtilTest.java b/src/test/java/in/dragonbra/javasteam/util/VZstdUtilTest.java new file mode 100644 index 000000000..6caf36f84 --- /dev/null +++ b/src/test/java/in/dragonbra/javasteam/util/VZstdUtilTest.java @@ -0,0 +1,240 @@ +package in.dragonbra.javasteam.util; + +import com.github.luben.zstd.Zstd; +import in.dragonbra.javasteam.TestBase; +import org.apache.commons.codec.binary.Hex; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Random; +import java.util.concurrent.Callable; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +public class VZstdUtilTest extends TestBase { + + /** + * The decrypted payload of depot/depot_3441461_chunk_9e72678e305540630a665b93e1463bc3983eb55a.bin, + * which is the VZstd data as Steam serves it. + */ + private static final String REAL_CHUNK = "depot/depot_3441461_chunk_9e72678e305540630a665b93e1463bc3983eb55a.vzstd"; + + private static final int REAL_CHUNK_SIZE = 156; + + private static final String REAL_CHUNK_SHA1 = "9E72678E305540630A665B93E1463BC3983EB55A"; + + // Disabled: the full-size real chunk is not in the repository, because it is licensed third-party + // content (a 729,103 byte slice of the VC 2022 Redist that decompresses to 1 MB). To run this + // locally, fetch it and place it under src/test/resources/depot without committing it. + // App 228980 (Steamworks Common Redistributables), depot 228989, + // manifest 5753583882400741046, chunk f6da62a3fd9d7a92184404b5752537918965037c. + // A chunk ID is the SHA-1 of the decompressed chunk. + // private static final String FULL_CHUNK = "depot/depot_228989_chunk_f6da62a3fd9d7a92184404b5752537918965037c.vzstd"; + + // private static final int FULL_CHUNK_SIZE = 1024 * 1024; + + // private static final String FULL_CHUNK_SHA1 = "F6DA62A3FD9D7A92184404B5752537918965037C"; + + @Test + public void decompressesRealChunk() throws IOException, NoSuchAlgorithmException { + var data = readResource(REAL_CHUNK); + var destination = new byte[REAL_CHUNK_SIZE]; + + var written = VZstdUtil.decompress(data, destination, true); + + Assertions.assertEquals(REAL_CHUNK_SIZE, written); + Assertions.assertEquals(REAL_CHUNK_SHA1, sha1(destination)); + } + + // @Test + // public void decompressesFullSizeRealChunk() throws IOException, NoSuchAlgorithmException { + // var data = readResource(FULL_CHUNK); + // Assertions.assertEquals(729103, data.length); + // var destination = new byte[FULL_CHUNK_SIZE]; + // + // // Twice, so the second pass runs on a buffer taken back from the pool. + // for (int i = 0; i < 2; i++) { + // Arrays.fill(destination, (byte) 0); + // var written = VZstdUtil.decompress(data, destination, true); + // + // Assertions.assertEquals(FULL_CHUNK_SIZE, written); + // Assertions.assertEquals(FULL_CHUNK_SHA1, sha1(destination)); + // } + // } + + @Test + public void decompressesRealChunkRepeatedly() throws IOException, NoSuchAlgorithmException { + var data = readResource(REAL_CHUNK); + + // Every call after the first one gets its input buffer back from the pool. + for (int i = 0; i < 100; i++) { + var destination = new byte[REAL_CHUNK_SIZE]; + Assertions.assertEquals(REAL_CHUNK_SIZE, VZstdUtil.decompress(data, destination, true)); + Assertions.assertEquals(REAL_CHUNK_SHA1, sha1(destination)); + } + } + + @Test + public void honorsLengthWhenBufferIsLarger() throws IOException, NoSuchAlgorithmException { + var data = readResource(REAL_CHUNK); + var padded = Arrays.copyOf(data, data.length + 64); + Arrays.fill(padded, data.length, padded.length, (byte) 0x7F); + var destination = new byte[REAL_CHUNK_SIZE + 32]; + + var written = VZstdUtil.decompress(padded, destination, true, data.length); + + Assertions.assertEquals(REAL_CHUNK_SIZE, written); + Assertions.assertEquals(REAL_CHUNK_SHA1, sha1(Arrays.copyOf(destination, written))); + } + + @Test + public void decompressesChunkLargerThanTheInputBuffer() throws IOException { + // 1 MB like a full depot chunk. The compressed data spans several fills of the pooled + // input buffer and the output spans several 64 KB reads. + var expected = chunkContent(1024 * 1024, 42); + var data = wrap(expected); + Assertions.assertTrue(data.length > 4 * 128 * 1024, "compressed data should span several input buffers"); + + var destination = new byte[expected.length]; + var written = VZstdUtil.decompress(data, destination, true); + + Assertions.assertEquals(expected.length, written); + Assertions.assertArrayEquals(expected, destination); + } + + @Test + public void decompressesInParallel() throws Exception { + var threads = 8; + var executor = Executors.newFixedThreadPool(threads); + try { + var futures = new ArrayList>(); + for (int t = 0; t < threads; t++) { + // Different content per thread, so a buffer shared between two streams shows up as wrong bytes. + var expected = chunkContent(300_000 + t * 10_000, t); + var data = wrap(expected); + Callable task = () -> { + var destination = new byte[expected.length]; + for (int i = 0; i < 50; i++) { + Arrays.fill(destination, (byte) 0); + if (VZstdUtil.decompress(data, destination, true) != expected.length || + !Arrays.equals(expected, destination)) { + return false; + } + } + return true; + }; + futures.add(executor.submit(task)); + } + + for (var future : futures) { + Assertions.assertTrue(future.get()); + } + } finally { + executor.shutdownNow(); + } + } + + @Test + public void recoversAfterCorruptData() throws IOException { + var expected = chunkContent(400_000, 7); + var data = wrap(expected); + var destination = new byte[expected.length]; + + // Break the Zstd frame magic, so the stream fails on its first read. + var badFrame = data.clone(); + badFrame[8] ^= 0x55; + Assertions.assertThrows(IOException.class, () -> VZstdUtil.decompress(badFrame, destination, false)); + + // Damage in the middle of the frame, after the stream has already produced output. + var corrupt = data.clone(); + Arrays.fill(corrupt, 200_000, 200_064, (byte) 0xFF); + Assertions.assertThrows(IOException.class, () -> VZstdUtil.decompress(corrupt, destination, true)); + + // Keep the footer, drop the second half of the frame. + var cut = data.length / 2; + var shortened = new byte[cut + 15]; + System.arraycopy(data, 0, shortened, 0, cut); + System.arraycopy(data, data.length - 15, shortened, cut, 15); + Assertions.assertThrows(IOException.class, () -> VZstdUtil.decompress(shortened, destination, false)); + + // The buffer handed back by the failed streams must still be usable. + Arrays.fill(destination, (byte) 0); + Assertions.assertEquals(expected.length, VZstdUtil.decompress(data, destination, true)); + Assertions.assertArrayEquals(expected, destination); + } + + @Test + public void rejectsBadHeaderFooterAndSizes() throws IOException { + var data = readResource(REAL_CHUNK); + var destination = new byte[REAL_CHUNK_SIZE]; + + var badHeader = data.clone(); + badHeader[0] = 'X'; + Assertions.assertThrows(IOException.class, () -> VZstdUtil.decompress(badHeader, destination)); + + var badFooter = data.clone(); + badFooter[badFooter.length - 1] = 'X'; + Assertions.assertThrows(IOException.class, () -> VZstdUtil.decompress(badFooter, destination)); + + Assertions.assertThrows(IOException.class, () -> VZstdUtil.decompress(new byte[22], destination)); + Assertions.assertThrows( + IllegalArgumentException.class, + () -> VZstdUtil.decompress(data, new byte[REAL_CHUNK_SIZE - 1]) + ); + Assertions.assertThrows( + IllegalArgumentException.class, + () -> VZstdUtil.decompress(data, destination, false, data.length + 1) + ); + + var badCrc = data.clone(); + badCrc[badCrc.length - 15] ^= 0x01; + Assertions.assertThrows(IOException.class, () -> VZstdUtil.decompress(badCrc, destination, true)); + } + + private byte[] readResource(String name) throws IOException { + try (var stream = getClass().getClassLoader().getResourceAsStream(name)) { + Assertions.assertNotNull(stream, name); + return stream.readAllBytes(); + } + } + + private static String sha1(byte[] data) throws NoSuchAlgorithmException { + return Hex.encodeHexString(MessageDigest.getInstance("SHA-1").digest(data), false); + } + + /** + * Pseudo random bytes that compress to about three quarters of their size. + */ + private static byte[] chunkContent(int size, long seed) { + var content = new byte[size]; + new Random(seed).nextBytes(content); + for (int i = 0; i < content.length; i++) { + content[i] &= 0x3F; + } + return content; + } + + /** + * Wraps data the way Steam does: "VSZa", CRC32, the Zstd frame, CRC32, decompressed size, 4 unused bytes, "zsv". + */ + private static byte[] wrap(byte[] content) { + var frame = Zstd.compress(content, 3); + var crc = (int) Utils.crc32(content); + var buffer = ByteBuffer.allocate(8 + frame.length + 15).order(ByteOrder.LITTLE_ENDIAN); + buffer.putInt(0x615A5356); + buffer.putInt(crc); + buffer.put(frame); + buffer.putInt(crc); + buffer.putInt(content.length); + buffer.putInt(0); + buffer.put(new byte[]{'z', 's', 'v'}); + return buffer.array(); + } +} diff --git a/src/test/resources/depot/depot_3441461_chunk_9e72678e305540630a665b93e1463bc3983eb55a.vzstd b/src/test/resources/depot/depot_3441461_chunk_9e72678e305540630a665b93e1463bc3983eb55a.vzstd new file mode 100644 index 000000000..e538491cc Binary files /dev/null and b/src/test/resources/depot/depot_3441461_chunk_9e72678e305540630a665b93e1463bc3983eb55a.vzstd differ